diff --git a/build/NuSpecs/UmbracoCms.Core.nuspec b/build/NuSpecs/UmbracoCms.Core.nuspec index 477bb143f9..ce8f3aae44 100644 --- a/build/NuSpecs/UmbracoCms.Core.nuspec +++ b/build/NuSpecs/UmbracoCms.Core.nuspec @@ -71,7 +71,6 @@ - @@ -79,7 +78,6 @@ - @@ -87,7 +85,6 @@ - diff --git a/src/Umbraco.Configuration/AspNetCoreConfigsFactory.cs b/src/Umbraco.Configuration/AspNetCoreConfigsFactory.cs deleted file mode 100644 index 0cacab9e1d..0000000000 --- a/src/Umbraco.Configuration/AspNetCoreConfigsFactory.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Configuration.Models; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.HealthChecks; -using Umbraco.Core.Configuration.UmbracoSettings; -using ConnectionStrings = Umbraco.Configuration.Models.ConnectionStrings; -using CoreDebugSettings = Umbraco.Configuration.Models.CoreDebugSettings; - -namespace Umbraco.Configuration -{ - public class AspNetCoreConfigsFactory : IConfigsFactory - { - private readonly IConfiguration _configuration; - - public AspNetCoreConfigsFactory(IConfiguration configuration) - { - _configuration = configuration ?? throw new System.ArgumentNullException(nameof(configuration)); - } - - public Configs Create() - { - var configs = new Configs(); - - configs.Add(() => new TourSettings(_configuration)); - configs.Add(() => new CoreDebugSettings(_configuration)); - configs.Add(() => new RequestHandlerSettings(_configuration)); - configs.Add(() => new SecuritySettings(_configuration)); - configs.Add(() => new UserPasswordConfigurationSettings(_configuration)); - configs.Add(() => new MemberPasswordConfigurationSettings(_configuration)); - configs.Add(() => new KeepAliveSettings(_configuration)); - configs.Add(() => new ContentSettings(_configuration)); - configs.Add(() => new HealthChecksSettings(_configuration)); - configs.Add(() => new LoggingSettings(_configuration)); - configs.Add(() => new ExceptionFilterSettings(_configuration)); - configs.Add(() => new ActiveDirectorySettings(_configuration)); - configs.Add(() => new RuntimeSettings(_configuration)); - configs.Add(() => new TypeFinderSettings(_configuration)); - configs.Add(() => new NuCacheSettings(_configuration)); - configs.Add(() => new WebRoutingSettings(_configuration)); - configs.Add(() => new IndexCreatorSettings(_configuration)); - configs.Add(() => new ModelsBuilderConfig(_configuration)); - configs.Add(() => new HostingSettings(_configuration)); - configs.Add(() => new GlobalSettings(_configuration)); - configs.Add(() => new ConnectionStrings(_configuration)); - configs.Add(() => new ImagingSettings(_configuration)); - - return configs; - } - } -} diff --git a/src/Umbraco.Configuration/ConfigsFactory.cs b/src/Umbraco.Configuration/ConfigsFactory.cs deleted file mode 100644 index be6cee2d0c..0000000000 --- a/src/Umbraco.Configuration/ConfigsFactory.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Umbraco.Configuration; -using Umbraco.Configuration.Implementations; -using Umbraco.Configuration.Legacy; -using Umbraco.Core.Configuration.HealthChecks; -using Umbraco.Core.Configuration.Legacy; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Core.Configuration -{ - public class ConfigsFactory : IConfigsFactory - { - public IHostingSettings HostingSettings { get; } = new HostingSettings(); - public ICoreDebugSettings CoreDebugSettings { get; } = new CoreDebugSettings(); - public IIndexCreatorSettings IndexCreatorSettings { get; } = new IndexCreatorSettings(); - public INuCacheSettings NuCacheSettings { get; } = new NuCacheSettings(); - public ITypeFinderSettings TypeFinderSettings { get; } = new TypeFinderSettings(); - public IRuntimeSettings RuntimeSettings { get; } = new RuntimeSettings(); - public IActiveDirectorySettings ActiveDirectorySettings { get; } = new ActiveDirectorySettings(); - public IExceptionFilterSettings ExceptionFilterSettings { get; } = new ExceptionFilterSettings(); - public ITourSettings TourSettings { get; } = new TourSettings(); - public ILoggingSettings LoggingSettings { get; } = new LoggingSettings(); - public IKeepAliveSettings KeepAliveSettings { get; } = new KeepAliveSettings(); - public IWebRoutingSettings WebRoutingSettings { get; } = new WebRoutingSettings(); - public IRequestHandlerSettings RequestHandlerSettings { get; } = new RequestHandlerSettings(); - public ISecuritySettings SecuritySettings { get; } = new SecuritySettings(); - public IUserPasswordConfiguration UserPasswordConfigurationSettings { get; } = new UserPasswordConfigurationSettings(); - public IMemberPasswordConfiguration MemberPasswordConfigurationSettings { get; } = new MemberPasswordConfigurationSettings(); - public IContentSettings ContentSettings { get; } = new ContentSettings(); - public IGlobalSettings GlobalSettings { get; } = new GlobalSettings(); - public IHealthChecksSettings HealthChecksSettings { get; } = new HealthChecksSettings(); - public IConnectionStrings ConnectionStrings { get; } = new ConnectionStrings(); - public IModelsBuilderConfig ModelsBuilderConfig { get; } = new ModelsBuilderConfig(); - - public Configs Create() - { - var configs = new Configs(); - - configs.Add(() => GlobalSettings); - configs.Add(() => HostingSettings); - configs.Add(() => HealthChecksSettings); - configs.Add(() => CoreDebugSettings); - configs.Add(() => ConnectionStrings); - configs.Add(() => ModelsBuilderConfig); - configs.Add(() => IndexCreatorSettings); - configs.Add(() => NuCacheSettings); - configs.Add(() => TypeFinderSettings); - configs.Add(() => RuntimeSettings); - configs.Add(() => ActiveDirectorySettings); - configs.Add(() => ExceptionFilterSettings); - configs.Add(() => TourSettings); - configs.Add(() => LoggingSettings); - configs.Add(() => KeepAliveSettings); - configs.Add(() => WebRoutingSettings); - configs.Add(() => RequestHandlerSettings); - configs.Add(() => SecuritySettings); - configs.Add(() => UserPasswordConfigurationSettings); - configs.Add(() => MemberPasswordConfigurationSettings); - configs.Add(() => ContentSettings); - - return configs; - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/DisabledHealthCheckElement.cs b/src/Umbraco.Configuration/HealthChecks/DisabledHealthCheckElement.cs deleted file mode 100644 index 01392da614..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/DisabledHealthCheckElement.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; -using System.Text; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public class DisabledHealthCheckElement : ConfigurationElement, IDisabledHealthCheck - { - private const string IdKey = "id"; - private const string DisabledOnKey = "disabledOn"; - private const string DisabledByKey = "disabledBy"; - - [ConfigurationProperty(IdKey, IsKey = true, IsRequired = true)] - public Guid Id - { - get - { - return ((Guid)(base[IdKey])); - } - } - - [ConfigurationProperty(DisabledOnKey, IsKey = false, IsRequired = false)] - public DateTime DisabledOn - { - get - { - return ((DateTime)(base[DisabledOnKey])); - } - } - - [ConfigurationProperty(DisabledByKey, IsKey = false, IsRequired = false)] - public int DisabledBy - { - get - { - return ((int)(base[DisabledByKey])); - } - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/DisabledHealthChecksElementCollection.cs b/src/Umbraco.Configuration/HealthChecks/DisabledHealthChecksElementCollection.cs deleted file mode 100644 index 87600b8ae3..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/DisabledHealthChecksElementCollection.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - [ConfigurationCollection(typeof(DisabledHealthCheckElement), AddItemName = "check")] - public class DisabledHealthChecksElementCollection : ConfigurationElementCollection, IEnumerable - { - protected override ConfigurationElement CreateNewElement() - { - return new DisabledHealthCheckElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((DisabledHealthCheckElement)(element)).Id; - } - - public new DisabledHealthCheckElement this[string key] - { - get - { - return (DisabledHealthCheckElement)BaseGet(key); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as DisabledHealthCheckElement; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/HealthCheckNotificationSettingsElement.cs b/src/Umbraco.Configuration/HealthChecks/HealthCheckNotificationSettingsElement.cs deleted file mode 100644 index 1ccf3e357b..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/HealthCheckNotificationSettingsElement.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public class HealthCheckNotificationSettingsElement : ConfigurationElement, IHealthCheckNotificationSettings - { - private const string EnabledKey = "enabled"; - private const string FirstRunTimeKey = "firstRunTime"; - private const string PeriodKey = "periodInHours"; - private const string NotificationMethodsKey = "notificationMethods"; - private const string DisabledChecksKey = "disabledChecks"; - - [ConfigurationProperty(EnabledKey, IsRequired = true)] - public bool Enabled - { - get - { - return (bool)base[EnabledKey]; - } - } - - [ConfigurationProperty(FirstRunTimeKey, IsRequired = false)] - public string FirstRunTime - { - get - { - return (string)base[FirstRunTimeKey]; - } - } - - [ConfigurationProperty(PeriodKey, IsRequired = true)] - public int PeriodInHours - { - get - { - return (int)base[PeriodKey]; - } - } - - [ConfigurationProperty(NotificationMethodsKey, IsDefaultCollection = true, IsRequired = false)] - public NotificationMethodsElementCollection NotificationMethods - { - get - { - return (NotificationMethodsElementCollection)base[NotificationMethodsKey]; - } - } - - [ConfigurationProperty(DisabledChecksKey, IsDefaultCollection = false, IsRequired = false)] - public DisabledHealthChecksElementCollection DisabledChecks - { - get - { - return (DisabledHealthChecksElementCollection)base[DisabledChecksKey]; - } - } - - bool IHealthCheckNotificationSettings.Enabled - { - get { return Enabled; } - } - - string IHealthCheckNotificationSettings.FirstRunTime - { - get { return FirstRunTime; } - } - - int IHealthCheckNotificationSettings.PeriodInHours - { - get { return PeriodInHours; } - } - - IReadOnlyDictionary IHealthCheckNotificationSettings.NotificationMethods - { - get { return NotificationMethods; } - } - - IEnumerable IHealthCheckNotificationSettings.DisabledChecks - { - get { return DisabledChecks; } - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs b/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs deleted file mode 100644 index 373d846567..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Configuration; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public class HealthChecksSection : ConfigurationSection - { - private const string DisabledChecksKey = "disabledChecks"; - private const string NotificationSettingsKey = "notificationSettings"; - - [ConfigurationProperty(DisabledChecksKey)] - public DisabledHealthChecksElementCollection DisabledChecks - { - get { return ((DisabledHealthChecksElementCollection)(base[DisabledChecksKey])); } - } - - [ConfigurationProperty(NotificationSettingsKey, IsRequired = true)] - public HealthCheckNotificationSettingsElement NotificationSettings - { - get { return ((HealthCheckNotificationSettingsElement)(base[NotificationSettingsKey])); } - } - - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/NotificationMethodElement.cs b/src/Umbraco.Configuration/HealthChecks/NotificationMethodElement.cs deleted file mode 100644 index cbbe5e8b02..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/NotificationMethodElement.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public class NotificationMethodElement : ConfigurationElement, INotificationMethod - { - private const string AliasKey = "alias"; - private const string EnabledKey = "enabled"; - private const string VerbosityKey = "verbosity"; - private const string FailureonlyKey = "failureOnly"; - private const string SettingsKey = "settings"; - - [ConfigurationProperty(AliasKey, IsKey = true, IsRequired = true)] - public string Alias - { - get - { - return (string)base[AliasKey]; - } - } - - [ConfigurationProperty(EnabledKey, IsKey = true, IsRequired = true)] - public bool Enabled - { - get - { - return (bool)base[EnabledKey]; - } - } - - [ConfigurationProperty(VerbosityKey, IsRequired = true)] - public HealthCheckNotificationVerbosity Verbosity - { - get - { - return (HealthCheckNotificationVerbosity)base[VerbosityKey]; - } - } - - [ConfigurationProperty(FailureonlyKey, IsRequired = false)] - public bool FailureOnly - { - get - { - return (bool)base[FailureonlyKey]; - } - } - - [ConfigurationProperty(SettingsKey, IsDefaultCollection = true, IsRequired = false)] - public NotificationMethodSettingsElementCollection Settings - { - get - { - return (NotificationMethodSettingsElementCollection)base[SettingsKey]; - } - } - - string INotificationMethod.Alias - { - get { return Alias; } - } - - bool INotificationMethod.Enabled - { - get { return Enabled; } - } - - HealthCheckNotificationVerbosity INotificationMethod.Verbosity - { - get { return Verbosity; } - } - - bool INotificationMethod.FailureOnly - { - get { return FailureOnly; } - } - - IReadOnlyDictionary INotificationMethod.Settings - { - get { return Settings; } - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElement.cs b/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElement.cs deleted file mode 100644 index ed42eb7221..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElement.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public class NotificationMethodSettingsElement : ConfigurationElement, INotificationMethodSettings - { - private const string KeyKey = "key"; - private const string ValueKey = "value"; - - [ConfigurationProperty(KeyKey, IsKey = true, IsRequired = true)] - public string Key - { - get - { - return (string)base[KeyKey]; - } - } - - [ConfigurationProperty(ValueKey, IsRequired = true)] - public string Value - { - get - { - return (string)base[ValueKey]; - } - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElementCollection.cs b/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElementCollection.cs deleted file mode 100644 index 226278ab61..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/NotificationMethodSettingsElementCollection.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - [ConfigurationCollection(typeof(NotificationMethodSettingsElement), AddItemName = "add")] - public class NotificationMethodSettingsElementCollection : ConfigurationElementCollection, IEnumerable, IReadOnlyDictionary - { - protected override ConfigurationElement CreateNewElement() - { - return new NotificationMethodSettingsElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((NotificationMethodSettingsElement)(element)).Key; - } - - IEnumerator> IEnumerable>.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - var val = (NotificationMethodSettingsElement)BaseGet(i); - var key = (string)BaseGetKey(i); - yield return new KeyValuePair(key, val); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return (NotificationMethodSettingsElement)BaseGet(i); - } - } - - bool IReadOnlyDictionary.ContainsKey(string key) - { - return ((IReadOnlyDictionary)this).Keys.Any(x => x == key); - } - - bool IReadOnlyDictionary.TryGetValue(string key, out INotificationMethodSettings value) - { - try - { - var val = (NotificationMethodSettingsElement)BaseGet(key); - value = val; - return true; - } - catch (Exception) - { - value = null; - return false; - } - } - - INotificationMethodSettings IReadOnlyDictionary.this[string key] - { - get { return (NotificationMethodSettingsElement)BaseGet(key); } - } - - IEnumerable IReadOnlyDictionary.Keys - { - get { return BaseGetAllKeys().Cast(); } - } - - IEnumerable IReadOnlyDictionary.Values - { - get - { - for (var i = 0; i < Count; i++) - { - yield return (NotificationMethodSettingsElement)BaseGet(i); - } - } - } - } -} diff --git a/src/Umbraco.Configuration/HealthChecks/NotificationMethodsElementCollection.cs b/src/Umbraco.Configuration/HealthChecks/NotificationMethodsElementCollection.cs deleted file mode 100644 index ee7e135961..0000000000 --- a/src/Umbraco.Configuration/HealthChecks/NotificationMethodsElementCollection.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using System.Linq; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - [ConfigurationCollection(typeof(NotificationMethodElement), AddItemName = "notificationMethod")] - public class NotificationMethodsElementCollection : ConfigurationElementCollection, IEnumerable, IReadOnlyDictionary - { - protected override ConfigurationElement CreateNewElement() - { - return new NotificationMethodElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((NotificationMethodElement)(element)).Alias; - } - - IEnumerator> IEnumerable>.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - var val = (NotificationMethodElement)BaseGet(i); - var key = (string)BaseGetKey(i); - yield return new KeyValuePair(key, val); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return (NotificationMethodElement)BaseGet(i); - } - } - - bool IReadOnlyDictionary.ContainsKey(string key) - { - return ((IReadOnlyDictionary) this).Keys.Any(x => x == key); - } - - bool IReadOnlyDictionary.TryGetValue(string key, out INotificationMethod value) - { - try - { - var val = (NotificationMethodElement)BaseGet(key); - value = val; - return true; - } - catch (Exception) - { - value = null; - return false; - } - } - - INotificationMethod IReadOnlyDictionary.this[string key] - { - get { return (NotificationMethodElement)BaseGet(key); } - } - - IEnumerable IReadOnlyDictionary.Keys - { - get { return BaseGetAllKeys().Cast(); } - } - - IEnumerable IReadOnlyDictionary.Values - { - get - { - for (var i = 0; i < Count; i++) - { - yield return (NotificationMethodElement)BaseGet(i); - } - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/ActiveDirectorySettings.cs b/src/Umbraco.Configuration/Legacy/ActiveDirectorySettings.cs deleted file mode 100644 index ef100afed6..0000000000 --- a/src/Umbraco.Configuration/Legacy/ActiveDirectorySettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class ActiveDirectorySettings : IActiveDirectorySettings - { - public ActiveDirectorySettings() - { - ActiveDirectoryDomain = ConfigurationManager.AppSettings["ActiveDirectoryDomain"]; - } - - public string ActiveDirectoryDomain { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/CommaDelimitedConfigurationElement.cs b/src/Umbraco.Configuration/Legacy/CommaDelimitedConfigurationElement.cs deleted file mode 100644 index 3ced2fab46..0000000000 --- a/src/Umbraco.Configuration/Legacy/CommaDelimitedConfigurationElement.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Configuration; - -namespace Umbraco.Core.Configuration -{ - /// - /// Defines a configuration section that contains inner text that is comma delimited - /// - internal class CommaDelimitedConfigurationElement : InnerTextConfigurationElement, IEnumerable - { - public override CommaDelimitedStringCollection Value - { - get - { - var converter = new CommaDelimitedStringCollectionConverter(); - return (CommaDelimitedStringCollection) converter.ConvertFrom(RawValue); - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - return new InnerEnumerator(Value.GetEnumerator()); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return new InnerEnumerator(Value.GetEnumerator()); - } - - /// - /// A wrapper for StringEnumerator since it doesn't explicitly implement IEnumerable - /// - private class InnerEnumerator : IEnumerator - { - private readonly StringEnumerator _stringEnumerator; - - public InnerEnumerator(StringEnumerator stringEnumerator) - { - _stringEnumerator = stringEnumerator; - } - - public bool MoveNext() - { - return _stringEnumerator.MoveNext(); - } - - public void Reset() - { - _stringEnumerator.Reset(); - } - - string IEnumerator.Current - { - get { return _stringEnumerator.Current; } - } - - public object Current - { - get { return _stringEnumerator.Current; } - } - - public void Dispose() - { - _stringEnumerator.DisposeIfDisposable(); - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/ConfigurationManagerConfigBase.cs b/src/Umbraco.Configuration/Legacy/ConfigurationManagerConfigBase.cs deleted file mode 100644 index 0302a7ea31..0000000000 --- a/src/Umbraco.Configuration/Legacy/ConfigurationManagerConfigBase.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal abstract class ConfigurationManagerConfigBase - { - private UmbracoSettingsSection _umbracoSettingsSection; - - protected UmbracoSettingsSection UmbracoSettingsSection - { - get - { - if (_umbracoSettingsSection is null) - { - _umbracoSettingsSection = ConfigurationManager.GetSection("umbracoConfiguration/settings") as UmbracoSettingsSection; - } - return _umbracoSettingsSection; - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/ConnectionStrings.cs b/src/Umbraco.Configuration/Legacy/ConnectionStrings.cs deleted file mode 100644 index a02c351118..0000000000 --- a/src/Umbraco.Configuration/Legacy/ConnectionStrings.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration -{ - public class ConnectionStrings : IConnectionStrings - { - public ConfigConnectionString this[string key] - { - get - { - var settings = ConfigurationManager.ConnectionStrings[key]; - if (settings == null) return null; - return new ConfigConnectionString(settings.ConnectionString, settings.ProviderName, settings.Name); - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/ContentSettings.cs b/src/Umbraco.Configuration/Legacy/ContentSettings.cs deleted file mode 100644 index 1c3f543bfe..0000000000 --- a/src/Umbraco.Configuration/Legacy/ContentSettings.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Macros; - -namespace Umbraco.Configuration.Implementations -{ - internal class ContentSettings : ConfigurationManagerConfigBase, IContentSettings - { - public string NotificationEmailAddress => UmbracoSettingsSection.Content.Notifications.NotificationEmailAddress; - public bool DisableHtmlEmail => UmbracoSettingsSection.Content.Notifications.DisableHtmlEmail; - public IEnumerable ImageFileTypes => UmbracoSettingsSection.Content.Imaging.ImageFileTypes; - public IEnumerable ImageAutoFillProperties => UmbracoSettingsSection.Content.Imaging.ImageAutoFillProperties; - public bool ResolveUrlsFromTextString => UmbracoSettingsSection.Content.ResolveUrlsFromTextString; - public IEnumerable Error404Collection => UmbracoSettingsSection.Content.Error404Collection; - public string PreviewBadge => UmbracoSettingsSection.Content.PreviewBadge; - public MacroErrorBehaviour MacroErrorBehaviour => UmbracoSettingsSection.Content.MacroErrors; - public IEnumerable DisallowedUploadFiles => UmbracoSettingsSection.Content.DisallowedUploadFiles; - public IEnumerable AllowedUploadFiles => UmbracoSettingsSection.Content.AllowedUploadFiles; - public bool ShowDeprecatedPropertyEditors => UmbracoSettingsSection.Content.ShowDeprecatedPropertyEditors; - public string LoginBackgroundImage => UmbracoSettingsSection.Content.LoginBackgroundImage; - } -} diff --git a/src/Umbraco.Configuration/Legacy/CoreDebugSettings.cs b/src/Umbraco.Configuration/Legacy/CoreDebugSettings.cs deleted file mode 100644 index 4902d4489f..0000000000 --- a/src/Umbraco.Configuration/Legacy/CoreDebugSettings.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Configuration; - -namespace Umbraco.Core.Configuration -{ - public class CoreDebugSettings : ICoreDebugSettings - { - public CoreDebugSettings() - { - var appSettings = ConfigurationManager.AppSettings; - LogUncompletedScopes = string.Equals("true", appSettings[Constants.AppSettings.Debug.LogUncompletedScopes], StringComparison.OrdinalIgnoreCase); - DumpOnTimeoutThreadAbort = string.Equals("true", appSettings[Constants.AppSettings.Debug.DumpOnTimeoutThreadAbort], StringComparison.OrdinalIgnoreCase); - } - - /// - public bool LogUncompletedScopes { get; } - - /// - public bool DumpOnTimeoutThreadAbort { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/ExceptionFilterSettings.cs b/src/Umbraco.Configuration/Legacy/ExceptionFilterSettings.cs deleted file mode 100644 index 50e2207485..0000000000 --- a/src/Umbraco.Configuration/Legacy/ExceptionFilterSettings.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class ExceptionFilterSettings : IExceptionFilterSettings - { - public ExceptionFilterSettings() - { - if (bool.TryParse(ConfigurationManager.AppSettings["Umbraco.Web.DisableModelBindingExceptionFilter"], - out var disabled)) - { - Disabled = disabled; - } - } - public bool Disabled { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/GlobalSettings.cs b/src/Umbraco.Configuration/Legacy/GlobalSettings.cs deleted file mode 100644 index fabe95f5bd..0000000000 --- a/src/Umbraco.Configuration/Legacy/GlobalSettings.cs +++ /dev/null @@ -1,377 +0,0 @@ -using System; -using System.Configuration; -using System.Linq; -using System.Net.Mail; -using System.Xml.Linq; -using Umbraco.Composing; -using Umbraco.Configuration; -using Umbraco.Core.IO; - -namespace Umbraco.Core.Configuration.Legacy -{ - // TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults! - // TODO: need to massively cleanup these configuration classes - - /// - /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings - /// - public class GlobalSettings : IGlobalSettings - { - - // TODO these should not be static - private static string _reservedPaths; - private static string _reservedUrls; - - //ensure the built on (non-changeable) reserved paths are there at all times - internal const string StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,"; //must end with a comma! - internal const string StaticReservedUrls = "~/config/splashes/noNodes.aspx,~/.well-known,"; //must end with a comma! - - /// - /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) - /// - private static void ResetInternal() - { - _reservedPaths = null; - _reservedUrls = null; - } - - /// - /// Resets settings that were set programmatically, to their initial values. - /// - /// To be used in unit tests. - internal static void Reset() - { - ResetInternal(); - } - - - public bool IsSmtpServerConfigured - { - get - { - var smtpSettings = SmtpSettings; - - if (smtpSettings is null) return false; - - if (!(smtpSettings.From is null)) return true; - if (!(smtpSettings.Host is null)) return true; - if (!(smtpSettings.PickupDirectoryLocation is null)) return true; - - return false; - } - } - - public ISmtpSettings SmtpSettings - { - get - { - var smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as ConfigurationSection; - if (smtpSection is null) return null; - - var result = new SmtpSettings(); - var from = smtpSection.ElementInformation.Properties["from"]; - if (@from != null - && @from.Value is string fromPropValue - && string.IsNullOrEmpty(fromPropValue) == false - && !string.Equals("noreply@example.com", fromPropValue, StringComparison.OrdinalIgnoreCase)) - { - result.From = fromPropValue; - } - - var specifiedPickupDirectorySection = ConfigurationManager.GetSection("system.net/mailSettings/smtp/specifiedPickupDirectory") as ConfigurationSection; - var pickupDirectoryLocation = specifiedPickupDirectorySection?.ElementInformation.Properties["pickupDirectoryLocation"]; - if (pickupDirectoryLocation != null - && pickupDirectoryLocation.Value is string pickupDirectoryLocationPropValue - && string.IsNullOrEmpty(pickupDirectoryLocationPropValue) == false) - { - result.PickupDirectoryLocation = pickupDirectoryLocationPropValue; - } - - // SmtpClient can magically read the section system.net/mailSettings/smtp/network, witch is always - // null if we use ConfigurationManager.GetSection. SmtpSection does not exist in .Net Standard - var smtpClient = new SmtpClient(); - - result.Host = smtpClient.Host; - result.Port = smtpClient.Port; - - return result; - - } - } - - /// - /// Gets the reserved urls from web.config. - /// - /// The reserved urls. - public string ReservedUrls - { - get - { - if (_reservedUrls != null) return _reservedUrls; - - var urls = ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.ReservedUrls) - ? ConfigurationManager.AppSettings[Constants.AppSettings.ReservedUrls] - : string.Empty; - - //ensure the built on (non-changeable) reserved paths are there at all times - _reservedUrls = StaticReservedUrls + urls; - return _reservedUrls; - } - internal set => _reservedUrls = value; - } - - /// - /// Gets the reserved paths from web.config - /// - /// The reserved paths. - public string ReservedPaths - { - get - { - if (_reservedPaths != null) return _reservedPaths; - - var reservedPaths = StaticReservedPaths; - var umbPath = ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.UmbracoPath) && !ConfigurationManager.AppSettings[Constants.AppSettings.UmbracoPath].IsNullOrWhiteSpace() - ? ConfigurationManager.AppSettings[Constants.AppSettings.UmbracoPath] - : "~/umbraco"; - //always add the umbraco path to the list - reservedPaths += umbPath.EnsureEndsWith(','); - - var allPaths = ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.ReservedPaths) - ? ConfigurationManager.AppSettings[Constants.AppSettings.ReservedPaths] - : string.Empty; - - _reservedPaths = reservedPaths + allPaths; - return _reservedPaths; - } - } - - - - - /// - /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. - /// - /// The configuration status. - public string ConfigurationStatus - { - get - { - return ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.ConfigurationStatus) - ? ConfigurationManager.AppSettings[Constants.AppSettings.ConfigurationStatus] - : string.Empty; - } - set - { - SaveSetting(Constants.AppSettings.ConfigurationStatus, value, Current.IOHelper); //TODO remove - } - } - - /// - /// Saves a setting into the configuration file. - /// - /// Key of the setting to be saved. - /// Value of the setting to be saved. - internal static void SaveSetting(string key, string value, IIOHelper ioHelper) - { - var fileName = ioHelper.MapPath("~/web.config"); - var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); - - var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); - - // Update appSetting if it exists, or else create a new appSetting for the given key and value - var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key); - if (setting == null) - appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value))); - else - setting.Attribute("value").Value = value; - - xml.Save(fileName, SaveOptions.DisableFormatting); - ConfigurationManager.RefreshSection("appSettings"); - } - - - /// - /// Gets the time out in minutes. - /// - /// The time out in minutes. - public int TimeOutInMinutes - { - get - { - try - { - return int.Parse(ConfigurationManager.AppSettings[Constants.AppSettings.TimeOutInMinutes]); - } - catch - { - return 20; - } - } - } - - /// - /// Returns the number of days that should take place between version checks. - /// - /// The version check period in days (0 = never). - public int VersionCheckPeriod - { - get - { - try - { - var val = ConfigurationManager.AppSettings[Constants.AppSettings.VersionCheckPeriod]; - if (!(val is null)) - { - return int.Parse(val); - } - } - catch - { - // Ignore - } - return 7; - } - } - - - - - /// - /// Gets the default UI language. - /// - /// The default UI language. - // ReSharper disable once InconsistentNaming - public string DefaultUILanguage - { - get - { - return ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.DefaultUILanguage) - ? ConfigurationManager.AppSettings[Constants.AppSettings.DefaultUILanguage] - : string.Empty; - } - } - - /// - /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. - /// - /// - /// true if umbraco hides top level nodes from urls; otherwise, false. - /// - public bool HideTopLevelNodeFromPath - { - get - { - try - { - return bool.Parse(ConfigurationManager.AppSettings[Constants.AppSettings.HideTopLevelNodeFromPath]); - } - catch - { - return false; - } - } - } - - /// - /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. - /// - public bool UseHttps - { - get - { - try - { - return bool.Parse(ConfigurationManager.AppSettings[Constants.AppSettings.UseHttps]); - } - catch - { - return false; - } - } - } - - private string _umbracoMediaPath = null; - public string UmbracoMediaPath => GetterWithDefaultValue(Constants.AppSettings.UmbracoMediaPath, "~/media", ref _umbracoMediaPath); - - private string _umbracoScriptsPath = null; - public string UmbracoScriptsPath => GetterWithDefaultValue(Constants.AppSettings.UmbracoScriptsPath, "~/scripts", ref _umbracoScriptsPath); - - private string _umbracoCssPath = null; - public string UmbracoCssPath => GetterWithDefaultValue(Constants.AppSettings.UmbracoCssPath, "~/css", ref _umbracoCssPath); - - private string _umbracoPath = null; - public string UmbracoPath => GetterWithDefaultValue(Constants.AppSettings.UmbracoPath, "~/umbraco", ref _umbracoPath); - - private bool _installMissingDatabase; - public bool InstallMissingDatabase => GetterWithDefaultValue("Umbraco.Core.RuntimeState.InstallMissingDatabase", false, ref _installMissingDatabase); - - private bool _installEmptyDatabase; - public bool InstallEmptyDatabase => GetterWithDefaultValue("Umbraco.Core.RuntimeState.InstallEmptyDatabase", false, ref _installEmptyDatabase); - - private bool _disableElectionForSingleServer; - public bool DisableElectionForSingleServer => GetterWithDefaultValue(Constants.AppSettings.DisableElectionForSingleServer, false, ref _disableElectionForSingleServer); - - private string _registerType; - public string RegisterType => GetterWithDefaultValue(Constants.AppSettings.RegisterType, string.Empty, ref _registerType); - - private string _databaseFactoryServerVersion; - public string DatabaseFactoryServerVersion => GetterWithDefaultValue(Constants.AppSettings.Debug.DatabaseFactoryServerVersion, string.Empty, ref _databaseFactoryServerVersion); - - - - private string _iconsPath; - /// - /// Gets the path to folder containing the icons used in the umbraco backoffice (/umbraco/assets/icons by default). - /// - /// The icons path. - public string IconsPath => GetterWithDefaultValue(Constants.AppSettings.IconsPath, $"{UmbracoPath}/assets/icons", ref _iconsPath); - - private string _mainDomLock; - - public string MainDomLock => GetterWithDefaultValue(Constants.AppSettings.MainDomLock, string.Empty, ref _mainDomLock); - - private T GetterWithDefaultValue(string appSettingKey, T defaultValue, ref T backingField) - { - if (backingField != null) return backingField; - - if (ConfigurationManager.AppSettings.ContainsKey(appSettingKey)) - { - try - { - var value = ConfigurationManager.AppSettings[appSettingKey]; - - backingField = (T)Convert.ChangeType(value, typeof(T)); - } - catch - { - /* ignore and use default value */ - backingField = defaultValue; - } - } - else - { - backingField = defaultValue; - } - - return backingField; - } - - /// - /// Gets the path to the razor file used when no published content is available. - /// - public string NoNodesViewPath - { - get - { - var configuredValue = ConfigurationManager.AppSettings[Constants.AppSettings.NoNodesViewPath]; - if (!string.IsNullOrWhiteSpace(configuredValue)) - { - return configuredValue; - } - - return "~/config/splashes/NoNodes.cshtml"; - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/HealthChecksSettings.cs b/src/Umbraco.Configuration/Legacy/HealthChecksSettings.cs deleted file mode 100644 index 23385d1378..0000000000 --- a/src/Umbraco.Configuration/Legacy/HealthChecksSettings.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; -using Umbraco.Core.Configuration.HealthChecks; - -namespace Umbraco.Core.Configuration.Legacy -{ - public class HealthChecksSettings : IHealthChecksSettings - { - private HealthChecksSection _healthChecksSection; - - private HealthChecksSection HealthChecksSection - { - get - { - if (_healthChecksSection is null) - { - _healthChecksSection = ConfigurationManager.GetSection("umbracoConfiguration/HealthChecks") as HealthChecksSection; - } - return _healthChecksSection; - } - } - - public IEnumerable DisabledChecks => HealthChecksSection.DisabledChecks; - public IHealthCheckNotificationSettings NotificationSettings => HealthChecksSection.NotificationSettings; - } -} diff --git a/src/Umbraco.Configuration/Legacy/HostingSettings.cs b/src/Umbraco.Configuration/Legacy/HostingSettings.cs deleted file mode 100644 index 1858e8a4a4..0000000000 --- a/src/Umbraco.Configuration/Legacy/HostingSettings.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.Legacy -{ - public class HostingSettings : IHostingSettings - { - private bool? _debugMode; - - /// - public LocalTempStorage LocalTempStorageLocation - { - get - { - var setting = ConfigurationManager.AppSettings[Constants.AppSettings.LocalTempStorage]; - if (!string.IsNullOrWhiteSpace(setting)) - return Enum.Parse(setting); - - return LocalTempStorage.Default; - } - } - - public string ApplicationVirtualPath => null; - - /// - /// Gets a value indicating whether umbraco is running in [debug mode]. - /// - /// true if [debug mode]; otherwise, false. - public bool DebugMode - { - get - { - if (!_debugMode.HasValue) - { - try - { - if (ConfigurationManager.GetSection("system.web/compilation") is ConfigurationSection compilation) - { - var debugElement = compilation.ElementInformation.Properties["debug"]; - - _debugMode = debugElement != null && (debugElement.Value is bool debug && debug); - - } - } - catch - { - _debugMode = false; - } - } - - return _debugMode.GetValueOrDefault(); - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/IndexCreatorSettings.cs b/src/Umbraco.Configuration/Legacy/IndexCreatorSettings.cs deleted file mode 100644 index d023d46246..0000000000 --- a/src/Umbraco.Configuration/Legacy/IndexCreatorSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class IndexCreatorSettings : IIndexCreatorSettings - { - public IndexCreatorSettings() - { - LuceneDirectoryFactory = ConfigurationManager.AppSettings["Umbraco.Examine.LuceneDirectoryFactory"]; - } - - public string LuceneDirectoryFactory { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/InnerTextConfigurationElement.cs b/src/Umbraco.Configuration/Legacy/InnerTextConfigurationElement.cs deleted file mode 100644 index 6a125f2c1b..0000000000 --- a/src/Umbraco.Configuration/Legacy/InnerTextConfigurationElement.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Xml; -using System.Xml.Linq; - -namespace Umbraco.Core.Configuration -{ - /// - /// A full config section is required for any full element and we have some elements that are defined like this: - /// {element}MyValue{/element} instead of as attribute values. - /// - /// - internal class InnerTextConfigurationElement : RawXmlConfigurationElement - { - public InnerTextConfigurationElement() - { - } - - public InnerTextConfigurationElement(XElement rawXml) : base(rawXml) - { - } - - protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) - { - base.DeserializeElement(reader, serializeCollectionKey); - //now validate and set the raw value - if (RawXml.HasElements) - throw new InvalidOperationException("An InnerTextConfigurationElement cannot contain any child elements, only attributes and a value"); - RawValue = RawXml.Value.Trim(); - - //RawValue = reader.ReadElementContentAsString(); - } - - public virtual T Value - { - get - { - var converted = RawValue.TryConvertTo(); - if (converted.Success == false) - throw new InvalidCastException("Could not convert value " + RawValue + " to type " + typeof(T)); - return converted.Result; - } - } - - /// - /// Exposes the raw string value - /// - internal string RawValue { get; set; } - - /// - /// Implicit operator so we don't need to use the 'Value' property explicitly - /// - /// - /// - public static implicit operator T(InnerTextConfigurationElement m) - { - return m.Value; - } - - /// - /// Return the string value of Value - /// - /// - public override string ToString() - { - return string.Format("{0}", Value); - } - - } -} diff --git a/src/Umbraco.Configuration/Legacy/KeepAliveSettings.cs b/src/Umbraco.Configuration/Legacy/KeepAliveSettings.cs deleted file mode 100644 index 0b8315d447..0000000000 --- a/src/Umbraco.Configuration/Legacy/KeepAliveSettings.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class KeepAliveSettings : ConfigurationManagerConfigBase, IKeepAliveSettings - { - public bool DisableKeepAliveTask => UmbracoSettingsSection.KeepAlive.DisableKeepAliveTask; - public string KeepAlivePingUrl => UmbracoSettingsSection.KeepAlive.KeepAlivePingUrl; - } -} diff --git a/src/Umbraco.Configuration/Legacy/LoggingSettings.cs b/src/Umbraco.Configuration/Legacy/LoggingSettings.cs deleted file mode 100644 index 020b0c0e64..0000000000 --- a/src/Umbraco.Configuration/Legacy/LoggingSettings.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class LoggingSettings : ConfigurationManagerConfigBase, ILoggingSettings - { - public int MaxLogAge => UmbracoSettingsSection.Logging.MaxLogAge; - } -} diff --git a/src/Umbraco.Configuration/Legacy/MemberPasswordConfigurationSettings.cs b/src/Umbraco.Configuration/Legacy/MemberPasswordConfigurationSettings.cs deleted file mode 100644 index e42b02de73..0000000000 --- a/src/Umbraco.Configuration/Legacy/MemberPasswordConfigurationSettings.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Implementations -{ - internal class MemberPasswordConfigurationSettings : ConfigurationManagerConfigBase, IMemberPasswordConfiguration - { - public int RequiredLength => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequiredLength; - public bool RequireNonLetterOrDigit => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireNonLetterOrDigit; - public bool RequireDigit => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireDigit; - public bool RequireLowercase=> UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireLowercase; - public bool RequireUppercase=> UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireUppercase; - public bool UseLegacyEncoding=> UmbracoSettingsSection.Security.UserPasswordConfiguration.UseLegacyEncoding; - public string HashAlgorithmType=> UmbracoSettingsSection.Security.UserPasswordConfiguration.HashAlgorithmType; - public int MaxFailedAccessAttemptsBeforeLockout => UmbracoSettingsSection.Security.UserPasswordConfiguration.MaxFailedAccessAttemptsBeforeLockout; - } -} diff --git a/src/Umbraco.Configuration/Legacy/ModelsBuilderConfig.cs b/src/Umbraco.Configuration/Legacy/ModelsBuilderConfig.cs deleted file mode 100644 index f6395b23b4..0000000000 --- a/src/Umbraco.Configuration/Legacy/ModelsBuilderConfig.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System; -using System.Configuration; -using System.IO; -using System.Threading; -using Umbraco.Core.Configuration; -using Umbraco.Core; -using Umbraco.Core.IO; - -namespace Umbraco.Configuration.Legacy -{ - /// - /// Represents the models builder configuration. - /// - public class ModelsBuilderConfig : IModelsBuilderConfig - { - - private const string Prefix = "Umbraco.ModelsBuilder."; - private object _modelsModelLock; - private bool _modelsModelConfigured; - private ModelsMode _modelsMode; - private object _flagOutOfDateModelsLock; - private bool _flagOutOfDateModelsConfigured; - private bool _flagOutOfDateModels; - - - public string DefaultModelsDirectory => "~/App_Data/Models"; - - /// - /// Initializes a new instance of the class. - /// - public ModelsBuilderConfig() - { - // giant kill switch, default: false - // must be explicitely set to true for anything else to happen - Enable = ConfigurationManager.AppSettings[Prefix + "Enable"] == "true"; - - // ensure defaults are initialized for tests - ModelsNamespace = Constants.ModelsBuilder.DefaultModelsNamespace; - ModelsDirectory = DefaultModelsDirectory; - DebugLevel = 0; - - // stop here, everything is false - if (!Enable) return; - - // default: false - AcceptUnsafeModelsDirectory = ConfigurationManager.AppSettings[Prefix + "AcceptUnsafeModelsDirectory"].InvariantEquals("true"); - - // default: true - EnableFactory = !ConfigurationManager.AppSettings[Prefix + "EnableFactory"].InvariantEquals("false"); - - // default: initialized above with DefaultModelsNamespace const - var value = ConfigurationManager.AppSettings[Prefix + "ModelsNamespace"]; - if (!string.IsNullOrWhiteSpace(value)) - ModelsNamespace = value; - - // default: initialized above with DefaultModelsDirectory const - value = ConfigurationManager.AppSettings[Prefix + "ModelsDirectory"]; - if (!string.IsNullOrWhiteSpace(value)) - { - // GetModelsDirectory will ensure that the path is safe - ModelsDirectory = value; - } - - // default: 0 - value = ConfigurationManager.AppSettings[Prefix + "DebugLevel"]; - if (!string.IsNullOrWhiteSpace(value)) - { - if (!int.TryParse(value, out var debugLevel)) - throw new ConfigurationErrorsException($"Invalid debug level \"{value}\"."); - DebugLevel = debugLevel; - } - - } - - /// - /// Initializes a new instance of the class. - /// - public ModelsBuilderConfig( - bool enable = false, - ModelsMode modelsMode = ModelsMode.Nothing, - string modelsNamespace = null, - bool enableFactory = true, - bool flagOutOfDateModels = true, - string modelsDirectory = null, - bool acceptUnsafeModelsDirectory = false, - int debugLevel = 0) - { - Enable = enable; - _modelsMode = modelsMode; - - ModelsNamespace = string.IsNullOrWhiteSpace(modelsNamespace) ? Constants.ModelsBuilder.DefaultModelsNamespace : modelsNamespace; - EnableFactory = enableFactory; - _flagOutOfDateModels = flagOutOfDateModels; - ModelsDirectory = string.IsNullOrWhiteSpace(modelsDirectory) ? DefaultModelsDirectory : modelsDirectory; - AcceptUnsafeModelsDirectory = acceptUnsafeModelsDirectory; - DebugLevel = debugLevel; - } - - - - /// - /// Gets a value indicating whether the whole models experience is enabled. - /// - /// - /// If this is false then absolutely nothing happens. - /// Default value is false which means that unless we have this setting, nothing happens. - /// - public bool Enable { get; } - - /// - /// Gets the models mode. - /// - public ModelsMode ModelsMode => - LazyInitializer.EnsureInitialized(ref _modelsMode, ref _modelsModelConfigured, ref _modelsModelLock, () => - { - // mode - var modelsMode = ConfigurationManager.AppSettings[Prefix + "ModelsMode"]; - if (string.IsNullOrWhiteSpace(modelsMode)) return ModelsMode.Nothing; //default - switch (modelsMode) - { - case nameof(ModelsMode.Nothing): - return ModelsMode.Nothing; - case nameof(ModelsMode.PureLive): - return ModelsMode.PureLive; - case nameof(ModelsMode.AppData): - return ModelsMode.AppData; - case nameof(ModelsMode.LiveAppData): - return ModelsMode.LiveAppData; - default: - throw new ConfigurationErrorsException($"ModelsMode \"{modelsMode}\" is not a valid mode." + " Note that modes are case-sensitive. Possible values are: " + string.Join(", ", Enum.GetNames(typeof(ModelsMode)))); - } - }); - - /// - /// Gets a value indicating whether system.web/compilation/@debug is true. - /// - public bool IsDebug - { - get - { - if (ConfigurationManager.GetSection("system.web/compilation") is ConfigurationSection section && - bool.TryParse(section.ElementInformation.Properties["debug"].Value.ToString(), out var isDebug)) - { - return isDebug; - } - - return false; - } - } - - /// - /// Gets the models namespace. - /// - /// That value could be overriden by other (attribute in user's code...). Return default if no value was supplied. - public string ModelsNamespace { get; } - - /// - /// Gets a value indicating whether we should enable the models factory. - /// - /// Default value is true because no factory is enabled by default in Umbraco. - public bool EnableFactory { get; } - - /// - /// Gets a value indicating whether we should flag out-of-date models. - /// - /// Models become out-of-date when data types or content types are updated. When this - /// setting is activated the ~/App_Data/Models/ood.txt file is then created. When models are - /// generated through the dashboard, the files is cleared. Default value is false. - public bool FlagOutOfDateModels - => LazyInitializer.EnsureInitialized(ref _flagOutOfDateModels, ref _flagOutOfDateModelsConfigured, ref _flagOutOfDateModelsLock, () => - { - var flagOutOfDateModels = !ConfigurationManager.AppSettings[Prefix + "FlagOutOfDateModels"].InvariantEquals("false"); - if (ModelsMode == ModelsMode.Nothing || ModelsMode.IsLive()) - { - flagOutOfDateModels = false; - } - - return flagOutOfDateModels; - }); - - /// - /// Gets the models directory. - /// - /// Default is ~/App_Data/Models but that can be changed. - public string ModelsDirectory { get; } - - /// - /// Gets a value indicating whether to accept an unsafe value for ModelsDirectory. - /// - /// An unsafe value is an absolute path, or a relative path pointing outside - /// of the website root. - public bool AcceptUnsafeModelsDirectory { get; } - - /// - /// Gets a value indicating the debug log level. - /// - /// 0 means minimal (safe on live site), anything else means more and more details (maybe not safe). - public int DebugLevel { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/NuCacheSettings.cs b/src/Umbraco.Configuration/Legacy/NuCacheSettings.cs deleted file mode 100644 index 25f52a5c7d..0000000000 --- a/src/Umbraco.Configuration/Legacy/NuCacheSettings.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class NuCacheSettings : INuCacheSettings - { - public NuCacheSettings() - { - BTreeBlockSize = ConfigurationManager.AppSettings["Umbraco.Web.PublishedCache.NuCache.BTree.BlockSize"]; - } - public string BTreeBlockSize { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/OptionalCommaDelimitedConfigurationElement.cs b/src/Umbraco.Configuration/Legacy/OptionalCommaDelimitedConfigurationElement.cs deleted file mode 100644 index 610067d2db..0000000000 --- a/src/Umbraco.Configuration/Legacy/OptionalCommaDelimitedConfigurationElement.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Core.Configuration -{ - /// - /// Used for specifying default values for comma delimited config - /// - internal class OptionalCommaDelimitedConfigurationElement : CommaDelimitedConfigurationElement - { - private readonly CommaDelimitedConfigurationElement _wrapped; - private readonly string[] _defaultValue; - - public OptionalCommaDelimitedConfigurationElement() - { - } - - public OptionalCommaDelimitedConfigurationElement(CommaDelimitedConfigurationElement wrapped, string[] defaultValue) - { - _wrapped = wrapped; - _defaultValue = defaultValue; - } - - public override CommaDelimitedStringCollection Value - { - get - { - if (_wrapped == null) - { - return base.Value; - } - - if (string.IsNullOrEmpty(_wrapped.RawValue)) - { - var val = new CommaDelimitedStringCollection(); - val.AddRange(_defaultValue); - return val; - } - return _wrapped.Value; - } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/OptionalInnerTextConfigurationElement.cs b/src/Umbraco.Configuration/Legacy/OptionalInnerTextConfigurationElement.cs deleted file mode 100644 index b15e33019d..0000000000 --- a/src/Umbraco.Configuration/Legacy/OptionalInnerTextConfigurationElement.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - /// - /// This is used to supply optional/default values when using InnerTextConfigurationElement - /// - /// - internal class OptionalInnerTextConfigurationElement : InnerTextConfigurationElement - { - private readonly InnerTextConfigurationElement _wrapped; - private readonly T _defaultValue; - - public OptionalInnerTextConfigurationElement(InnerTextConfigurationElement wrapped, T defaultValue) - { - _wrapped = wrapped; - _defaultValue = defaultValue; - } - - public override T Value - { - get { return string.IsNullOrEmpty(_wrapped.RawValue) ? _defaultValue : _wrapped.Value; } - } - } -} diff --git a/src/Umbraco.Configuration/Legacy/RawXmlConfigurationElement.cs b/src/Umbraco.Configuration/Legacy/RawXmlConfigurationElement.cs deleted file mode 100644 index 5bc6ad3d32..0000000000 --- a/src/Umbraco.Configuration/Legacy/RawXmlConfigurationElement.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Configuration; -using System.Xml; -using System.Xml.Linq; - -namespace Umbraco.Core.Configuration -{ - /// - /// A configuration section that simply exposes the entire raw xml of the section itself which inheritors can use - /// to do with as they please. - /// - internal abstract class RawXmlConfigurationElement : ConfigurationElement - { - protected RawXmlConfigurationElement() - { - - } - - protected RawXmlConfigurationElement(XElement rawXml) - { - RawXml = rawXml; - } - - protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) - { - RawXml = (XElement)XNode.ReadFrom(reader); - } - - protected XElement RawXml { get; private set; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/RequestHandlerSettings.cs b/src/Umbraco.Configuration/Legacy/RequestHandlerSettings.cs deleted file mode 100644 index 1c54f4d475..0000000000 --- a/src/Umbraco.Configuration/Legacy/RequestHandlerSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class RequestHandlerSettings : ConfigurationManagerConfigBase, IRequestHandlerSettings - { - public bool AddTrailingSlash => UmbracoSettingsSection?.RequestHandler?.AddTrailingSlash ?? true; - public bool ConvertUrlsToAscii => UmbracoSettingsSection?.RequestHandler?.UrlReplacing?.ConvertUrlsToAscii.InvariantEquals("true") ?? false; - public bool TryConvertUrlsToAscii => UmbracoSettingsSection?.RequestHandler?.UrlReplacing?.ConvertUrlsToAscii.InvariantEquals("try") ?? false; - public IEnumerable CharCollection => UmbracoSettingsSection?.RequestHandler?.UrlReplacing?.CharCollection ?? Enumerable.Empty(); - } -} diff --git a/src/Umbraco.Configuration/Legacy/RuntimeSettings.cs b/src/Umbraco.Configuration/Legacy/RuntimeSettings.cs deleted file mode 100644 index 200642a819..0000000000 --- a/src/Umbraco.Configuration/Legacy/RuntimeSettings.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Configuration; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class RuntimeSettings : IRuntimeSettings - { - public RuntimeSettings() - { - if (ConfigurationManager.GetSection("system.web/httpRuntime") is ConfigurationSection section) - { - var maxRequestLengthProperty = section.ElementInformation.Properties["maxRequestLength"]; - if (maxRequestLengthProperty != null && maxRequestLengthProperty.Value is int requestLength) - { - MaxRequestLength = requestLength; - } - - var maxQueryStringProperty = section.ElementInformation.Properties["maxQueryStringLength"]; - if (maxQueryStringProperty != null && maxQueryStringProperty.Value is int maxQueryStringLength) - { - MaxQueryStringLength = maxQueryStringLength; - } - } - } - public int? MaxQueryStringLength { get; } - public int? MaxRequestLength { get; } - - } -} diff --git a/src/Umbraco.Configuration/Legacy/SecuritySettings.cs b/src/Umbraco.Configuration/Legacy/SecuritySettings.cs deleted file mode 100644 index b7e39b0608..0000000000 --- a/src/Umbraco.Configuration/Legacy/SecuritySettings.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class SecuritySettings : ConfigurationManagerConfigBase, ISecuritySettings - { - public bool KeepUserLoggedIn => UmbracoSettingsSection.Security.KeepUserLoggedIn; - public bool HideDisabledUsersInBackoffice => UmbracoSettingsSection.Security.HideDisabledUsersInBackoffice; - public bool AllowPasswordReset => UmbracoSettingsSection.Security.AllowPasswordReset; - public string AuthCookieName => UmbracoSettingsSection.Security.AuthCookieName; - public string AuthCookieDomain => UmbracoSettingsSection.Security.AuthCookieDomain; - public bool UsernameIsEmail => UmbracoSettingsSection.Security.UsernameIsEmail; - } -} diff --git a/src/Umbraco.Configuration/Legacy/TourSettings.cs b/src/Umbraco.Configuration/Legacy/TourSettings.cs deleted file mode 100644 index 134c3c48d5..0000000000 --- a/src/Umbraco.Configuration/Legacy/TourSettings.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class TourSettings : ConfigurationManagerConfigBase, ITourSettings - { - public bool EnableTours => UmbracoSettingsSection.BackOffice.Tours.EnableTours; - } -} diff --git a/src/Umbraco.Configuration/Legacy/TypeFinderSettings.cs b/src/Umbraco.Configuration/Legacy/TypeFinderSettings.cs deleted file mode 100644 index b1009f754b..0000000000 --- a/src/Umbraco.Configuration/Legacy/TypeFinderSettings.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Legacy -{ - public class TypeFinderSettings : ITypeFinderSettings - { - public TypeFinderSettings() - { - AssembliesAcceptingLoadExceptions = ConfigurationManager.AppSettings[ - Constants.AppSettings.AssembliesAcceptingLoadExceptions]; - } - - public string AssembliesAcceptingLoadExceptions { get; } - } -} diff --git a/src/Umbraco.Configuration/Legacy/UmbracoConfigurationSection.cs b/src/Umbraco.Configuration/Legacy/UmbracoConfigurationSection.cs deleted file mode 100644 index 8c0754b91d..0000000000 --- a/src/Umbraco.Configuration/Legacy/UmbracoConfigurationSection.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration -{ - /// - /// Represents an Umbraco section within the configuration file. - /// - /// - /// The requirement for these sections is to be read-only. - /// However for unit tests purposes it is internally possible to override some values, and - /// then calling >ResetSection should cancel these changes and bring the section back to - /// what it was originally. - /// The UmbracoSettings.For{T} method will return a section, either one that - /// is in the configuration file, or a section that was created with default values. - /// - public abstract class UmbracoConfigurationSection : ConfigurationSection, IUmbracoConfigurationSection - { - /// - /// Gets a value indicating whether the section actually is in the configuration file. - /// - protected bool IsPresent { get { return ElementInformation.IsPresent; } } - - } -} diff --git a/src/Umbraco.Configuration/Legacy/UserPasswordConfigurationSettings.cs b/src/Umbraco.Configuration/Legacy/UserPasswordConfigurationSettings.cs deleted file mode 100644 index 51dd645c42..0000000000 --- a/src/Umbraco.Configuration/Legacy/UserPasswordConfigurationSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Umbraco.Core.Configuration; -namespace Umbraco.Configuration.Implementations -{ - internal class UserPasswordConfigurationSettings : ConfigurationManagerConfigBase, IUserPasswordConfiguration - { - public int RequiredLength => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequiredLength; - public bool RequireNonLetterOrDigit => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireNonLetterOrDigit; - public bool RequireDigit => UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireDigit; - public bool RequireLowercase=> UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireLowercase; - public bool RequireUppercase=> UmbracoSettingsSection.Security.UserPasswordConfiguration.RequireUppercase; - public bool UseLegacyEncoding=> UmbracoSettingsSection.Security.UserPasswordConfiguration.UseLegacyEncoding; - public string HashAlgorithmType=> UmbracoSettingsSection.Security.UserPasswordConfiguration.HashAlgorithmType; - public int MaxFailedAccessAttemptsBeforeLockout => UmbracoSettingsSection.Security.UserPasswordConfiguration.MaxFailedAccessAttemptsBeforeLockout; - } -} diff --git a/src/Umbraco.Configuration/Legacy/WebRoutingSettings.cs b/src/Umbraco.Configuration/Legacy/WebRoutingSettings.cs deleted file mode 100644 index cfca66822b..0000000000 --- a/src/Umbraco.Configuration/Legacy/WebRoutingSettings.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Implementations -{ - internal class WebRoutingSettings : ConfigurationManagerConfigBase, IWebRoutingSettings - { - public bool TrySkipIisCustomErrors => UmbracoSettingsSection?.WebRouting?.TrySkipIisCustomErrors ?? false; - public bool InternalRedirectPreservesTemplate => UmbracoSettingsSection?.WebRouting?.InternalRedirectPreservesTemplate ?? false; - public bool DisableAlternativeTemplates => UmbracoSettingsSection?.WebRouting?.DisableAlternativeTemplates ?? false; - public bool ValidateAlternativeTemplates => UmbracoSettingsSection?.WebRouting?.ValidateAlternativeTemplates ?? false; - public bool DisableFindContentByIdPath => UmbracoSettingsSection?.WebRouting?.DisableFindContentByIdPath ?? false; - public bool DisableRedirectUrlTracking => UmbracoSettingsSection?.WebRouting?.DisableRedirectUrlTracking ?? false; - public string UrlProviderMode => UmbracoSettingsSection?.WebRouting?.UrlProviderMode ?? "Auto"; - public string UmbracoApplicationUrl => UmbracoSettingsSection?.WebRouting?.UmbracoApplicationUrl; - } -} diff --git a/src/Umbraco.Configuration/Models/ActiveDirectorySettings.cs b/src/Umbraco.Configuration/Models/ActiveDirectorySettings.cs deleted file mode 100644 index 015fb17a8e..0000000000 --- a/src/Umbraco.Configuration/Models/ActiveDirectorySettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class ActiveDirectorySettings : IActiveDirectorySettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "ActiveDirectory:"; - private readonly IConfiguration _configuration; - - public ActiveDirectorySettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string ActiveDirectoryDomain => _configuration.GetValue(Prefix+"Domain"); - } -} diff --git a/src/Umbraco.Configuration/Models/ConnectionStrings.cs b/src/Umbraco.Configuration/Models/ConnectionStrings.cs deleted file mode 100644 index 586765714c..0000000000 --- a/src/Umbraco.Configuration/Models/ConnectionStrings.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Data.Common; -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - public class ConnectionStrings : IConnectionStrings - { - private readonly IConfiguration _configuration; - - public ConnectionStrings(IConfiguration configuration) - { - _configuration = configuration; - } - - public ConfigConnectionString this[string key] - { - get - { - var connectionString = _configuration.GetConnectionString(key); - var provider = ParseProvider(connectionString); - return new ConfigConnectionString(connectionString, provider, key); - } - set => throw new NotImplementedException(); - } - - private string ParseProvider(string connectionString) - { - if (string.IsNullOrEmpty(connectionString)) - { - return null; - } - - var builder = new DbConnectionStringBuilder(); - - builder.ConnectionString = connectionString; - - if (builder.TryGetValue("Data Source", out var ds) && ds is string dataSource) - { - if (dataSource.EndsWith(".sdf")) - { - return Constants.DbProviderNames.SqlCe; - } - } - - if (builder.TryGetValue("Server", out var s) && s is string server && !string.IsNullOrEmpty(server)) - { - if (builder.TryGetValue("Database", out var db) && db is string database && !string.IsNullOrEmpty(database)) - { - return Constants.DbProviderNames.SqlServer; - } - - if (builder.TryGetValue("AttachDbFileName", out var a) && a is string attachDbFileName && !string.IsNullOrEmpty(attachDbFileName)) - { - return Constants.DbProviderNames.SqlServer; - } - - if (builder.TryGetValue("Initial Catalog", out var i) && i is string initialCatalog && !string.IsNullOrEmpty(initialCatalog)) - { - return Constants.DbProviderNames.SqlServer; - } - } - - throw new ArgumentException("Cannot determine provider name from connection string", nameof(connectionString)); - } - } -} diff --git a/src/Umbraco.Configuration/Models/ContentSettings.cs b/src/Umbraco.Configuration/Models/ContentSettings.cs deleted file mode 100644 index 6c9b986dd1..0000000000 --- a/src/Umbraco.Configuration/Models/ContentSettings.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Macros; - -namespace Umbraco.Configuration.Models -{ - internal class ContentSettings : IContentSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Content:"; - private const string NotificationsPrefix = Prefix + "Notifications:"; - private const string ImagingPrefix = Prefix + "Imaging:"; - private const string DefaultPreviewBadge = - @"
Preview modeClick to end
"; - - private static readonly ImagingAutoFillUploadField[] DefaultImagingAutoFillUploadField = - { - new ImagingAutoFillUploadField - { - Alias = Constants.Conventions.Media.File, - WidthFieldAlias = Constants.Conventions.Media.Width, - HeightFieldAlias =Constants.Conventions.Media.Height, - ExtensionFieldAlias =Constants.Conventions.Media.Extension, - LengthFieldAlias =Constants.Conventions.Media.Bytes, - } - }; - - private readonly IConfiguration _configuration; - - public ContentSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string NotificationEmailAddress => - _configuration.GetValue(NotificationsPrefix+"Email"); - - public bool DisableHtmlEmail => - _configuration.GetValue(NotificationsPrefix+"DisableHtmlEmail", false); - - public IEnumerable ImageFileTypes => _configuration.GetValue( - ImagingPrefix+"ImageFileTypes", new[] { "jpeg", "jpg", "gif", "bmp", "png", "tiff", "tif" }); - - public IEnumerable ImageAutoFillProperties => - _configuration.GetValue(ImagingPrefix+"AutoFillImageProperties", - DefaultImagingAutoFillUploadField); - - - public bool ResolveUrlsFromTextString => - _configuration.GetValue(Prefix+"ResolveUrlsFromTextString", false); - - public IEnumerable Error404Collection => _configuration - .GetSection(Prefix+"Errors:Error404") - .GetChildren() - .Select(x => new ContentErrorPage(x)); - - public string PreviewBadge => _configuration.GetValue(Prefix+"PreviewBadge", DefaultPreviewBadge); - - public MacroErrorBehaviour MacroErrorBehaviour => - _configuration.GetValue(Prefix+"MacroErrors", MacroErrorBehaviour.Inline); - - public IEnumerable DisallowedUploadFiles => _configuration.GetValue( - Prefix+"DisallowedUploadFiles", - new[] { "ashx", "aspx", "ascx", "config", "cshtml", "vbhtml", "asmx", "air", "axd" }); - - public IEnumerable AllowedUploadFiles => - _configuration.GetValue(Prefix+"AllowedUploadFiles", Array.Empty()); - - public bool ShowDeprecatedPropertyEditors => - _configuration.GetValue(Prefix+"ShowDeprecatedPropertyEditors", false); - - public string LoginBackgroundImage => - _configuration.GetValue(Prefix+"LoginBackgroundImage", "assets/img/login.jpg"); - - private class ContentErrorPage : IContentErrorPage - { - public ContentErrorPage(IConfigurationSection configurationSection) - { - Culture = configurationSection.Key; - - var value = configurationSection.Value; - - if (int.TryParse(value, out var contentId)) - { - HasContentId = true; - ContentId = contentId; - } - else if (Guid.TryParse(value, out var contentKey)) - { - HasContentKey = true; - ContentKey = contentKey; - } - else - { - ContentXPath = value; - } - } - - public int ContentId { get; } - public Guid ContentKey { get; } - public string ContentXPath { get; } - public bool HasContentId { get; } - public bool HasContentKey { get; } - public string Culture { get; set; } - } - - private class ImagingAutoFillUploadField : IImagingAutoFillUploadField - { - public string Alias { get; set; } - public string WidthFieldAlias { get; set; } - public string HeightFieldAlias { get; set; } - public string LengthFieldAlias { get; set; } - public string ExtensionFieldAlias { get; set; } - } - } -} diff --git a/src/Umbraco.Configuration/Models/CoreDebugSettings.cs b/src/Umbraco.Configuration/Models/CoreDebugSettings.cs deleted file mode 100644 index 6d6c0eaf0d..0000000000 --- a/src/Umbraco.Configuration/Models/CoreDebugSettings.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class CoreDebugSettings : ICoreDebugSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Core:Debug:"; - private readonly IConfiguration _configuration; - - public CoreDebugSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public bool LogUncompletedScopes => - _configuration.GetValue(Prefix+"LogUncompletedScopes", false); - - public bool DumpOnTimeoutThreadAbort => - _configuration.GetValue(Prefix+"DumpOnTimeoutThreadAbort", false); - } -} diff --git a/src/Umbraco.Configuration/Models/ExceptionFilterSettings.cs b/src/Umbraco.Configuration/Models/ExceptionFilterSettings.cs deleted file mode 100644 index 581daf9f40..0000000000 --- a/src/Umbraco.Configuration/Models/ExceptionFilterSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class ExceptionFilterSettings : IExceptionFilterSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "ExceptionFilter:"; - private readonly IConfiguration _configuration; - - public ExceptionFilterSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public bool Disabled => _configuration.GetValue(Prefix+"Disabled", false); - } -} diff --git a/src/Umbraco.Configuration/Models/GlobalSettings.cs b/src/Umbraco.Configuration/Models/GlobalSettings.cs deleted file mode 100644 index 02b73d1196..0000000000 --- a/src/Umbraco.Configuration/Models/GlobalSettings.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Linq; -using System.Net.Mail; -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - /// - /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information - /// from web.config appsettings - /// - internal class GlobalSettings : IGlobalSettings - { - private const string Prefix = Constants.Configuration.ConfigGlobalPrefix; - - internal const string - StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,"; //must end with a comma! - - internal const string - StaticReservedUrls = "~/config/splashes/noNodes.aspx,~/.well-known,"; //must end with a comma! - - private readonly IConfiguration _configuration; - - public GlobalSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string ReservedUrls => _configuration.GetValue(Prefix + "ReservedUrls", StaticReservedUrls); - public string ReservedPaths => _configuration.GetValue(Prefix + "ReservedPaths", StaticReservedPaths); - - // TODO: https://github.com/umbraco/Umbraco-CMS/issues/4238 - stop having version in web.config appSettings - public string ConfigurationStatus - { - get => _configuration.GetValue(Prefix + "ConfigurationStatus"); - set => throw new NotImplementedException("We should remove this and only use the value from database"); - } - - public int TimeOutInMinutes => _configuration.GetValue(Prefix + "TimeOutInMinutes", 20); - public string DefaultUILanguage => _configuration.GetValue(Prefix + "DefaultUILanguage", "en-US"); - - public bool HideTopLevelNodeFromPath => - _configuration.GetValue(Prefix + "HideTopLevelNodeFromPath", true); - - public bool UseHttps => _configuration.GetValue(Prefix + "UseHttps", false); - public int VersionCheckPeriod => _configuration.GetValue(Prefix + "VersionCheckPeriod", 7); - public string UmbracoPath => _configuration.GetValue(Prefix + "UmbracoPath", "~/umbraco"); - public string IconsPath => _configuration.GetValue(Prefix + "IconsPath", $"{UmbracoPath}/assets/icons"); - - public string UmbracoCssPath => _configuration.GetValue(Prefix + "UmbracoCssPath", "~/css"); - - public string UmbracoScriptsPath => - _configuration.GetValue(Prefix + "UmbracoScriptsPath", "~/scripts"); - - public string UmbracoMediaPath => _configuration.GetValue(Prefix + "UmbracoMediaPath", "~/media"); - - public bool InstallMissingDatabase => - _configuration.GetValue(Prefix + "InstallMissingDatabase", false); - - public bool InstallEmptyDatabase => _configuration.GetValue(Prefix + "InstallEmptyDatabase", false); - - public bool DisableElectionForSingleServer => - _configuration.GetValue(Prefix + "DisableElectionForSingleServer", false); - - public string RegisterType => _configuration.GetValue(Prefix + "RegisterType", string.Empty); - - public string DatabaseFactoryServerVersion => - _configuration.GetValue(Prefix + "DatabaseFactoryServerVersion", string.Empty); - - public string MainDomLock => _configuration.GetValue(Prefix + "MainDomLock", string.Empty); - - public string NoNodesViewPath => - _configuration.GetValue(Prefix + "NoNodesViewPath", "~/config/splashes/NoNodes.cshtml"); - - public bool IsSmtpServerConfigured => - _configuration.GetSection(Constants.Configuration.ConfigGlobalPrefix + "Smtp")?.GetChildren().Any() ?? false; - - public ISmtpSettings SmtpSettings => - new SmtpSettingsImpl(_configuration.GetSection(Constants.Configuration.ConfigGlobalPrefix + "Smtp")); - - private class SmtpSettingsImpl : ISmtpSettings - { - private readonly IConfigurationSection _configurationSection; - - public SmtpSettingsImpl(IConfigurationSection configurationSection) - { - _configurationSection = configurationSection; - } - - public string From => _configurationSection.GetValue("From"); - public string Host => _configurationSection.GetValue("Host"); - public int Port => _configurationSection.GetValue("Port"); - public string PickupDirectoryLocation => _configurationSection.GetValue("PickupDirectoryLocation"); - public SmtpDeliveryMethod DeliveryMethod => _configurationSection.GetValue("DeliveryMethod"); - - public string Username => _configurationSection.GetValue("Username"); - - public string Password => _configurationSection.GetValue("Password"); - } - } -} diff --git a/src/Umbraco.Configuration/Models/HealthChecksSettingsSettings.cs b/src/Umbraco.Configuration/Models/HealthChecksSettingsSettings.cs deleted file mode 100644 index 1e3751b6aa..0000000000 --- a/src/Umbraco.Configuration/Models/HealthChecksSettingsSettings.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.HealthChecks; - -namespace Umbraco.Configuration.Models -{ - internal class HealthChecksSettings : IHealthChecksSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "HealthChecks:"; - private readonly IConfiguration _configuration; - - public HealthChecksSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public IEnumerable DisabledChecks => _configuration - .GetSection(Prefix+"DisabledChecks") - .GetChildren() - .Select( - x => new DisabledHealthCheck - { - Id = x.GetValue("Id"), - DisabledOn = x.GetValue("DisabledOn"), - DisabledBy = x.GetValue("DisabledBy") - }); - - public IHealthCheckNotificationSettings NotificationSettings => - new HealthCheckNotificationSettings( - _configuration.GetSection(Prefix+"NotificationSettings")); - - private class DisabledHealthCheck : IDisabledHealthCheck - { - public Guid Id { get; set; } - public DateTime DisabledOn { get; set; } - public int DisabledBy { get; set; } - } - - private class HealthCheckNotificationSettings : IHealthCheckNotificationSettings - { - private readonly IConfigurationSection _configurationSection; - - public HealthCheckNotificationSettings(IConfigurationSection configurationSection) - { - _configurationSection = configurationSection; - } - - public bool Enabled => _configurationSection.GetValue("Enabled", false); - public string FirstRunTime => _configurationSection.GetValue("FirstRunTime"); - public int PeriodInHours => _configurationSection.GetValue("PeriodInHours", 24); - - public IReadOnlyDictionary NotificationMethods => _configurationSection - .GetSection("NotificationMethods") - .GetChildren() - .ToDictionary(x => x.Key, x => (INotificationMethod) new NotificationMethod(x.Key, x), StringComparer.InvariantCultureIgnoreCase); - - public IEnumerable DisabledChecks => _configurationSection - .GetSection("DisabledChecks").GetChildren().Select( - x => new DisabledHealthCheck - { - Id = x.GetValue("Id"), - DisabledOn = x.GetValue("DisabledOn"), - DisabledBy = x.GetValue("DisabledBy") - }); - } - - private class NotificationMethod : INotificationMethod - { - private readonly IConfigurationSection _configurationSection; - - public NotificationMethod(string alias, IConfigurationSection configurationSection) - { - Alias = alias; - _configurationSection = configurationSection; - } - - public string Alias { get; } - public bool Enabled => _configurationSection.GetValue("Enabled", false); - - public HealthCheckNotificationVerbosity Verbosity => - _configurationSection.GetValue("Verbosity", HealthCheckNotificationVerbosity.Summary); - - public bool FailureOnly => _configurationSection.GetValue("FailureOnly", true); - - public IReadOnlyDictionary Settings => _configurationSection - .GetSection("Settings").GetChildren().ToDictionary(x => x.Key, - x => (INotificationMethodSettings) new NotificationMethodSettings(x.Key, x.Value), StringComparer.InvariantCultureIgnoreCase); - } - - private class NotificationMethodSettings : INotificationMethodSettings - { - public NotificationMethodSettings(string key, string value) - { - Key = key; - Value = value; - } - - public string Key { get; } - public string Value { get; } - } - } -} diff --git a/src/Umbraco.Configuration/Models/HostingSettings.cs b/src/Umbraco.Configuration/Models/HostingSettings.cs deleted file mode 100644 index f0fbcf4cab..0000000000 --- a/src/Umbraco.Configuration/Models/HostingSettings.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class HostingSettings : IHostingSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Hosting:"; - private readonly IConfiguration _configuration; - - public HostingSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - /// - public LocalTempStorage LocalTempStorageLocation => - _configuration.GetValue(Prefix+"LocalTempStorage", LocalTempStorage.Default); - - public string ApplicationVirtualPath => null; - - /// - /// Gets a value indicating whether umbraco is running in [debug mode]. - /// - /// true if [debug mode]; otherwise, false. - public bool DebugMode => _configuration.GetValue(Prefix+"Debug", false); - } -} diff --git a/src/Umbraco.Configuration/Models/ImagingSettings.cs b/src/Umbraco.Configuration/Models/ImagingSettings.cs deleted file mode 100644 index 4a9501b2ba..0000000000 --- a/src/Umbraco.Configuration/Models/ImagingSettings.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class ImagingSettings : IImagingSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Imaging:"; - private const string CachePrefix = Prefix + "Cache:"; - private const string ResizePrefix = Prefix + "Resize:"; - private readonly IConfiguration _configuration; - - public ImagingSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public int MaxBrowserCacheDays => _configuration.GetValue(CachePrefix + "MaxBrowserCacheDays", 7); - public int MaxCacheDays => _configuration.GetValue(CachePrefix + "MaxCacheDays", 365); - public uint CachedNameLength => _configuration.GetValue(CachePrefix + "CachedNameLength", (uint) 8); - public string CacheFolder => _configuration.GetValue(CachePrefix + "Folder", "../App_Data/Cache"); - public int MaxResizeWidth => _configuration.GetValue(ResizePrefix + "MaxWidth", 5000); - public int MaxResizeHeight => _configuration.GetValue(ResizePrefix + "MaxHeight", 5000); - } -} diff --git a/src/Umbraco.Configuration/Models/IndexCreatorSettings.cs b/src/Umbraco.Configuration/Models/IndexCreatorSettings.cs deleted file mode 100644 index b4bb000552..0000000000 --- a/src/Umbraco.Configuration/Models/IndexCreatorSettings.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class IndexCreatorSettings : IIndexCreatorSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Examine:"; - private readonly IConfiguration _configuration; - - public IndexCreatorSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string LuceneDirectoryFactory => - _configuration.GetValue(Prefix + "LuceneDirectoryFactory"); - } -} diff --git a/src/Umbraco.Configuration/Models/KeepAliveSettings.cs b/src/Umbraco.Configuration/Models/KeepAliveSettings.cs deleted file mode 100644 index 04194e1a3c..0000000000 --- a/src/Umbraco.Configuration/Models/KeepAliveSettings.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Models -{ - internal class KeepAliveSettings : IKeepAliveSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "KeepAlive:"; - private readonly IConfiguration _configuration; - - public KeepAliveSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public bool DisableKeepAliveTask => - _configuration.GetValue(Prefix + "DisableKeepAliveTask", false); - - public string KeepAlivePingUrl => _configuration.GetValue(Prefix + "KeepAlivePingUrl", - "{umbracoApplicationUrl}/api/keepalive/ping"); - } -} diff --git a/src/Umbraco.Configuration/Models/LoggingSettings.cs b/src/Umbraco.Configuration/Models/LoggingSettings.cs deleted file mode 100644 index b05fe03875..0000000000 --- a/src/Umbraco.Configuration/Models/LoggingSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Models -{ - internal class LoggingSettings : ILoggingSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Logging:"; - private readonly IConfiguration _configuration; - - public LoggingSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public int MaxLogAge => _configuration.GetValue(Prefix + "MaxLogAge", -1); - } -} diff --git a/src/Umbraco.Configuration/Models/MemberPasswordConfigurationSettings.cs b/src/Umbraco.Configuration/Models/MemberPasswordConfigurationSettings.cs deleted file mode 100644 index 5a8313a351..0000000000 --- a/src/Umbraco.Configuration/Models/MemberPasswordConfigurationSettings.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class MemberPasswordConfigurationSettings : IMemberPasswordConfiguration - { - private const string Prefix = Constants.Configuration.ConfigSecurityPrefix + "MemberPassword:"; - private readonly IConfiguration _configuration; - - public MemberPasswordConfigurationSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public int RequiredLength => - _configuration.GetValue(Prefix + "RequiredLength", 10); - - public bool RequireNonLetterOrDigit => - _configuration.GetValue(Prefix + "RequireNonLetterOrDigit", false); - - public bool RequireDigit => - _configuration.GetValue(Prefix + "RequireDigit", false); - - public bool RequireLowercase => - _configuration.GetValue(Prefix + "RequireLowercase", false); - - public bool RequireUppercase => - _configuration.GetValue(Prefix + "RequireUppercase", false); - - public string HashAlgorithmType => - _configuration.GetValue(Prefix + "HashAlgorithmType", Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); // TODO: Need to change to current format when we do members - - public int MaxFailedAccessAttemptsBeforeLockout => - _configuration.GetValue(Prefix + "MaxFailedAccessAttemptsBeforeLockout", 5); - } -} diff --git a/src/Umbraco.Configuration/Models/NuCacheSettings.cs b/src/Umbraco.Configuration/Models/NuCacheSettings.cs deleted file mode 100644 index 51b8b1fe08..0000000000 --- a/src/Umbraco.Configuration/Models/NuCacheSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class NuCacheSettings : INuCacheSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "NuCache:"; - private readonly IConfiguration _configuration; - - public NuCacheSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string BTreeBlockSize => _configuration.GetValue(Prefix+"BTreeBlockSize"); - } -} diff --git a/src/Umbraco.Configuration/Models/RuntimeSettings.cs b/src/Umbraco.Configuration/Models/RuntimeSettings.cs deleted file mode 100644 index ef129030b6..0000000000 --- a/src/Umbraco.Configuration/Models/RuntimeSettings.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class RuntimeSettings : IRuntimeSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Runtime:"; - private readonly IConfiguration _configuration; - public RuntimeSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public int? MaxQueryStringLength => _configuration.GetValue(Prefix+"MaxRequestLength"); - public int? MaxRequestLength => _configuration.GetValue(Prefix+"MaxRequestLength"); - } -} diff --git a/src/Umbraco.Configuration/Models/SecuritySettings.cs b/src/Umbraco.Configuration/Models/SecuritySettings.cs deleted file mode 100644 index 297c95b1af..0000000000 --- a/src/Umbraco.Configuration/Models/SecuritySettings.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Models -{ - internal class SecuritySettings : ISecuritySettings - { - private const string Prefix = Constants.Configuration.ConfigSecurityPrefix; - private readonly IConfiguration _configuration; - - public SecuritySettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public bool KeepUserLoggedIn => _configuration.GetValue(Prefix + "KeepUserLoggedIn", false); - - public bool HideDisabledUsersInBackoffice => - _configuration.GetValue(Prefix + "HideDisabledUsersInBackoffice", false); - - public bool AllowPasswordReset => - _configuration.GetValue(Prefix + "AllowPasswordResetAllowPasswordReset", true); - - public string AuthCookieName => - _configuration.GetValue(Prefix + "AuthCookieName", "UMB_UCONTEXT"); - - public string AuthCookieDomain => - _configuration.GetValue(Prefix + "AuthCookieDomain"); - - public bool UsernameIsEmail => _configuration.GetValue(Prefix + "UsernameIsEmail", true); - } -} diff --git a/src/Umbraco.Configuration/Models/TourSettings.cs b/src/Umbraco.Configuration/Models/TourSettings.cs deleted file mode 100644 index 9fe1814ff5..0000000000 --- a/src/Umbraco.Configuration/Models/TourSettings.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Configuration.Models -{ - internal class TourSettings : ITourSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "Tours:"; - private readonly IConfiguration _configuration; - - public TourSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string Type { get; set; } - - public bool EnableTours => _configuration.GetValue(Prefix+"EnableTours", true); - } -} diff --git a/src/Umbraco.Configuration/Models/TypeFinderSettings.cs b/src/Umbraco.Configuration/Models/TypeFinderSettings.cs deleted file mode 100644 index 8a1f7ac9e0..0000000000 --- a/src/Umbraco.Configuration/Models/TypeFinderSettings.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class TypeFinderSettings : ITypeFinderSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "TypeFinder:"; - private readonly IConfiguration _configuration; - - public TypeFinderSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public string AssembliesAcceptingLoadExceptions => - _configuration.GetValue(Prefix+"AssembliesAcceptingLoadExceptions"); - } -} diff --git a/src/Umbraco.Configuration/Models/UserPasswordConfigurationSettings.cs b/src/Umbraco.Configuration/Models/UserPasswordConfigurationSettings.cs deleted file mode 100644 index 25ce3e3d9a..0000000000 --- a/src/Umbraco.Configuration/Models/UserPasswordConfigurationSettings.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Configuration.Models -{ - internal class UserPasswordConfigurationSettings : IUserPasswordConfiguration - { - private const string Prefix = Constants.Configuration.ConfigSecurityPrefix + "UserPassword:"; - private readonly IConfiguration _configuration; - - public UserPasswordConfigurationSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public int RequiredLength => _configuration.GetValue(Prefix + "RequiredLength", 10); - - public bool RequireNonLetterOrDigit => - _configuration.GetValue(Prefix + "RequireNonLetterOrDigit", false); - - public bool RequireDigit => _configuration.GetValue(Prefix + "RequireDigit", false); - - public bool RequireLowercase => - _configuration.GetValue(Prefix + "RequireLowercase", false); - - public bool RequireUppercase => - _configuration.GetValue(Prefix + "RequireUppercase", false); - - public string HashAlgorithmType => - _configuration.GetValue(Prefix + "HashAlgorithmType", Constants.Security.AspNetCoreV3PasswordHashAlgorithmName); - - public int MaxFailedAccessAttemptsBeforeLockout => - _configuration.GetValue(Prefix + "MaxFailedAccessAttemptsBeforeLockout", 5); - } -} diff --git a/src/Umbraco.Configuration/Models/WebRoutingSettings.cs b/src/Umbraco.Configuration/Models/WebRoutingSettings.cs deleted file mode 100644 index 9ac856ca9f..0000000000 --- a/src/Umbraco.Configuration/Models/WebRoutingSettings.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Models.PublishedContent; - -namespace Umbraco.Configuration.Models -{ - internal class WebRoutingSettings : IWebRoutingSettings - { - private const string Prefix = Constants.Configuration.ConfigPrefix + "WebRouting:"; - private readonly IConfiguration _configuration; - - public WebRoutingSettings(IConfiguration configuration) - { - _configuration = configuration; - } - - public bool TrySkipIisCustomErrors => - _configuration.GetValue(Prefix + "TrySkipIisCustomErrors", false); - - public bool InternalRedirectPreservesTemplate => - _configuration.GetValue(Prefix + "InternalRedirectPreservesTemplate", false); - - public bool DisableAlternativeTemplates => - _configuration.GetValue(Prefix + "DisableAlternativeTemplates", false); - - public bool ValidateAlternativeTemplates => - _configuration.GetValue(Prefix + "ValidateAlternativeTemplates", false); - - public bool DisableFindContentByIdPath => - _configuration.GetValue(Prefix + "DisableFindContentByIdPath", false); - - public bool DisableRedirectUrlTracking => - _configuration.GetValue(Prefix + "DisableRedirectUrlTracking", false); - - public string UrlProviderMode => - _configuration.GetValue(Prefix + "UrlProviderMode", UrlMode.Auto.ToString()); - - public string UmbracoApplicationUrl => - _configuration.GetValue(Prefix + "UmbracoApplicationUrl"); - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/BackOfficeElement.cs b/src/Umbraco.Configuration/UmbracoSettings/BackOfficeElement.cs deleted file mode 100644 index 46b9bf32a9..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/BackOfficeElement.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class BackOfficeElement : UmbracoConfigurationElement, IBackOfficeSection - { - [ConfigurationProperty("tours")] - internal TourConfigElement Tours => (TourConfigElement)this["tours"]; - - ITourSettings IBackOfficeSection.Tours => Tours; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/CharCollection.cs b/src/Umbraco.Configuration/UmbracoSettings/CharCollection.cs deleted file mode 100644 index 7b62fcc123..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/CharCollection.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class CharCollection : ConfigurationElementCollection, IEnumerable - { - internal void Add(CharElement c) - { - BaseAdd(c); - } - - protected override ConfigurationElement CreateNewElement() - { - return new CharElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((CharElement)element).Char; - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as IChar; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/CharElement.cs b/src/Umbraco.Configuration/UmbracoSettings/CharElement.cs deleted file mode 100644 index 1ff63ac017..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/CharElement.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class CharElement : InnerTextConfigurationElement, IChar - { - private string _char; - private string _replacement; - - internal string Char - { - get => _char ?? (_char = (string)RawXml.Attribute("org")); - set => _char = value; - } - - internal string Replacement - { - get => _replacement ?? (_replacement = Value); - set => _replacement = value; - } - - string IChar.Char => Char; - - string IChar.Replacement => Replacement; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ContentElement.cs b/src/Umbraco.Configuration/UmbracoSettings/ContentElement.cs deleted file mode 100644 index 28b4314c9a..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ContentElement.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; -using Umbraco.Core.Macros; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ContentElement : UmbracoConfigurationElement, IContentSettings - { - private const string DefaultPreviewBadge = @"
Preview modeClick to end
"; - - [ConfigurationProperty("imaging")] - internal ContentImagingElement Imaging => (ContentImagingElement) this["imaging"]; - - [ConfigurationProperty("ResolveUrlsFromTextString")] - internal InnerTextConfigurationElement ResolveUrlsFromTextString => GetOptionalTextElement("ResolveUrlsFromTextString", false); - - public IEnumerable Error404Collection => Errors.Error404Collection; - - [ConfigurationProperty("errors", IsRequired = true)] - internal ContentErrorsElement Errors => (ContentErrorsElement) base["errors"]; - - [ConfigurationProperty("notifications", IsRequired = true)] - internal NotificationsElement Notifications => (NotificationsElement) base["notifications"]; - - [ConfigurationProperty("PreviewBadge")] - internal InnerTextConfigurationElement PreviewBadge => GetOptionalTextElement("PreviewBadge", DefaultPreviewBadge); - - [ConfigurationProperty("MacroErrors")] - internal InnerTextConfigurationElement MacroErrors => GetOptionalTextElement("MacroErrors", MacroErrorBehaviour.Inline); - - [ConfigurationProperty("disallowedUploadFiles")] - internal CommaDelimitedConfigurationElement DisallowedUploadFiles => GetOptionalDelimitedElement("disallowedUploadFiles", new[] {"ashx", "aspx", "ascx", "config", "cshtml", "vbhtml", "asmx", "air", "axd"}); - - [ConfigurationProperty("allowedUploadFiles")] - internal CommaDelimitedConfigurationElement AllowedUploadFiles => GetOptionalDelimitedElement("allowedUploadFiles", new string[0]); - - [ConfigurationProperty("showDeprecatedPropertyEditors")] - internal InnerTextConfigurationElement ShowDeprecatedPropertyEditors => GetOptionalTextElement("showDeprecatedPropertyEditors", false); - - [ConfigurationProperty("loginBackgroundImage")] - internal InnerTextConfigurationElement LoginBackgroundImage => GetOptionalTextElement("loginBackgroundImage", string.Empty); - - string IContentSettings.NotificationEmailAddress => Notifications.NotificationEmailAddress; - - bool IContentSettings.DisableHtmlEmail => Notifications.DisableHtmlEmail; - - IEnumerable IContentSettings.ImageFileTypes => Imaging.ImageFileTypes; - - IEnumerable IContentSettings.ImageAutoFillProperties => Imaging.ImageAutoFillProperties; - - bool IContentSettings.ResolveUrlsFromTextString => ResolveUrlsFromTextString; - - string IContentSettings.PreviewBadge => PreviewBadge; - - MacroErrorBehaviour IContentSettings.MacroErrorBehaviour => MacroErrors; - - IEnumerable IContentSettings.DisallowedUploadFiles => DisallowedUploadFiles; - - IEnumerable IContentSettings.AllowedUploadFiles => AllowedUploadFiles; - - bool IContentSettings.ShowDeprecatedPropertyEditors => ShowDeprecatedPropertyEditors; - - string IContentSettings.LoginBackgroundImage => LoginBackgroundImage; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ContentError404Collection.cs b/src/Umbraco.Configuration/UmbracoSettings/ContentError404Collection.cs deleted file mode 100644 index bdbcb27b4c..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ContentError404Collection.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ContentError404Collection : ConfigurationElementCollection, IEnumerable - { - internal void Add(ContentErrorPageElement element) - { - BaseAdd(element); - } - - protected override ConfigurationElement CreateNewElement() - { - return new ContentErrorPageElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((ContentErrorPageElement)element).Culture - + ((ContentErrorPageElement)element).Value; - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as ContentErrorPageElement; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ContentErrorPageElement.cs b/src/Umbraco.Configuration/UmbracoSettings/ContentErrorPageElement.cs deleted file mode 100644 index 96cea71a8e..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ContentErrorPageElement.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Xml.Linq; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ContentErrorPageElement : InnerTextConfigurationElement, IContentErrorPage - { - public ContentErrorPageElement(XElement rawXml) - : base(rawXml) - { - } - - public ContentErrorPageElement() - { - - } - - public bool HasContentId => ContentId != int.MinValue; - - public bool HasContentKey => ContentKey != Guid.Empty; - - public int ContentId - { - get - { - int parsed; - if (int.TryParse(Value, out parsed)) - { - return parsed; - } - return int.MinValue; - } - } - - public Guid ContentKey - { - get - { - Guid parsed; - if (Guid.TryParse(Value, out parsed)) - { - return parsed; - } - return Guid.Empty; - } - } - - public string ContentXPath => Value; - - public string Culture - { - get => (string) RawXml.Attribute("culture"); - set => RawXml.Attribute("culture").Value = value; - } - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ContentErrorsElement.cs b/src/Umbraco.Configuration/UmbracoSettings/ContentErrorsElement.cs deleted file mode 100644 index 5b5b54380d..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ContentErrorsElement.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ContentErrorsElement : RawXmlConfigurationElement - { - - public IEnumerable Error404Collection - { - get - { - var result = new ContentError404Collection(); - if (RawXml != null) - { - var e404 = RawXml.Elements("error404").First(); - var ePages = e404.Elements("errorPage").ToArray(); - if (ePages.Any()) - { - //there are multiple - foreach (var e in ePages) - { - result.Add(new ContentErrorPageElement(e) - { - Culture = (string)e.Attribute("culture"), - RawValue = e.Value - }); - } - } - else - { - //there's only one defined - result.Add(new ContentErrorPageElement(e404) - { - RawValue = e404.Value - }); - } - } - return result; - } - } - - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ContentImagingElement.cs b/src/Umbraco.Configuration/UmbracoSettings/ContentImagingElement.cs deleted file mode 100644 index 9a5a9b2a59..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ContentImagingElement.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ContentImagingElement : ConfigurationElement - { - - [ConfigurationProperty("imageFileTypes")] - internal CommaDelimitedConfigurationElement ImageFileTypes => - new OptionalCommaDelimitedConfigurationElement( - (CommaDelimitedConfigurationElement)this["imageFileTypes"], - //set the default - GetDefaultImageFileTypes()); - - public static string[] GetDefaultImageFileTypes() - { - return new[] {"jpeg", "jpg", "gif", "bmp", "png", "tiff", "tif"}; - } - - private ImagingAutoFillPropertiesCollection _defaultImageAutoFill; - - [ConfigurationCollection(typeof(ImagingAutoFillPropertiesCollection), AddItemName = "uploadField")] - [ConfigurationProperty("autoFillImageProperties", IsDefaultCollection = true)] - internal ImagingAutoFillPropertiesCollection ImageAutoFillProperties - { - get - { - if (_defaultImageAutoFill != null) - { - return _defaultImageAutoFill; - } - - //here we need to check if this element is defined, if it is not then we'll setup the defaults - var prop = Properties["autoFillImageProperties"]; - var autoFill = this[prop] as ConfigurationElement; - if (autoFill != null && autoFill.ElementInformation.IsPresent == false) - { - _defaultImageAutoFill = new ImagingAutoFillPropertiesCollection - { - new ImagingAutoFillUploadFieldElement - { - Alias = "umbracoFile" - } - }; - return _defaultImageAutoFill; - } - - return (ImagingAutoFillPropertiesCollection) base["autoFillImageProperties"]; - } - } - - public static ImagingAutoFillPropertiesCollection GetDefaultImageAutoFillProperties() - { - return new ImagingAutoFillPropertiesCollection - { - new ImagingAutoFillUploadFieldElement - { - Alias = "umbracoFile" - } - }; - } - - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillPropertiesCollection.cs b/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillPropertiesCollection.cs deleted file mode 100644 index 0bac9721a3..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillPropertiesCollection.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ImagingAutoFillPropertiesCollection : ConfigurationElementCollection, IEnumerable - { - - protected override ConfigurationElement CreateNewElement() - { - return new ImagingAutoFillUploadFieldElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((ImagingAutoFillUploadFieldElement)element).Alias; - } - - internal void Add(ImagingAutoFillUploadFieldElement item) - { - BaseAdd(item); - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as IImagingAutoFillUploadField; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillUploadFieldElement.cs b/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillUploadFieldElement.cs deleted file mode 100644 index 9b4c45b5c6..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/ImagingAutoFillUploadFieldElement.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ImagingAutoFillUploadFieldElement : UmbracoConfigurationElement, IImagingAutoFillUploadField - { - /// - /// Allow setting internally so we can create a default - /// - [ConfigurationProperty("alias", IsKey = true, IsRequired = true)] - public string Alias - { - get => (string)this["alias"]; - set => this["alias"] = value; - } - - [ConfigurationProperty("widthFieldAlias")] - internal InnerTextConfigurationElement WidthFieldAlias => GetOptionalTextElement("widthFieldAlias", "umbracoWidth"); - - [ConfigurationProperty("heightFieldAlias")] - internal InnerTextConfigurationElement HeightFieldAlias => GetOptionalTextElement("heightFieldAlias", "umbracoHeight"); - - [ConfigurationProperty("lengthFieldAlias")] - internal InnerTextConfigurationElement LengthFieldAlias => GetOptionalTextElement("lengthFieldAlias", "umbracoBytes"); - - [ConfigurationProperty("extensionFieldAlias")] - internal InnerTextConfigurationElement ExtensionFieldAlias => GetOptionalTextElement("extensionFieldAlias", "umbracoExtension"); - - string IImagingAutoFillUploadField.Alias => Alias; - - string IImagingAutoFillUploadField.WidthFieldAlias => WidthFieldAlias; - - string IImagingAutoFillUploadField.HeightFieldAlias => HeightFieldAlias; - - string IImagingAutoFillUploadField.LengthFieldAlias => LengthFieldAlias; - - string IImagingAutoFillUploadField.ExtensionFieldAlias => ExtensionFieldAlias; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/KeepAliveElement.cs b/src/Umbraco.Configuration/UmbracoSettings/KeepAliveElement.cs deleted file mode 100644 index 2297fb4e20..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/KeepAliveElement.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class KeepAliveElement : ConfigurationElement, IKeepAliveSettings - { - [ConfigurationProperty("disableKeepAliveTask", DefaultValue = "false")] - public bool DisableKeepAliveTask => (bool)base["disableKeepAliveTask"]; - - [ConfigurationProperty("keepAlivePingUrl", DefaultValue = "{umbracoApplicationUrl}/api/keepalive/ping")] - public string KeepAlivePingUrl => (string)base["keepAlivePingUrl"]; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/LoggingElement.cs b/src/Umbraco.Configuration/UmbracoSettings/LoggingElement.cs deleted file mode 100644 index 2fdd61e169..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/LoggingElement.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class LoggingElement : UmbracoConfigurationElement, ILoggingSettings - { - - [ConfigurationProperty("maxLogAge")] - internal InnerTextConfigurationElement MaxLogAge => GetOptionalTextElement("maxLogAge", -1); - - int ILoggingSettings.MaxLogAge => MaxLogAge; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/MemberPasswordConfigurationElement.cs b/src/Umbraco.Configuration/UmbracoSettings/MemberPasswordConfigurationElement.cs deleted file mode 100644 index 92cd112630..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/MemberPasswordConfigurationElement.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class MemberPasswordConfigurationElement : PasswordConfigurationElement, IMemberPasswordConfiguration - { - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/NotificationsElement.cs b/src/Umbraco.Configuration/UmbracoSettings/NotificationsElement.cs deleted file mode 100644 index afadff5654..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/NotificationsElement.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class NotificationsElement : UmbracoConfigurationElement - { - [ConfigurationProperty("email")] - internal InnerTextConfigurationElement NotificationEmailAddress => (InnerTextConfigurationElement)this["email"]; - - [ConfigurationProperty("disableHtmlEmail")] - internal InnerTextConfigurationElement DisableHtmlEmail => GetOptionalTextElement("disableHtmlEmail", false); - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/PasswordConfigurationElement.cs b/src/Umbraco.Configuration/UmbracoSettings/PasswordConfigurationElement.cs deleted file mode 100644 index 91b5cae7a4..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/PasswordConfigurationElement.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class PasswordConfigurationElement : UmbracoConfigurationElement - { - [ConfigurationProperty("requiredLength", DefaultValue = "12")] - public int RequiredLength => (int)base["requiredLength"]; - - [ConfigurationProperty("requireNonLetterOrDigit", DefaultValue = "false")] - public bool RequireNonLetterOrDigit => (bool)base["requireNonLetterOrDigit"]; - - [ConfigurationProperty("requireDigit", DefaultValue = "false")] - public bool RequireDigit => (bool)base["requireDigit"]; - - [ConfigurationProperty("requireLowercase", DefaultValue = "false")] - public bool RequireLowercase => (bool)base["requireLowercase"]; - - [ConfigurationProperty("requireUppercase", DefaultValue = "false")] - public bool RequireUppercase => (bool)base["requireUppercase"]; - - [ConfigurationProperty("useLegacyEncoding", DefaultValue = "false")] - public bool UseLegacyEncoding => (bool)base["useLegacyEncoding"]; - - [ConfigurationProperty("hashAlgorithmType", DefaultValue = Constants.Security.AspNetCoreV3PasswordHashAlgorithmName)] - public string HashAlgorithmType => (string)base["hashAlgorithmType"]; - - [ConfigurationProperty("maxFailedAccessAttemptsBeforeLockout", DefaultValue = "5")] - public int MaxFailedAccessAttemptsBeforeLockout => (int)base["maxFailedAccessAttemptsBeforeLockout"]; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/RequestHandlerElement.cs b/src/Umbraco.Configuration/UmbracoSettings/RequestHandlerElement.cs deleted file mode 100644 index f959a56e71..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/RequestHandlerElement.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.Configuration; -using System.Globalization; -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class RequestHandlerElement : UmbracoConfigurationElement, IRequestHandlerSettings - { - [ConfigurationProperty("addTrailingSlash")] - public InnerTextConfigurationElement AddTrailingSlash => GetOptionalTextElement("addTrailingSlash", true); - - private UrlReplacingElement _defaultUrlReplacing; - [ConfigurationProperty("urlReplacing")] - public UrlReplacingElement UrlReplacing - { - get - { - if (_defaultUrlReplacing != null) - { - return _defaultUrlReplacing; - } - - //here we need to check if this element is defined, if it is not then we'll setup the defaults - var prop = Properties["urlReplacing"]; - var urls = this[prop] as ConfigurationElement; - if (urls != null && urls.ElementInformation.IsPresent == false) - { - _defaultUrlReplacing = new UrlReplacingElement() - { - CharCollection = GetDefaultCharReplacements() - }; - - return _defaultUrlReplacing; - } - - return (UrlReplacingElement)this["urlReplacing"]; - } - } - - public static CharCollection GetDefaultCharReplacements() - { - var dictionary = new Dictionary() - { - {' ',"-"}, - {'\"',""}, - {'\'',""}, - {'%',""}, - {'.',""}, - {';',""}, - {'/',""}, - {'\\',""}, - {':',""}, - {'#',""}, - {'+',"plus"}, - {'*',"star"}, - {'&',""}, - {'?',""}, - {'æ',"ae"}, - {'ø',"oe"}, - {'å',"aa"}, - {'ä',"ae"}, - {'ö',"oe"}, - {'ü',"ue"}, - {'ß',"ss"}, - {'Ä',"ae"}, - {'Ö',"oe"}, - {'|',"-"}, - {'<',""}, - {'>',""} - }; - - //const string chars = @" ,"",',%,.,;,/,\,:,#,+,*,&,?,æ,ø,å,ä,ö,ü,ß,Ä,Ö,|,<,>"; - - var collection = new CharCollection(); - foreach (var c in dictionary) - { - collection.Add(new CharElement - { - Char = c.Key.ToString(CultureInfo.InvariantCulture), - Replacement = c.Value.ToString(CultureInfo.InvariantCulture) - }); - } - - return collection; - } - - bool IRequestHandlerSettings.AddTrailingSlash => AddTrailingSlash; - - bool IRequestHandlerSettings.ConvertUrlsToAscii => UrlReplacing.ConvertUrlsToAscii.InvariantEquals("true"); - - bool IRequestHandlerSettings.TryConvertUrlsToAscii => UrlReplacing.ConvertUrlsToAscii.InvariantEquals("try"); - - IEnumerable IRequestHandlerSettings.CharCollection => UrlReplacing.CharCollection; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/SecurityElement.cs b/src/Umbraco.Configuration/UmbracoSettings/SecurityElement.cs deleted file mode 100644 index aec6809298..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/SecurityElement.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class SecurityElement : UmbracoConfigurationElement, ISecuritySettings - { - [ConfigurationProperty("keepUserLoggedIn")] - internal InnerTextConfigurationElement KeepUserLoggedIn => GetOptionalTextElement("keepUserLoggedIn", true); - - [ConfigurationProperty("hideDisabledUsersInBackoffice")] - internal InnerTextConfigurationElement HideDisabledUsersInBackoffice => GetOptionalTextElement("hideDisabledUsersInBackoffice", false); - - /// - /// Used to enable/disable the forgot password functionality on the back office login screen - /// - [ConfigurationProperty("allowPasswordReset")] - internal InnerTextConfigurationElement AllowPasswordReset => GetOptionalTextElement("allowPasswordReset", true); - - /// - /// A boolean indicating that by default the email address will be the username - /// - /// - /// Even if this is true and the username is different from the email in the database, the username field will still be shown. - /// When this is false, the username and email fields will be shown in the user section. - /// - [ConfigurationProperty("usernameIsEmail")] - internal InnerTextConfigurationElement UsernameIsEmail => GetOptionalTextElement("usernameIsEmail", true); - - [ConfigurationProperty("authCookieName")] - internal InnerTextConfigurationElement AuthCookieName => GetOptionalTextElement("authCookieName", "UMB_UCONTEXT"); - - [ConfigurationProperty("authCookieDomain")] - internal InnerTextConfigurationElement AuthCookieDomain => GetOptionalTextElement("authCookieDomain", null); - - [ConfigurationProperty("userPasswordConfiguration")] - public UserPasswordConfigurationElement UserPasswordConfiguration => (UserPasswordConfigurationElement)this["userPasswordConfiguration"]; - - [ConfigurationProperty("memberPasswordConfiguration")] - public MemberPasswordConfigurationElement MemberPasswordConfiguration => (MemberPasswordConfigurationElement)this["memberPasswordConfiguration"]; - - bool ISecuritySettings.KeepUserLoggedIn => KeepUserLoggedIn; - - bool ISecuritySettings.HideDisabledUsersInBackoffice => HideDisabledUsersInBackoffice; - - /// - /// Used to enable/disable the forgot password functionality on the back office login screen - /// - bool ISecuritySettings.AllowPasswordReset => AllowPasswordReset; - - /// - /// A boolean indicating that by default the email address will be the username - /// - /// - /// Even if this is true and the username is different from the email in the database, the username field will still be shown. - /// When this is false, the username and email fields will be shown in the user section. - /// - bool ISecuritySettings.UsernameIsEmail => UsernameIsEmail; - - string ISecuritySettings.AuthCookieName => AuthCookieName; - - string ISecuritySettings.AuthCookieDomain => AuthCookieDomain; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/TourConfigElement.cs b/src/Umbraco.Configuration/UmbracoSettings/TourConfigElement.cs deleted file mode 100644 index f75b71fc57..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/TourConfigElement.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class TourConfigElement : UmbracoConfigurationElement, ITourSettings - { - //disabled by default so that upgraders don't get it enabled by default - // TODO: we probably just want to disable the initial one from automatically loading ? - [ConfigurationProperty("enable", DefaultValue = false)] - public bool EnableTours => (bool)this["enable"]; - - // TODO: We could have additional filters, etc... defined here - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/UmbracoConfigurationElement.cs b/src/Umbraco.Configuration/UmbracoSettings/UmbracoConfigurationElement.cs deleted file mode 100644 index 670f620b15..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/UmbracoConfigurationElement.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Concurrent; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - /// - /// Base class with shared helper methods - /// - internal class UmbracoConfigurationElement : ConfigurationElement - { - /// - /// Used so the RawElement types are not re-created every time they are accessed - /// - private readonly ConcurrentDictionary _rawElements = new ConcurrentDictionary(); - - protected OptionalInnerTextConfigurationElement GetOptionalTextElement(string name, T defaultVal) - { - return (OptionalInnerTextConfigurationElement) _rawElements.GetOrAdd( - name, - s => new OptionalInnerTextConfigurationElement( - (InnerTextConfigurationElement) this[s], - //set the default - defaultVal)); - } - - protected OptionalCommaDelimitedConfigurationElement GetOptionalDelimitedElement(string name, string[] defaultVal) - { - return (OptionalCommaDelimitedConfigurationElement) _rawElements.GetOrAdd( - name, - s => new OptionalCommaDelimitedConfigurationElement( - (CommaDelimitedConfigurationElement) this[name], - //set the default - defaultVal)); - } - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsSection.cs b/src/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsSection.cs deleted file mode 100644 index 781d00b979..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsSection.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class UmbracoSettingsSection : ConfigurationSection - { - [ConfigurationProperty("backOffice")] - public BackOfficeElement BackOffice => (BackOfficeElement)this["backOffice"]; - - [ConfigurationProperty("content")] - public ContentElement Content => (ContentElement)this["content"]; - - [ConfigurationProperty("security")] - public SecurityElement Security => (SecurityElement)this["security"]; - - [ConfigurationProperty("requestHandler")] - public RequestHandlerElement RequestHandler => (RequestHandlerElement)this["requestHandler"]; - - [ConfigurationProperty("logging")] - public LoggingElement Logging => (LoggingElement)this["logging"]; - - [ConfigurationProperty("web.routing")] - public WebRoutingElement WebRouting => (WebRoutingElement)this["web.routing"]; - - [ConfigurationProperty("keepAlive")] - internal KeepAliveElement KeepAlive => (KeepAliveElement)this["keepAlive"]; - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/UrlReplacingElement.cs b/src/Umbraco.Configuration/UmbracoSettings/UrlReplacingElement.cs deleted file mode 100644 index 3e12d106ff..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/UrlReplacingElement.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class UrlReplacingElement : ConfigurationElement - { - [ConfigurationProperty("removeDoubleDashes", DefaultValue = true)] - internal bool RemoveDoubleDashes => (bool) base["removeDoubleDashes"]; - - [ConfigurationProperty("toAscii", DefaultValue = "false")] - internal string ConvertUrlsToAscii => (string) base["toAscii"]; - - [ConfigurationCollection(typeof(CharCollection), AddItemName = "char")] - [ConfigurationProperty("", IsDefaultCollection = true)] - internal CharCollection CharCollection - { - get => (CharCollection)base[""]; - set => base[""] = value; - } - - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/UserPasswordConfigurationElement.cs b/src/Umbraco.Configuration/UmbracoSettings/UserPasswordConfigurationElement.cs deleted file mode 100644 index a1d2aa8842..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/UserPasswordConfigurationElement.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class UserPasswordConfigurationElement : PasswordConfigurationElement, IUserPasswordConfiguration - { - } -} diff --git a/src/Umbraco.Configuration/UmbracoSettings/WebRoutingElement.cs b/src/Umbraco.Configuration/UmbracoSettings/WebRoutingElement.cs deleted file mode 100644 index 206fc213d2..0000000000 --- a/src/Umbraco.Configuration/UmbracoSettings/WebRoutingElement.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class WebRoutingElement : ConfigurationElement, IWebRoutingSettings - { - [ConfigurationProperty("trySkipIisCustomErrors", DefaultValue = "false")] - public bool TrySkipIisCustomErrors => (bool) base["trySkipIisCustomErrors"]; - - [ConfigurationProperty("internalRedirectPreservesTemplate", DefaultValue = "false")] - public bool InternalRedirectPreservesTemplate => (bool) base["internalRedirectPreservesTemplate"]; - - [ConfigurationProperty("disableAlternativeTemplates", DefaultValue = "false")] - public bool DisableAlternativeTemplates => (bool) base["disableAlternativeTemplates"]; - - [ConfigurationProperty("validateAlternativeTemplates", DefaultValue = "false")] - public bool ValidateAlternativeTemplates => (bool) base["validateAlternativeTemplates"]; - - [ConfigurationProperty("disableFindContentByIdPath", DefaultValue = "false")] - public bool DisableFindContentByIdPath => (bool) base["disableFindContentByIdPath"]; - - [ConfigurationProperty("disableRedirectUrlTracking", DefaultValue = "false")] - public bool DisableRedirectUrlTracking => (bool) base["disableRedirectUrlTracking"]; - - [ConfigurationProperty("urlProviderMode", DefaultValue = "Auto")] - public string UrlProviderMode => (string) base["urlProviderMode"]; - - [ConfigurationProperty("umbracoApplicationUrl", DefaultValue = null)] - public string UmbracoApplicationUrl => (string)base["umbracoApplicationUrl"]; - } -} diff --git a/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs b/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs index 8df253b296..bd04b44b18 100644 --- a/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs @@ -5,6 +5,7 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Identity; using Umbraco.Core.Models.Membership; @@ -39,7 +40,7 @@ namespace Umbraco.Core.BackOffice /// This is allowed to be null (but would need to be filled in if trying to persist this instance) /// /// - public static BackOfficeIdentityUser CreateNew(IGlobalSettings globalSettings, string username, string email, string culture) + public static BackOfficeIdentityUser CreateNew(GlobalSettings globalSettings, string username, string email, string culture) { if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username)); if (string.IsNullOrWhiteSpace(culture)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(culture)); @@ -57,7 +58,7 @@ namespace Umbraco.Core.BackOffice return user; } - private BackOfficeIdentityUser(IGlobalSettings globalSettings, IReadOnlyUserGroup[] groups) + private BackOfficeIdentityUser(GlobalSettings globalSettings, IReadOnlyUserGroup[] groups) { _startMediaIds = Array.Empty(); _startContentIds = Array.Empty(); @@ -78,7 +79,7 @@ namespace Umbraco.Core.BackOffice /// /// /// - public BackOfficeIdentityUser(IGlobalSettings globalSettings, int userId, IEnumerable groups) + public BackOfficeIdentityUser(GlobalSettings globalSettings, int userId, IEnumerable groups) : this(globalSettings, groups.ToArray()) { // use the property setters - they do more than just setting a field diff --git a/src/Umbraco.Core/BackOffice/IdentityMapDefinition.cs b/src/Umbraco.Core/BackOffice/IdentityMapDefinition.cs index e8d16a7903..61fdf82d19 100644 --- a/src/Umbraco.Core/BackOffice/IdentityMapDefinition.cs +++ b/src/Umbraco.Core/BackOffice/IdentityMapDefinition.cs @@ -1,5 +1,7 @@ using System; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; @@ -11,13 +13,13 @@ namespace Umbraco.Core.BackOffice { private readonly ILocalizedTextService _textService; private readonly IEntityService _entityService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public IdentityMapDefinition(ILocalizedTextService textService, IEntityService entityService, IGlobalSettings globalSettings) + public IdentityMapDefinition(ILocalizedTextService textService, IEntityService entityService, IOptions globalSettings) { _textService = textService; _entityService = entityService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public void DefineMaps(UmbracoMapper mapper) diff --git a/src/Umbraco.Core/Composing/Composition.cs b/src/Umbraco.Core/Composing/Composition.cs index f6e8655575..998f42a2dc 100644 --- a/src/Umbraco.Core/Composing/Composition.cs +++ b/src/Umbraco.Core/Composing/Composition.cs @@ -21,7 +21,6 @@ namespace Umbraco.Core.Composing private readonly Dictionary> _uniques = new Dictionary>(); private readonly IRegister _register; - /// /// Initializes a new instance of the class. /// @@ -32,13 +31,12 @@ namespace Umbraco.Core.Composing /// Optional configs. /// An IOHelper /// - public Composition(IRegister register, TypeLoader typeLoader, IProfilingLogger logger, IRuntimeState runtimeState, Configs configs, IIOHelper ioHelper, AppCaches appCaches) + public Composition(IRegister register, TypeLoader typeLoader, IProfilingLogger logger, IRuntimeState runtimeState, IIOHelper ioHelper, AppCaches appCaches) { _register = register ?? throw new ArgumentNullException(nameof(register)); TypeLoader = typeLoader ?? throw new ArgumentNullException(nameof(typeLoader)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); RuntimeState = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState)); - Configs = configs ?? throw new ArgumentNullException(nameof(configs)); IOHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); AppCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches)); } @@ -63,11 +61,6 @@ namespace Umbraco.Core.Composing /// public IRuntimeState RuntimeState { get; } - /// - /// Gets the configurations. - /// - public Configs Configs { get; } - #endregion #region IRegister @@ -136,8 +129,6 @@ namespace Umbraco.Core.Composing IFactory factory = null; - Configs.RegisterWith(_register); - // ReSharper disable once AccessToModifiedClosure -- on purpose _register.Register(_ => factory, Lifetime.Singleton); factory = _register.CreateFactory(); diff --git a/src/Umbraco.Core/Composing/Current.cs b/src/Umbraco.Core/Composing/Current.cs index fb2c82030a..84a9b1ecc0 100644 --- a/src/Umbraco.Core/Composing/Current.cs +++ b/src/Umbraco.Core/Composing/Current.cs @@ -1,8 +1,10 @@ using System; using System.Runtime.CompilerServices; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -15,18 +17,20 @@ namespace Umbraco.Composing { private static Microsoft.Extensions.Logging.ILogger _logger = new NullLogger(); private static ILoggerFactory _loggerFactory; - private static Configs _configs; private static IIOHelper _ioHelper; private static IHostingEnvironment _hostingEnvironment; private static IBackOfficeInfo _backOfficeInfo; private static IProfiler _profiler; + private static SecuritySettings _securitySettings; + private static GlobalSettings _globalSettings; public static Microsoft.Extensions.Logging.ILogger Logger => EnsureInitialized(_logger); - public static Configs Configs => EnsureInitialized(_configs); public static IIOHelper IOHelper => EnsureInitialized(_ioHelper); public static IHostingEnvironment HostingEnvironment => EnsureInitialized(_hostingEnvironment); public static IBackOfficeInfo BackOfficeInfo => EnsureInitialized(_backOfficeInfo); public static IProfiler Profiler => EnsureInitialized(_profiler); + public static SecuritySettings SecuritySettings => EnsureInitialized(_securitySettings); + public static GlobalSettings GlobalSettings => EnsureInitialized(_globalSettings); public static ILoggerFactory LoggerFactory => EnsureInitialized(_loggerFactory); public static bool IsInitialized { get; internal set; } @@ -42,7 +46,8 @@ namespace Umbraco.Composing public static void Initialize( Microsoft.Extensions.Logging.ILogger logger, - Configs configs, + SecuritySettings securitySettings, + GlobalSettings globalSettings, IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo, @@ -54,13 +59,15 @@ namespace Umbraco.Composing } _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _configs = configs ?? throw new ArgumentNullException(nameof(configs)); _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); _backOfficeInfo = backOfficeInfo ?? throw new ArgumentNullException(nameof(backOfficeInfo)); _profiler = profiler ?? throw new ArgumentNullException(nameof(profiler)); + _securitySettings = securitySettings ?? throw new ArgumentNullException(nameof(securitySettings)); + _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); IsInitialized = true; } + } } diff --git a/src/Umbraco.Core/Composing/TypeFinderConfig.cs b/src/Umbraco.Core/Composing/TypeFinderConfig.cs index 9a3cd7072c..302d45b4e8 100644 --- a/src/Umbraco.Core/Composing/TypeFinderConfig.cs +++ b/src/Umbraco.Core/Composing/TypeFinderConfig.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; namespace Umbraco.Core.Composing @@ -11,12 +12,12 @@ namespace Umbraco.Core.Composing /// public class TypeFinderConfig : ITypeFinderConfig { - private readonly ITypeFinderSettings _settings; + private readonly TypeFinderSettings _settings; private IEnumerable _assembliesAcceptingLoadExceptions; - public TypeFinderConfig(ITypeFinderSettings settings) + public TypeFinderConfig(IOptionsMonitor settings) { - _settings = settings; + _settings = settings.CurrentValue; } public IEnumerable AssembliesAcceptingLoadExceptions diff --git a/src/Umbraco.Core/ConfigConnectionStringExtensions.cs b/src/Umbraco.Core/ConfigConnectionStringExtensions.cs index 693b8a433e..8047af88c5 100644 --- a/src/Umbraco.Core/ConfigConnectionStringExtensions.cs +++ b/src/Umbraco.Core/ConfigConnectionStringExtensions.cs @@ -5,7 +5,6 @@ using Umbraco.Core.Configuration; namespace Umbraco.Core { - public static class ConfigConnectionStringExtensions { public static bool IsConnectionStringConfigured(this ConfigConnectionString databaseSettings) diff --git a/src/Umbraco.Core/Configuration/ConfigConnectionString.cs b/src/Umbraco.Core/Configuration/ConfigConnectionString.cs index e9ac944b85..3a540aa3e2 100644 --- a/src/Umbraco.Core/Configuration/ConfigConnectionString.cs +++ b/src/Umbraco.Core/Configuration/ConfigConnectionString.cs @@ -1,16 +1,61 @@ +using System; +using System.Data.Common; + namespace Umbraco.Core.Configuration { public class ConfigConnectionString { - public ConfigConnectionString(string connectionString, string providerName, string name) + public ConfigConnectionString(string name, string connectionString, string providerName = null) { + Name = name ?? throw new ArgumentNullException(nameof(name)); ConnectionString = connectionString; - ProviderName = providerName; - Name = name; + + ProviderName = string.IsNullOrEmpty(providerName) ? ParseProvider(connectionString) : providerName; } public string ConnectionString { get; } public string ProviderName { get; } public string Name { get; } + + private string ParseProvider(string connectionString) + { + if (string.IsNullOrEmpty(connectionString)) + { + return null; + } + + var builder = new DbConnectionStringBuilder + { + ConnectionString = connectionString + }; + + if (builder.TryGetValue("Data Source", out var ds) && ds is string dataSource) + { + if (dataSource.EndsWith(".sdf")) + { + return Constants.DbProviderNames.SqlCe; + } + } + + if (builder.TryGetValue("Server", out var s) && s is string server && !string.IsNullOrEmpty(server)) + { + if (builder.TryGetValue("Database", out var db) && db is string database && !string.IsNullOrEmpty(database)) + { + return Constants.DbProviderNames.SqlServer; + } + + if (builder.TryGetValue("AttachDbFileName", out var a) && a is string attachDbFileName && !string.IsNullOrEmpty(attachDbFileName)) + { + return Constants.DbProviderNames.SqlServer; + } + + if (builder.TryGetValue("Initial Catalog", out var i) && i is string initialCatalog && !string.IsNullOrEmpty(initialCatalog)) + { + return Constants.DbProviderNames.SqlServer; + } + } + + throw new ArgumentException("Cannot determine provider name from connection string", nameof(connectionString)); + } } } diff --git a/src/Umbraco.Core/Configuration/Configs.cs b/src/Umbraco.Core/Configuration/Configs.cs deleted file mode 100644 index 821ee308f0..0000000000 --- a/src/Umbraco.Core/Configuration/Configs.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using Umbraco.Core.Composing; - -namespace Umbraco.Core.Configuration -{ - /// - /// Represents Umbraco configurations. - /// - /// - /// During composition, use composition.Configs. When running, either inject the required configuration, - /// or use Current.Configs. - /// - public class Configs - { - private readonly Dictionary> _configs = new Dictionary>(); - private Dictionary> _registerings = new Dictionary>(); - - /// - /// Gets a configuration. - /// - public TConfig GetConfig() - where TConfig : class - { - if (!_configs.TryGetValue(typeof(TConfig), out var configFactory)) - throw new InvalidOperationException($"No configuration of type {typeof(TConfig)} has been added."); - - return (TConfig) configFactory.Value; - } - - /// - /// Adds a configuration, provided by a factory. - /// - public void Add(Func configFactory) - where TConfig : class - { - // make sure it is not too late - if (_registerings == null) - throw new InvalidOperationException("Configurations have already been registered."); - - var typeOfConfig = typeof(TConfig); - - var lazyConfigFactory = _configs[typeOfConfig] = new Lazy(configFactory); - _registerings[typeOfConfig] = register => register.Register(_ => (TConfig) lazyConfigFactory.Value, Lifetime.Singleton); - } - - /// - /// Registers configurations in a register. - /// - public void RegisterWith(IRegister register) - { - // do it only once - if (_registerings == null) - throw new InvalidOperationException("Configurations have already been registered."); - - register.Register(this); - - foreach (var registering in _registerings.Values) - registering(register); - - // no need to keep them around - _registerings = null; - } - } -} diff --git a/src/Umbraco.Core/Configuration/ConfigsExtensions.cs b/src/Umbraco.Core/Configuration/ConfigsExtensions.cs deleted file mode 100644 index a4bdb5c55f..0000000000 --- a/src/Umbraco.Core/Configuration/ConfigsExtensions.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Grid; -using Umbraco.Core.Configuration.HealthChecks; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Core -{ - /// - /// Provides extension methods for the class. - /// - public static class ConfigsExtensions - { - - public static IImagingSettings Imaging(this Configs configs) - => configs.GetConfig(); - public static IGlobalSettings Global(this Configs configs) - => configs.GetConfig(); - - public static IHostingSettings Hosting(this Configs configs) - => configs.GetConfig(); - - public static IConnectionStrings ConnectionStrings(this Configs configs) - => configs.GetConfig(); - - public static IContentSettings Content(this Configs configs) - => configs.GetConfig(); - - public static ISecuritySettings Security(this Configs configs) - => configs.GetConfig(); - - public static ITypeFinderSettings TypeFinder(this Configs configs) - => configs.GetConfig(); - - - public static IUserPasswordConfiguration UserPasswordConfiguration(this Configs configs) - => configs.GetConfig(); - public static IMemberPasswordConfiguration MemberPasswordConfiguration(this Configs configs) - => configs.GetConfig(); - - public static IRequestHandlerSettings RequestHandler(this Configs configs) - => configs.GetConfig(); - - public static IWebRoutingSettings WebRouting(this Configs configs) - => configs.GetConfig(); - - public static IHealthChecksSettings HealthChecks(this Configs configs) - => configs.GetConfig(); - public static ICoreDebugSettings CoreDebug(this Configs configs) - => configs.GetConfig(); - - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs b/src/Umbraco.Core/Configuration/ContentSettingsExtensions.cs similarity index 74% rename from src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs rename to src/Umbraco.Core/Configuration/ContentSettingsExtensions.cs index d100eb0a74..21ebe55f2f 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs +++ b/src/Umbraco.Core/Configuration/ContentSettingsExtensions.cs @@ -1,9 +1,11 @@ using System; using System.Linq; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Configuration.UmbracoSettings; -namespace Umbraco.Core.Configuration.UmbracoSettings +namespace Umbraco.Core.Configuration { - public static class ContentSectionExtensions + public static class ContentSettingsExtensions { /// /// Gets a value indicating whether the file extension corresponds to an image. @@ -11,12 +13,12 @@ namespace Umbraco.Core.Configuration.UmbracoSettings /// The file extension. /// /// A value indicating whether the file extension corresponds to an image. - public static bool IsImageFile(this IContentSettings contentConfig, string extension) + public static bool IsImageFile(this ContentSettings contentConfig, string extension) { if (contentConfig == null) throw new ArgumentNullException(nameof(contentConfig)); if (extension == null) return false; extension = extension.TrimStart('.'); - return contentConfig.ImageFileTypes.InvariantContains(extension); + return contentConfig.Imaging.ImageFileTypes.InvariantContains(extension); } /// @@ -24,7 +26,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings /// held in settings. /// Allow upload if extension is whitelisted OR if there is no whitelist and extension is NOT blacklisted. /// - public static bool IsFileAllowedForUpload(this IContentSettings contentSettings, string extension) + public static bool IsFileAllowedForUpload(this ContentSettings contentSettings, string extension) { return contentSettings.AllowedUploadFiles.Any(x => x.InvariantEquals(extension)) || (contentSettings.AllowedUploadFiles.Any() == false && @@ -37,9 +39,9 @@ namespace Umbraco.Core.Configuration.UmbracoSettings /// /// The property type alias. /// The auto-fill configuration for the specified property alias, or null. - public static IImagingAutoFillUploadField GetConfig(this IContentSettings contentSettings, string propertyTypeAlias) + public static IImagingAutoFillUploadField GetConfig(this ContentSettings contentSettings, string propertyTypeAlias) { - var autoFillConfigs = contentSettings.ImageAutoFillProperties; + var autoFillConfigs = contentSettings.Imaging.AutoFillImageProperties; return autoFillConfigs?.FirstOrDefault(x => x.Alias == propertyTypeAlias); } } diff --git a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs index a9a7f578d0..f9b2362e14 100644 --- a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs +++ b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs @@ -1,4 +1,5 @@ using System; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; namespace Umbraco.Core.Configuration @@ -14,7 +15,7 @@ namespace Umbraco.Core.Configuration /// /// /// - public static string GetBackOfficePath(this IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static string GetBackOfficePath(this GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { if (_backOfficePath != null) return _backOfficePath; _backOfficePath = hostingEnvironment.ToAbsolute(globalSettings.UmbracoPath); @@ -32,7 +33,7 @@ namespace Umbraco.Core.Configuration /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". /// - public static string GetUmbracoMvcArea(this IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static string GetUmbracoMvcArea(this GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { if (_mvcArea != null) return _mvcArea; @@ -41,7 +42,7 @@ namespace Umbraco.Core.Configuration return _mvcArea; } - internal static string GetUmbracoMvcAreaNoCache(this IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + internal static string GetUmbracoMvcAreaNoCache(this GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var path = string.IsNullOrEmpty(globalSettings.UmbracoPath) ? string.Empty diff --git a/src/Umbraco.Core/Configuration/HealthChecks/DisabledHealthCheck.cs b/src/Umbraco.Core/Configuration/HealthChecks/DisabledHealthCheck.cs new file mode 100644 index 0000000000..c962014bd5 --- /dev/null +++ b/src/Umbraco.Core/Configuration/HealthChecks/DisabledHealthCheck.cs @@ -0,0 +1,11 @@ +using System; + +namespace Umbraco.Core.Configuration.HealthChecks +{ + public class DisabledHealthCheck + { + public Guid Id { get; set; } + public DateTime DisabledOn { get; set; } + public int DisabledBy { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/HealthChecks/IDisabledHealthCheck.cs b/src/Umbraco.Core/Configuration/HealthChecks/IDisabledHealthCheck.cs deleted file mode 100644 index 4ea63048f8..0000000000 --- a/src/Umbraco.Core/Configuration/HealthChecks/IDisabledHealthCheck.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public interface IDisabledHealthCheck - { - Guid Id { get; } - DateTime DisabledOn { get; } - int DisabledBy { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/HealthChecks/IHealthCheckNotificationSettings.cs b/src/Umbraco.Core/Configuration/HealthChecks/IHealthCheckNotificationSettings.cs deleted file mode 100644 index 4564e87ed6..0000000000 --- a/src/Umbraco.Core/Configuration/HealthChecks/IHealthCheckNotificationSettings.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public interface IHealthCheckNotificationSettings - { - bool Enabled { get; } - string FirstRunTime { get; } - int PeriodInHours { get; } - IReadOnlyDictionary NotificationMethods { get; } - IEnumerable DisabledChecks { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/HealthChecks/IHealthChecksSettings.cs b/src/Umbraco.Core/Configuration/HealthChecks/IHealthChecksSettings.cs deleted file mode 100644 index 785e8d5651..0000000000 --- a/src/Umbraco.Core/Configuration/HealthChecks/IHealthChecksSettings.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.HealthChecks -{ - public interface IHealthChecksSettings - { - IEnumerable DisabledChecks { get; } - IHealthCheckNotificationSettings NotificationSettings { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs b/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs deleted file mode 100644 index e6b9202c06..0000000000 --- a/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IActiveDirectorySettings - { - string ActiveDirectoryDomain { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IConfigsFactory.cs b/src/Umbraco.Core/Configuration/IConfigsFactory.cs deleted file mode 100644 index dd2459b88c..0000000000 --- a/src/Umbraco.Core/Configuration/IConfigsFactory.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Umbraco.Core.IO; -using Umbraco.Core.Logging; - -namespace Umbraco.Core.Configuration -{ - public interface IConfigsFactory - { - Configs Create(); - } -} diff --git a/src/Umbraco.Core/Configuration/IConnectionStrings.cs b/src/Umbraco.Core/Configuration/IConnectionStrings.cs deleted file mode 100644 index 0d33378669..0000000000 --- a/src/Umbraco.Core/Configuration/IConnectionStrings.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IConnectionStrings - { - ConfigConnectionString this[string key] - { - get; - } - } -} diff --git a/src/Umbraco.Core/Configuration/ICoreDebugSettings.cs b/src/Umbraco.Core/Configuration/ICoreDebugSettings.cs deleted file mode 100644 index 586e4bc3e4..0000000000 --- a/src/Umbraco.Core/Configuration/ICoreDebugSettings.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface ICoreDebugSettings - { - /// - /// When set to true, Scope logs the stack trace for any scope that gets disposed without being completed. - /// this helps troubleshooting rogue scopes that we forget to complete - /// - bool LogUncompletedScopes { get; } - - /// - /// When set to true, the Logger creates a mini dump of w3wp in ~/App_Data/MiniDump whenever it logs - /// an error due to a ThreadAbortException that is due to a timeout. - /// - bool DumpOnTimeoutThreadAbort { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs b/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs deleted file mode 100644 index 169c04da5f..0000000000 --- a/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IExceptionFilterSettings - { - bool Disabled { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IGlobalSettings.cs b/src/Umbraco.Core/Configuration/IGlobalSettings.cs deleted file mode 100644 index 26d833613f..0000000000 --- a/src/Umbraco.Core/Configuration/IGlobalSettings.cs +++ /dev/null @@ -1,108 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - /// - /// Contains general settings information for the entire Umbraco instance based on information from web.config appsettings - /// - public interface IGlobalSettings - { - // fixme: Review this class, it is now just a dumping ground for config options (based basically on whatever might be in appSettings), - // our config classes should be named according to what they are configuring. - - /// - /// Gets the reserved urls from web.config. - /// - /// The reserved urls. - string ReservedUrls { get; } - - /// - /// Gets the reserved paths from web.config - /// - /// The reserved paths. - string ReservedPaths { get; } - - /// - /// Gets the path to umbraco's icons directory (/umbraco/assets/icons by default). - /// - string IconsPath { get; } - - /// - /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. - /// - string ConfigurationStatus { get; set; } - - /// - /// Gets the time out in minutes. - /// - int TimeOutInMinutes { get; } - - /// - /// Gets the default UI language. - /// - /// The default UI language. - // ReSharper disable once InconsistentNaming - string DefaultUILanguage { get; } - - /// - /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. - /// - /// - /// true if umbraco hides top level nodes from urls; otherwise, false. - /// - bool HideTopLevelNodeFromPath { get; } - - /// - /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. - /// - bool UseHttps { get; } - - /// - /// Returns a string value to determine if umbraco should skip version-checking. - /// - /// The version check period in days (0 = never). - int VersionCheckPeriod { get; } - - /// - /// Gets the path to umbraco's root directory. - /// - string UmbracoPath { get; } - string UmbracoCssPath { get; } - string UmbracoScriptsPath { get; } - string UmbracoMediaPath { get; } - - bool IsSmtpServerConfigured { get; } - ISmtpSettings SmtpSettings { get; } - - /// - /// Gets a value indicating whether the runtime should enter Install level when the database is missing. - /// - /// - /// By default, when a database connection string is configured but it is not possible to - /// connect to the database, the runtime enters the BootFailed level. If this options is set to true, - /// it enters the Install level instead. - /// It is then up to the implementor, that is setting this value, to take over the installation - /// sequence. - /// - bool InstallMissingDatabase { get; } - - /// - /// Gets a value indicating whether the runtime should enter Install level when the database is empty. - /// - /// - /// By default, when a database connection string is configured and it is possible to connect to - /// the database, but the database is empty, the runtime enters the BootFailed level. If this options - /// is set to true, it enters the Install level instead. - /// It is then up to the implementor, that is setting this value, to take over the installation - /// sequence. - /// - bool InstallEmptyDatabase { get; } - bool DisableElectionForSingleServer { get; } - string RegisterType { get; } - string DatabaseFactoryServerVersion { get; } - string MainDomLock { get; } - - /// - /// Gets the path to the razor file used when no published content is available. - /// - string NoNodesViewPath { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IHostingSettings.cs b/src/Umbraco.Core/Configuration/IHostingSettings.cs deleted file mode 100644 index 48ff4f216e..0000000000 --- a/src/Umbraco.Core/Configuration/IHostingSettings.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Umbraco.Core.Hosting; - -namespace Umbraco.Core.Configuration -{ - public interface IHostingSettings - { - bool DebugMode { get; } - - /// - /// Gets the configuration for the location of temporary files. - /// - LocalTempStorage LocalTempStorageLocation { get; } - - /// - /// Optional property to explicitly configure the application's virtual path - /// - /// - /// By default this is null which will mean that the is automatically configured, - /// otherwise this explicitly sets it. - /// If set, this value must begin with a "/" and cannot end with "/". - /// - string ApplicationVirtualPath { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IImagingSettings.cs b/src/Umbraco.Core/Configuration/IImagingSettings.cs deleted file mode 100644 index 13e1b30389..0000000000 --- a/src/Umbraco.Core/Configuration/IImagingSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IImagingSettings - { - int MaxBrowserCacheDays { get;} - int MaxCacheDays { get; } - uint CachedNameLength { get; } - int MaxResizeWidth { get; } - int MaxResizeHeight { get; } - string CacheFolder { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs b/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs deleted file mode 100644 index b3e2854a0d..0000000000 --- a/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IIndexCreatorSettings - { - string LuceneDirectoryFactory { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs b/src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs deleted file mode 100644 index 990bde9843..0000000000 --- a/src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IModelsBuilderConfig - { - bool Enable { get; } - bool AcceptUnsafeModelsDirectory { get; } - int DebugLevel { get; } - bool EnableFactory { get; } - bool FlagOutOfDateModels { get; } - string ModelsDirectory { get; } - ModelsMode ModelsMode { get; } - string ModelsNamespace { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/INuCacheSettings.cs b/src/Umbraco.Core/Configuration/INuCacheSettings.cs deleted file mode 100644 index c6524297a6..0000000000 --- a/src/Umbraco.Core/Configuration/INuCacheSettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface INuCacheSettings - { - string BTreeBlockSize { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/IRuntimeSettings.cs b/src/Umbraco.Core/Configuration/IRuntimeSettings.cs deleted file mode 100644 index 915e774186..0000000000 --- a/src/Umbraco.Core/Configuration/IRuntimeSettings.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Umbraco.Core.Configuration -{ - public interface IRuntimeSettings - { - int? MaxQueryStringLength { get; } - int? MaxRequestLength { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/ISmtpSettings.cs b/src/Umbraco.Core/Configuration/ISmtpSettings.cs deleted file mode 100644 index ea42ae5567..0000000000 --- a/src/Umbraco.Core/Configuration/ISmtpSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Net.Mail; - -namespace Umbraco.Core.Configuration -{ - public interface ISmtpSettings - { - string From { get; } - string Host { get; } - int Port{ get; } - string PickupDirectoryLocation { get; } - SmtpDeliveryMethod DeliveryMethod { get; } - string Username { get; } - string Password { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/Models/ActiveDirectorySettings.cs b/src/Umbraco.Core/Configuration/Models/ActiveDirectorySettings.cs new file mode 100644 index 0000000000..0fe541416a --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ActiveDirectorySettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class ActiveDirectorySettings + { + public string Domain { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs b/src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs new file mode 100644 index 0000000000..d21cba4486 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ConnectionStrings.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; + +namespace Umbraco.Core.Configuration.Models +{ + public class ConnectionStrings + { + // Backing field for UmbracoConnectionString to load from configuration value with key umbracoDbDSN. + // Attributes cannot be applied to map from keys that don't match, and have chosen to retain the key name + // used in configuration for older Umbraco versions. + // See: https://stackoverflow.com/a/54607296/489433 + private string umbracoDbDSN + { + get => UmbracoConnectionString?.ConnectionString; + set => UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, value); + } + + public ConfigConnectionString UmbracoConnectionString { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ContentErrorPage.cs b/src/Umbraco.Core/Configuration/Models/ContentErrorPage.cs new file mode 100644 index 0000000000..8971dda5cc --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ContentErrorPage.cs @@ -0,0 +1,15 @@ +using System; + +namespace Umbraco.Core.Configuration.Models +{ + public class ContentErrorPage + { + //TODO introduce validation, to check only one of key/id/xPath is used. + public int ContentId { get; } + public Guid ContentKey { get; } + public string ContentXPath { get; } + public bool HasContentId { get; } + public bool HasContentKey { get; } + public string Culture { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ContentImagingSettings.cs b/src/Umbraco.Core/Configuration/Models/ContentImagingSettings.cs new file mode 100644 index 0000000000..018936896c --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ContentImagingSettings.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using Umbraco.Core.Configuration.UmbracoSettings; + +namespace Umbraco.Core.Configuration.Models +{ + public class ContentImagingSettings + { + private static readonly ImagingAutoFillUploadField[] DefaultImagingAutoFillUploadField = +{ + new ImagingAutoFillUploadField + { + Alias = Constants.Conventions.Media.File, + WidthFieldAlias = Constants.Conventions.Media.Width, + HeightFieldAlias = Constants.Conventions.Media.Height, + ExtensionFieldAlias = Constants.Conventions.Media.Extension, + LengthFieldAlias = Constants.Conventions.Media.Bytes, + } + }; + + public IEnumerable ImageFileTypes { get; set; } = new[] { "jpeg", "jpg", "gif", "bmp", "png", "tiff", "tif" }; + + public IEnumerable AutoFillImageProperties { get; set; } = DefaultImagingAutoFillUploadField; + + private class ImagingAutoFillUploadField : IImagingAutoFillUploadField + { + public string Alias { get; set; } + public string WidthFieldAlias { get; set; } + public string HeightFieldAlias { get; set; } + public string LengthFieldAlias { get; set; } + public string ExtensionFieldAlias { get; set; } + } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ContentNotificationSettings.cs b/src/Umbraco.Core/Configuration/Models/ContentNotificationSettings.cs new file mode 100644 index 0000000000..ab1c10ff77 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ContentNotificationSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class ContentNotificationSettings + { + public string Email { get; set; } + + public bool DisableHtmlEmail { get; set; } = false; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ContentSettings.cs b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs new file mode 100644 index 0000000000..5158a5c746 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ContentSettings.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Macros; + +namespace Umbraco.Core.Configuration.Models +{ + public class ContentSettings + { + private const string DefaultPreviewBadge = + @"
Preview modeClick to end
"; + + public ContentNotificationSettings Notifications { get; set; } = new ContentNotificationSettings(); + + public ContentImagingSettings Imaging { get; set; } = new ContentImagingSettings(); + + public bool ResolveUrlsFromTextString { get; set; } = false; + + public IEnumerable Error404Collection { get; set; } = Array.Empty(); + + public string PreviewBadge { get; set; } = DefaultPreviewBadge; + + public MacroErrorBehaviour MacroErrors { get; set; } = MacroErrorBehaviour.Inline; + + public IEnumerable DisallowedUploadFiles { get; set; } = new[] { "ashx", "aspx", "ascx", "config", "cshtml", "vbhtml", "asmx", "air", "axd" }; + + public IEnumerable AllowedUploadFiles { get; set; } = Array.Empty(); + + public bool ShowDeprecatedPropertyEditors { get; set; } = false; + + public string LoginBackgroundImage { get; set; } = "assets/img/login.jpg"; + + + } +} diff --git a/src/Umbraco.Core/Configuration/Models/CoreDebugSettings.cs b/src/Umbraco.Core/Configuration/Models/CoreDebugSettings.cs new file mode 100644 index 0000000000..2b13609509 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/CoreDebugSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class CoreDebugSettings + { + public bool LogUncompletedScopes { get; set; } = false; + + public bool DumpOnTimeoutThreadAbort { get; set; } = false; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ExceptionFilterSettings.cs b/src/Umbraco.Core/Configuration/Models/ExceptionFilterSettings.cs new file mode 100644 index 0000000000..6b8f74bef0 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ExceptionFilterSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class ExceptionFilterSettings + { + public bool Disabled { get; set; } = false; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs b/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs new file mode 100644 index 0000000000..84956c7636 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/GlobalSettings.cs @@ -0,0 +1,61 @@ +namespace Umbraco.Core.Configuration.Models +{ + /// + /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information + /// from web.config appsettings + /// + public class GlobalSettings + { + internal const string + StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,~/umbraco/,"; //must end with a comma! + + internal const string + StaticReservedUrls = "~/config/splashes/noNodes.aspx,~/.well-known,"; //must end with a comma! + + public string ReservedUrls { get; set; } = StaticReservedUrls; + + public string ReservedPaths { get; set; } = StaticReservedPaths; + + // TODO: https://github.com/umbraco/Umbraco-CMS/issues/4238 - stop having version in web.config appSettings + // TODO: previously this would throw on set, but presumably we can't do that if we do still want this in config. + public string ConfigurationStatus { get; set; } + + public int TimeOutInMinutes { get; set; } = 20; + + public string DefaultUILanguage { get; set; } = "en-US"; + + public bool HideTopLevelNodeFromPath { get; set; } = false; + + public bool UseHttps { get; set; } = false; + + public int VersionCheckPeriod { get; set; } = 7; + + public string UmbracoPath { get; set; } = "~/umbraco"; + + public string IconsPath { get; set; } = $"~/umbraco/assets/icons"; + + public string UmbracoCssPath { get; set; } = "~/css"; + + public string UmbracoScriptsPath { get; set; } = "~/scripts"; + + public string UmbracoMediaPath { get; set; } = "~/media"; + + public bool InstallMissingDatabase { get; set; } = false; + + public bool InstallEmptyDatabase { get; set; } = false; + + public bool DisableElectionForSingleServer { get; set; } = false; + + public string RegisterType { get; set; } = string.Empty; + + public string DatabaseFactoryServerVersion { get; set; } = string.Empty; + + public string MainDomLock { get; set; } = string.Empty; + + public string NoNodesViewPath { get; set; } = "~/config/splashes/NoNodes.cshtml"; + + public bool IsSmtpServerConfigured => !string.IsNullOrWhiteSpace(Smtp?.Host); + + public SmtpSettings Smtp { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/HealthChecksSettings.cs b/src/Umbraco.Core/Configuration/Models/HealthChecksSettings.cs new file mode 100644 index 0000000000..0903a8f242 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/HealthChecksSettings.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Linq; +using Umbraco.Core.Configuration.HealthChecks; + +namespace Umbraco.Core.Configuration.Models +{ + public class HealthChecksSettings + { + public IEnumerable DisabledChecks { get; set; } = Enumerable.Empty(); + + public HealthCheckNotificationSettings NotificationSettings { get; set; } = new HealthCheckNotificationSettings(); + + public class HealthCheckNotificationSettings + { + public bool Enabled { get; set; } = false; + + public string FirstRunTime { get; set; } + + public int PeriodInHours { get; set; } = 24; + + public IReadOnlyDictionary NotificationMethods { get; set; } = new Dictionary(); + + public IEnumerable DisabledChecks { get; set; } = Enumerable.Empty(); + } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/HostingSettings.cs b/src/Umbraco.Core/Configuration/Models/HostingSettings.cs new file mode 100644 index 0000000000..0863181922 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/HostingSettings.cs @@ -0,0 +1,18 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class HostingSettings + { + public string ApplicationVirtualPath { get; set; } + + /// + /// Gets the configuration for the location of temporary files. + /// + public LocalTempStorage LocalTempStorageLocation { get; set; } = LocalTempStorage.Default; + + /// + /// Gets a value indicating whether umbraco is running in [debug mode]. + /// + /// true if [debug mode]; otherwise, false. + public bool Debug { get; set; } = false; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ImagingCacheSettings.cs b/src/Umbraco.Core/Configuration/Models/ImagingCacheSettings.cs new file mode 100644 index 0000000000..25467b5a46 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ImagingCacheSettings.cs @@ -0,0 +1,15 @@ +using System.IO; + +namespace Umbraco.Core.Configuration.Models +{ + public class ImagingCacheSettings + { + public int MaxBrowserCacheDays { get; set; } = 7; + + public int MaxCacheDays { get; set; } = 365; + + public uint CachedNameLength { get; set; } = 8; + + public string CacheFolder { get; set; } = Path.Combine("..", "Umbraco", "MediaCache"); + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ImagingResizeSettings.cs b/src/Umbraco.Core/Configuration/Models/ImagingResizeSettings.cs new file mode 100644 index 0000000000..f9db53d7dd --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ImagingResizeSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class ImagingResizeSettings + { + public int MaxWidth { get; set; } = 5000; + + public int MaxHeight { get; set; } = 5000; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/ImagingSettings.cs b/src/Umbraco.Core/Configuration/Models/ImagingSettings.cs new file mode 100644 index 0000000000..2f253b151b --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/ImagingSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class ImagingSettings + { + public ImagingCacheSettings Cache { get; set; } = new ImagingCacheSettings(); + + public ImagingResizeSettings Resize { get; set; } = new ImagingResizeSettings(); + } +} diff --git a/src/Umbraco.Core/Configuration/Models/IndexCreatorSettings.cs b/src/Umbraco.Core/Configuration/Models/IndexCreatorSettings.cs new file mode 100644 index 0000000000..fcc22de9a3 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/IndexCreatorSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class IndexCreatorSettings + { + public string LuceneDirectoryFactory { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/KeepAliveSettings.cs b/src/Umbraco.Core/Configuration/Models/KeepAliveSettings.cs new file mode 100644 index 0000000000..01d3b36a5d --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/KeepAliveSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class KeepAliveSettings + { + public bool DisableKeepAliveTask => false; + + public string KeepAlivePingUrl => "{umbracoApplicationUrl}/api/keepalive/ping"; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/LoggingSettings.cs b/src/Umbraco.Core/Configuration/Models/LoggingSettings.cs new file mode 100644 index 0000000000..414ff06b57 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/LoggingSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class LoggingSettings + { + public int MaxLogAge { get; set; } = -1; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/MemberPasswordConfigurationSettings.cs b/src/Umbraco.Core/Configuration/Models/MemberPasswordConfigurationSettings.cs new file mode 100644 index 0000000000..52bba6f4b8 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/MemberPasswordConfigurationSettings.cs @@ -0,0 +1,19 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class MemberPasswordConfigurationSettings : IPasswordConfiguration + { + public int RequiredLength { get; set; } = 10; + + public bool RequireNonLetterOrDigit { get; set; } = false; + + public bool RequireDigit { get; set; } = false; + + public bool RequireLowercase { get; set; } = false; + + public bool RequireUppercase { get; set; } = false; + + public string HashAlgorithmType { get; set; } = Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName; + + public int MaxFailedAccessAttemptsBeforeLockout { get; set; } = 5; + } +} diff --git a/src/Umbraco.Configuration/Models/ModelsBuilderConfig.cs b/src/Umbraco.Core/Configuration/Models/ModelsBuilderConfig.cs similarity index 59% rename from src/Umbraco.Configuration/Models/ModelsBuilderConfig.cs rename to src/Umbraco.Core/Configuration/Models/ModelsBuilderConfig.cs index 4d35e3fa95..e99557755c 100644 --- a/src/Umbraco.Configuration/Models/ModelsBuilderConfig.cs +++ b/src/Umbraco.Core/Configuration/Models/ModelsBuilderConfig.cs @@ -1,26 +1,13 @@ -using Microsoft.Extensions.Configuration; -using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Configuration; -namespace Umbraco.Configuration.Models +namespace Umbraco.Core.Configuration.Models { /// /// Represents the models builder configuration. /// - internal class ModelsBuilderConfig : IModelsBuilderConfig + public class ModelsBuilderConfig { - private const string Prefix = Constants.Configuration.ConfigModelsBuilderPrefix; - private readonly IConfiguration _configuration; - - /// - /// Initializes a new instance of the class. - /// - public ModelsBuilderConfig(IConfiguration configuration) - { - _configuration = configuration; - } - - public string DefaultModelsDirectory => "~/Umbraco/Models"; + public static string DefaultModelsDirectory => "~/App_Data/Models"; /// /// Gets a value indicating whether the whole models experience is enabled. @@ -29,25 +16,26 @@ namespace Umbraco.Configuration.Models /// If this is false then absolutely nothing happens. /// Default value is false which means that unless we have this setting, nothing happens. /// - public bool Enable => _configuration.GetValue(Prefix+"Enable", false); + public bool Enable { get; set; } = false; /// /// Gets the models mode. /// - public ModelsMode ModelsMode => - _configuration.GetValue(Prefix+"ModelsMode", ModelsMode.Nothing); + public ModelsMode ModelsMode { get; set; } = ModelsMode.Nothing; /// /// Gets the models namespace. /// /// That value could be overriden by other (attribute in user's code...). Return default if no value was supplied. - public string ModelsNamespace => _configuration.GetValue(Prefix+"ModelsNamespace"); + public string ModelsNamespace { get; set; } /// /// Gets a value indicating whether we should enable the models factory. /// /// Default value is true because no factory is enabled by default in Umbraco. - public bool EnableFactory => _configuration.GetValue(Prefix+"EnableFactory", true); + public bool EnableFactory { get; set; } = true; + + private bool _flagOutOfDateModels; /// /// Gets a value indicating whether we should flag out-of-date models. @@ -57,15 +45,26 @@ namespace Umbraco.Configuration.Models /// setting is activated the ~/App_Data/Models/ood.txt file is then created. When models are /// generated through the dashboard, the files is cleared. Default value is false. /// - public bool FlagOutOfDateModels => - _configuration.GetValue(Prefix+"FlagOutOfDateModels", false) && !ModelsMode.IsLive(); + public bool FlagOutOfDateModels + { + get => _flagOutOfDateModels; + + set + { + if (!ModelsMode.IsLive()) + { + _flagOutOfDateModels = false; + } + + _flagOutOfDateModels = value; + } + } /// /// Gets the models directory. /// /// Default is ~/App_Data/Models but that can be changed. - public string ModelsDirectory => - _configuration.GetValue(Prefix+"ModelsDirectory", "~/Umbraco/Models"); + public string ModelsDirectory { get; set; } = DefaultModelsDirectory; /// /// Gets a value indicating whether to accept an unsafe value for ModelsDirectory. @@ -74,13 +73,12 @@ namespace Umbraco.Configuration.Models /// An unsafe value is an absolute path, or a relative path pointing outside /// of the website root. /// - public bool AcceptUnsafeModelsDirectory => - _configuration.GetValue(Prefix+"AcceptUnsafeModelsDirectory", false); + public bool AcceptUnsafeModelsDirectory { get; set; } = false; /// /// Gets a value indicating the debug log level. /// /// 0 means minimal (safe on live site), anything else means more and more details (maybe not safe). - public int DebugLevel => _configuration.GetValue(Prefix+"DebugLevel", 0); + public int DebugLevel { get; set; } = 0; } } diff --git a/src/Umbraco.Core/Configuration/Models/NuCacheSettings.cs b/src/Umbraco.Core/Configuration/Models/NuCacheSettings.cs new file mode 100644 index 0000000000..a2bc7d3561 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/NuCacheSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class NuCacheSettings + { + public string BTreeBlockSize { get; set; } + } +} diff --git a/src/Umbraco.Configuration/Models/RequestHandlerSettings.cs b/src/Umbraco.Core/Configuration/Models/RequestHandlerSettings.cs similarity index 50% rename from src/Umbraco.Configuration/Models/RequestHandlerSettings.cs rename to src/Umbraco.Core/Configuration/Models/RequestHandlerSettings.cs index ce5cd65c20..d7203b4901 100644 --- a/src/Umbraco.Configuration/Models/RequestHandlerSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/RequestHandlerSettings.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.Extensions.Configuration; -using Umbraco.Core; +using System.Collections.Generic; using Umbraco.Core.Configuration.UmbracoSettings; -namespace Umbraco.Configuration.Models +namespace Umbraco.Core.Configuration.Models { - internal class RequestHandlerSettings : IRequestHandlerSettings + public class RequestHandlerSettings { - private const string Prefix = Constants.Configuration.ConfigPrefix + "RequestHandler:"; - private static readonly CharItem[] DefaultCharCollection = + internal static readonly CharItem[] DefaultCharCollection = { new CharItem { Char = " ", Replacement = "-" }, new CharItem { Char = "\"", Replacement = "" }, @@ -38,49 +33,38 @@ namespace Umbraco.Configuration.Models new CharItem { Char = ">", Replacement = "" } }; - private readonly IConfiguration _configuration; + public bool AddTrailingSlash { get; set; } = true; - public RequestHandlerSettings(IConfiguration configuration) - { - _configuration = configuration; - } + public string ConvertUrlsToAscii { get; set; } = "try"; - public bool AddTrailingSlash => - _configuration.GetValue(Prefix+"AddTrailingSlash", true); - - public bool ConvertUrlsToAscii => _configuration - .GetValue(Prefix+"ConvertUrlsToAscii").InvariantEquals("true"); - - public bool TryConvertUrlsToAscii => _configuration - .GetValue(Prefix+"ConvertUrlsToAscii").InvariantEquals("try"); + public bool ShouldConvertUrlsToAscii => ConvertUrlsToAscii.InvariantEquals("true"); + public bool ShouldTryConvertUrlsToAscii => ConvertUrlsToAscii.InvariantEquals("try"); //We need to special handle ":", as this character is special in keys - public IEnumerable CharCollection - { - get - { - var collection = _configuration.GetSection(Prefix + "CharCollection").GetChildren() - .Select(x => new CharItem() - { - Char = x.GetValue("Char"), - Replacement = x.GetValue("Replacement"), - }).ToArray(); - if (collection.Any() || _configuration.GetSection("Prefix").GetChildren().Any(x => - x.Key.Equals("CharCollection", StringComparison.OrdinalIgnoreCase))) - { - return collection; - } + // TODO: implement from configuration - return DefaultCharCollection; - } - } + //var collection = _configuration.GetSection(Prefix + "CharCollection").GetChildren() + // .Select(x => new CharItem() + // { + // Char = x.GetValue("Char"), + // Replacement = x.GetValue("Replacement"), + // }).ToArray(); + //if (collection.Any() || _configuration.GetSection("Prefix").GetChildren().Any(x => + // x.Key.Equals("CharCollection", StringComparison.OrdinalIgnoreCase))) + //{ + // return collection; + //} + + // return DefaultCharCollection; + public IEnumerable CharCollection { get; set; } = DefaultCharCollection; public class CharItem : IChar { public string Char { get; set; } + public string Replacement { get; set; } } } diff --git a/src/Umbraco.Core/Configuration/Models/RuntimeSettings.cs b/src/Umbraco.Core/Configuration/Models/RuntimeSettings.cs new file mode 100644 index 0000000000..f93530b490 --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/RuntimeSettings.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class RuntimeSettings + { + public int? MaxQueryStringLength { get; set; } + + public int? MaxRequestLength { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs b/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs new file mode 100644 index 0000000000..f40160d69b --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs @@ -0,0 +1,21 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class SecuritySettings + { + public bool KeepUserLoggedIn { get; set; } = false; + + public bool HideDisabledUsersInBackoffice { get; set; } = false; + + public bool AllowPasswordReset { get; set; } = true; + + public string AuthCookieName { get; set; } = "UMB_UCONTEXT"; + + public string AuthCookieDomain { get; set; } + + public bool UsernameIsEmail { get; set; } = true; + + public UserPasswordConfigurationSettings UserPassword { get; set; } + + public MemberPasswordConfigurationSettings MemberPassword { get; set; } + } +} diff --git a/src/Umbraco.Configuration/Legacy/SmtpSettings.cs b/src/Umbraco.Core/Configuration/Models/SmtpSettings.cs similarity index 72% rename from src/Umbraco.Configuration/Legacy/SmtpSettings.cs rename to src/Umbraco.Core/Configuration/Models/SmtpSettings.cs index dce3d85840..a507f8a62f 100644 --- a/src/Umbraco.Configuration/Legacy/SmtpSettings.cs +++ b/src/Umbraco.Core/Configuration/Models/SmtpSettings.cs @@ -1,14 +1,17 @@ -using System.Net.Mail; -using Umbraco.Core.Configuration; +using System.Net.Mail; -namespace Umbraco.Configuration +namespace Umbraco.Core.Configuration.Models { - public class SmtpSettings : ISmtpSettings + public class SmtpSettings { public string From { get; set; } + public string Host { get; set; } + public int Port { get; set; } + public string PickupDirectoryLocation { get; set; } + public SmtpDeliveryMethod DeliveryMethod { get; set; } public string Username { get; set; } diff --git a/src/Umbraco.Core/Configuration/Models/TourSettings.cs b/src/Umbraco.Core/Configuration/Models/TourSettings.cs new file mode 100644 index 0000000000..895eff6dee --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/TourSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class TourSettings + { + public bool EnableTours { get; set; } = true; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/TypeFinderSettings.cs b/src/Umbraco.Core/Configuration/Models/TypeFinderSettings.cs new file mode 100644 index 0000000000..c5210f6c8e --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/TypeFinderSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class TypeFinderSettings + { + public string AssembliesAcceptingLoadExceptions { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/Models/UserPasswordConfigurationSettings.cs b/src/Umbraco.Core/Configuration/Models/UserPasswordConfigurationSettings.cs new file mode 100644 index 0000000000..445a0f545c --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/UserPasswordConfigurationSettings.cs @@ -0,0 +1,19 @@ +namespace Umbraco.Core.Configuration.Models +{ + public class UserPasswordConfigurationSettings : IPasswordConfiguration + { + public int RequiredLength { get; set; } = 10; + + public bool RequireNonLetterOrDigit { get; set; } = false; + + public bool RequireDigit { get; set; } = false; + + public bool RequireLowercase { get; set; } = false; + + public bool RequireUppercase { get; set; } = false; + + public string HashAlgorithmType { get; set; } = Constants.Security.AspNetCoreV3PasswordHashAlgorithmName; + + public int MaxFailedAccessAttemptsBeforeLockout { get; set; } = 5; + } +} diff --git a/src/Umbraco.Core/Configuration/Models/WebRoutingSettings.cs b/src/Umbraco.Core/Configuration/Models/WebRoutingSettings.cs new file mode 100644 index 0000000000..7e0c4d5d8c --- /dev/null +++ b/src/Umbraco.Core/Configuration/Models/WebRoutingSettings.cs @@ -0,0 +1,23 @@ +using Umbraco.Core.Models.PublishedContent; + +namespace Umbraco.Core.Configuration.Models +{ + public class WebRoutingSettings + { + public bool TrySkipIisCustomErrors { get; set; } = false; + + public bool InternalRedirectPreservesTemplate { get; set; } = false; + + public bool DisableAlternativeTemplates { get; set; } = false; + + public bool ValidateAlternativeTemplates { get; set; } = false; + + public bool DisableFindContentByIdPath { get; set; } = false; + + public bool DisableRedirectUrlTracking { get; set; } = false; + + public string UrlProviderMode { get; set; } = UrlMode.Auto.ToString(); + + public string UmbracoApplicationUrl { get; set; } + } +} diff --git a/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs b/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs index 07b344cec3..edf068e16f 100644 --- a/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs +++ b/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs @@ -1,6 +1,7 @@ using System.Configuration; using System.IO; using Umbraco.Core.Hosting; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; namespace Umbraco.Core.Configuration @@ -9,9 +10,8 @@ namespace Umbraco.Core.Configuration { private static string _modelsDirectoryAbsolute = null; - public static string ModelsDirectoryAbsolute(this IModelsBuilderConfig modelsBuilderConfig, IHostingEnvironment hostingEnvironment) + public static string ModelsDirectoryAbsolute(this ModelsBuilderConfig modelsBuilderConfig, IHostingEnvironment hostingEnvironment) { - if (_modelsDirectoryAbsolute is null) { var modelsDirectory = modelsBuilderConfig.ModelsDirectory; diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IBackOfficeSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IBackOfficeSection.cs deleted file mode 100644 index 85df4540c0..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IBackOfficeSection.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IBackOfficeSection - { - ITourSettings Tours { get; } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IContentErrorPage.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IContentErrorPage.cs deleted file mode 100644 index 3ea00d7c74..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IContentErrorPage.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IContentErrorPage - { - int ContentId { get; } - Guid ContentKey { get; } - string ContentXPath { get; } - bool HasContentId { get; } - bool HasContentKey { get; } - string Culture { get; set; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IContentSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IContentSettings.cs deleted file mode 100644 index 08f6231309..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IContentSettings.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; -using Umbraco.Core.Macros; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IContentSettings : IUmbracoConfigurationSection - { - string NotificationEmailAddress { get; } - - bool DisableHtmlEmail { get; } - - IEnumerable ImageFileTypes { get; } - - IEnumerable ImageAutoFillProperties { get; } - - bool ResolveUrlsFromTextString { get; } - - IEnumerable Error404Collection { get; } - - string PreviewBadge { get; } - - MacroErrorBehaviour MacroErrorBehaviour { get; } - - IEnumerable DisallowedUploadFiles { get; } - - IEnumerable AllowedUploadFiles { get; } - - /// - /// Gets a value indicating whether to show deprecated property editors in - /// a datatype list of available editors. - /// - bool ShowDeprecatedPropertyEditors { get; } - - string LoginBackgroundImage { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IKeepAliveSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IKeepAliveSettings.cs deleted file mode 100644 index 58a8151474..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IKeepAliveSettings.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IKeepAliveSettings : IUmbracoConfigurationSection - { - bool DisableKeepAliveTask { get; } - string KeepAlivePingUrl { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ILoggingSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ILoggingSettings.cs deleted file mode 100644 index ee5647ee27..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ILoggingSettings.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface ILoggingSettings : IUmbracoConfigurationSection - { - int MaxLogAge { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IRequestHandlerSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IRequestHandlerSettings.cs deleted file mode 100644 index 11fdaa8310..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IRequestHandlerSettings.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IRequestHandlerSettings : IUmbracoConfigurationSection - { - bool AddTrailingSlash { get; } - - bool ConvertUrlsToAscii { get; } - - bool TryConvertUrlsToAscii { get; } - - IEnumerable CharCollection { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ISecuritySettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ISecuritySettings.cs deleted file mode 100644 index 6ab520fefd..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ISecuritySettings.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface ISecuritySettings : IUmbracoConfigurationSection - { - bool KeepUserLoggedIn { get; } - - bool HideDisabledUsersInBackoffice { get; } - - /// - /// Used to enable/disable the forgot password functionality on the back office login screen - /// - bool AllowPasswordReset { get; } - - string AuthCookieName { get; } - - string AuthCookieDomain { get; } - - /// - /// A boolean indicating that by default the email address will be the username - /// - /// - /// Even if this is true and the username is different from the email in the database, the username field will still be shown. - /// When this is false, the username and email fields will be shown in the user section. - /// - bool UsernameIsEmail { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ITourSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ITourSettings.cs deleted file mode 100644 index d3d8293140..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ITourSettings.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface ITourSettings - { - bool EnableTours { get; } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IWebRoutingSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IWebRoutingSettings.cs deleted file mode 100644 index f7f6a94d30..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IWebRoutingSettings.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IWebRoutingSettings : IUmbracoConfigurationSection - { - bool TrySkipIisCustomErrors { get; } - - bool InternalRedirectPreservesTemplate { get; } - - bool DisableAlternativeTemplates { get; } - - bool ValidateAlternativeTemplates { get; } - - bool DisableFindContentByIdPath { get; } - - bool DisableRedirectUrlTracking { get; } - - string UrlProviderMode { get; } - - string UmbracoApplicationUrl { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoVersion.cs b/src/Umbraco.Core/Configuration/UmbracoVersion.cs index 0ddac4a8bd..2e45be6cc6 100644 --- a/src/Umbraco.Core/Configuration/UmbracoVersion.cs +++ b/src/Umbraco.Core/Configuration/UmbracoVersion.cs @@ -1,5 +1,4 @@ using System; -using System.Configuration; using System.Reflection; using Semver; @@ -10,14 +9,6 @@ namespace Umbraco.Core.Configuration /// public class UmbracoVersion : IUmbracoVersion { - private readonly IGlobalSettings _globalSettings; - - public UmbracoVersion(IGlobalSettings globalSettings) - : this() - { - _globalSettings = globalSettings; - } - public UmbracoVersion() { var umbracoCoreAssembly = typeof(SemVersion).Assembly; diff --git a/src/Umbraco.Core/Editors/BackOfficeModel.cs b/src/Umbraco.Core/Editors/BackOfficeModel.cs deleted file mode 100644 index be91654d9e..0000000000 --- a/src/Umbraco.Core/Editors/BackOfficeModel.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Hosting; -using Umbraco.Core.IO; -using Umbraco.Web.Features; -using Umbraco.Web.Trees; - -namespace Umbraco.Web.Editors -{ - // TODO: Almost nothing here needs to exist since we can inject these into the view - public class BackOfficeModel - { - public BackOfficeModel(UmbracoFeatures features, IGlobalSettings globalSettings, IUmbracoVersion umbracoVersion, - IContentSettings contentSettings, - IHostingEnvironment hostingEnvironment, - IRuntimeSettings runtimeSettings, ISecuritySettings securitySettings) - { - Features = features; - GlobalSettings = globalSettings; - UmbracoVersion = umbracoVersion; - ContentSettings = contentSettings; - HostingEnvironment = hostingEnvironment; - RuntimeSettings = runtimeSettings; - SecuritySettings = securitySettings; - BackOfficePath = GlobalSettings.GetBackOfficePath(HostingEnvironment); - } - - public UmbracoFeatures Features { get; } - public IGlobalSettings GlobalSettings { get; } - public IUmbracoVersion UmbracoVersion { get; } - public IContentSettings ContentSettings { get; } - public IHostingEnvironment HostingEnvironment { get; } - public IRuntimeSettings RuntimeSettings { get; set; } - public ISecuritySettings SecuritySettings { get; set; } - - public string BackOfficePath { get; } - } -} diff --git a/src/Umbraco.Core/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs b/src/Umbraco.Core/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs index 6aeb83d61c..d6fbfae813 100644 --- a/src/Umbraco.Core/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs +++ b/src/Umbraco.Core/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Install; using Umbraco.Core.IO; using Umbraco.Core.Services; @@ -29,14 +31,14 @@ namespace Umbraco.Web.HealthCheck.Checks.Permissions public class FolderAndFilePermissionsCheck : HealthCheck { private readonly ILocalizedTextService _textService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IFilePermissionHelper _filePermissionHelper; private readonly IIOHelper _ioHelper; - public FolderAndFilePermissionsCheck(ILocalizedTextService textService, IGlobalSettings globalSettings, IFilePermissionHelper filePermissionHelper, IIOHelper ioHelper) + public FolderAndFilePermissionsCheck(ILocalizedTextService textService, IOptions globalSettings, IFilePermissionHelper filePermissionHelper, IIOHelper ioHelper) { _textService = textService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _filePermissionHelper = filePermissionHelper; _ioHelper = ioHelper; } diff --git a/src/Umbraco.Core/HealthCheck/Checks/Security/HttpsCheck.cs b/src/Umbraco.Core/HealthCheck/Checks/Security/HttpsCheck.cs index 43776ad827..7f85d326df 100644 --- a/src/Umbraco.Core/HealthCheck/Checks/Security/HttpsCheck.cs +++ b/src/Umbraco.Core/HealthCheck/Checks/Security/HttpsCheck.cs @@ -8,6 +8,8 @@ using Umbraco.Core.IO; using Umbraco.Core.Services; using Umbraco.Core.Logging; using Umbraco.Web.HealthCheck.Checks.Config; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.HealthCheck.Checks.Security { @@ -19,17 +21,17 @@ namespace Umbraco.Web.HealthCheck.Checks.Security public class HttpsCheck : HealthCheck { private readonly ILocalizedTextService _textService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; private readonly ILogger _logger; private readonly IRequestAccessor _requestAccessor; private const string FixHttpsSettingAction = "fixHttpsSetting"; - public HttpsCheck(ILocalizedTextService textService, IGlobalSettings globalSettings, IIOHelper ioHelper, ILogger logger, IRequestAccessor requestAccessor) + public HttpsCheck(ILocalizedTextService textService, IOptions globalSettings, IIOHelper ioHelper, ILogger logger, IRequestAccessor requestAccessor) { _textService = textService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _ioHelper = ioHelper; _logger = logger; _requestAccessor = requestAccessor; diff --git a/src/Umbraco.Core/HealthCheck/Checks/Services/SmtpCheck.cs b/src/Umbraco.Core/HealthCheck/Checks/Services/SmtpCheck.cs index 7b57c01223..77b1201ef6 100644 --- a/src/Umbraco.Core/HealthCheck/Checks/Services/SmtpCheck.cs +++ b/src/Umbraco.Core/HealthCheck/Checks/Services/SmtpCheck.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Net.Sockets; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Services; namespace Umbraco.Web.HealthCheck.Checks.Services @@ -16,14 +18,12 @@ namespace Umbraco.Web.HealthCheck.Checks.Services public class SmtpCheck : HealthCheck { private readonly ILocalizedTextService _textService; - private readonly IRuntimeState _runtime; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public SmtpCheck(ILocalizedTextService textService, IRuntimeState runtime, IGlobalSettings globalSettings) + public SmtpCheck(ILocalizedTextService textService, IOptions globalSettings) { _textService = textService; - _runtime = runtime; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } /// @@ -48,11 +48,11 @@ namespace Umbraco.Web.HealthCheck.Checks.Services private HealthCheckStatus CheckSmtpSettings() { - var message = string.Empty; var success = false; - var smtpSettings = _globalSettings.SmtpSettings; + var smtpSettings = _globalSettings.Smtp; + string message; if (smtpSettings == null) { message = _textService.Localize("healthcheck/smtpMailSettingsNotFound"); diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 0e5d0695dd..75a43c068f 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -6,6 +6,8 @@ using Microsoft.Extensions.Logging; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Hosting; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Core.IO { @@ -37,13 +39,13 @@ namespace Umbraco.Core.IO #region Constructor // DI wants a public ctor - public FileSystems(IFactory container, ILogger logger, ILoggerFactory loggerFactory, IIOHelper ioHelper, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public FileSystems(IFactory container, ILogger logger, ILoggerFactory loggerFactory, IIOHelper ioHelper, IOptions globalSettings, IHostingEnvironment hostingEnvironment) { _container = container; _logger = logger; _loggerFactory = loggerFactory; _ioHelper = ioHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; } @@ -158,7 +160,7 @@ namespace Umbraco.Core.IO // internal for tests internal IReadOnlyDictionary Paths => _paths; - private IGlobalSettings _globalSettings; + private GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; /// diff --git a/src/Umbraco.Core/IO/IOHelper.cs b/src/Umbraco.Core/IO/IOHelper.cs index cb074e67e5..118b528869 100644 --- a/src/Umbraco.Core/IO/IOHelper.cs +++ b/src/Umbraco.Core/IO/IOHelper.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Reflection; using System.IO; using System.Linq; +using System.Reflection; using Umbraco.Core.Hosting; using Umbraco.Core.Strings; diff --git a/src/Umbraco.Core/Models/Language.cs b/src/Umbraco.Core/Models/Language.cs index e83c59443d..0ac8526181 100644 --- a/src/Umbraco.Core/Models/Language.cs +++ b/src/Umbraco.Core/Models/Language.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Runtime.Serialization; using System.Threading; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Entities; namespace Umbraco.Core.Models @@ -14,7 +15,7 @@ namespace Umbraco.Core.Models [DataContract(IsReference = true)] public class Language : EntityBase, ILanguage { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private string _isoCode; private string _cultureName; @@ -22,7 +23,7 @@ namespace Umbraco.Core.Models private bool _mandatory; private int? _fallbackLanguageId; - public Language(IGlobalSettings globalSettings, string isoCode) + public Language(GlobalSettings globalSettings, string isoCode) { IsoCode = isoCode; _globalSettings = globalSettings; diff --git a/src/Umbraco.Core/Models/MediaExtensions.cs b/src/Umbraco.Core/Models/MediaExtensions.cs index ffcc2c2a92..9615969c07 100644 --- a/src/Umbraco.Core/Models/MediaExtensions.cs +++ b/src/Umbraco.Core/Models/MediaExtensions.cs @@ -1,5 +1,5 @@ using System.Linq; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.PropertyEditors; namespace Umbraco.Core.Models @@ -27,9 +27,9 @@ namespace Umbraco.Core.Models /// /// Gets the urls of a media item. /// - public static string[] GetUrls(this IMedia media, IContentSettings contentSettings, MediaUrlGeneratorCollection mediaUrlGenerators) + public static string[] GetUrls(this IMedia media, ContentSettings contentSettings, MediaUrlGeneratorCollection mediaUrlGenerators) { - return contentSettings.ImageAutoFillProperties + return contentSettings.Imaging.AutoFillImageProperties .Select(field => media.GetUrl(field.Alias, mediaUrlGenerators)) .Where(link => string.IsNullOrWhiteSpace(link) == false) .ToArray(); diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 43cedec951..7599997750 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Runtime.Serialization; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Entities; namespace Umbraco.Core.Models.Membership @@ -18,7 +19,7 @@ namespace Umbraco.Core.Models.Membership /// /// Constructor for creating a new/empty user /// - public User(IGlobalSettings globalSettings) + public User(GlobalSettings globalSettings) { SessionTimeout = 60; _userGroups = new HashSet(); @@ -38,7 +39,7 @@ namespace Umbraco.Core.Models.Membership /// /// /// - public User(IGlobalSettings globalSettings, string name, string email, string username, string rawPasswordValue) + public User(GlobalSettings globalSettings, string name, string email, string username, string rawPasswordValue) : this(globalSettings) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); @@ -69,7 +70,7 @@ namespace Umbraco.Core.Models.Membership /// /// /// - public User(IGlobalSettings globalSettings, int id, string name, string email, string username, + public User(GlobalSettings globalSettings, int id, string name, string email, string username, string rawPasswordValue, string passwordConfig, IEnumerable userGroups, int[] startContentIds, int[] startMediaIds) : this(globalSettings) diff --git a/src/Umbraco.Core/Models/UmbracoUserExtensions.cs b/src/Umbraco.Core/Models/UmbracoUserExtensions.cs index 6ed3e6279b..18684f7946 100644 --- a/src/Umbraco.Core/Models/UmbracoUserExtensions.cs +++ b/src/Umbraco.Core/Models/UmbracoUserExtensions.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using System.Text; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; @@ -48,14 +49,14 @@ namespace Umbraco.Core.Models /// /// /// - public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService, IGlobalSettings globalSettings) + public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService, GlobalSettings globalSettings) { if (user == null) throw new ArgumentNullException(nameof(user)); if (textService == null) throw new ArgumentNullException(nameof(textService)); return GetUserCulture(user.Language, textService, globalSettings); } - public static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService, IGlobalSettings globalSettings) + public static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService, GlobalSettings globalSettings) { try { diff --git a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs index 510a4122e9..b4cd2bd03f 100644 --- a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs +++ b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs @@ -3,7 +3,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Packaging; using File = System.IO.File; @@ -15,12 +16,12 @@ namespace Umbraco.Core.Packaging public class CompiledPackageXmlParser { private readonly ConflictingPackageData _conflictingPackageData; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public CompiledPackageXmlParser(ConflictingPackageData conflictingPackageData, IGlobalSettings globalSettings) + public CompiledPackageXmlParser(ConflictingPackageData conflictingPackageData, IOptions globalSettings) { _conflictingPackageData = conflictingPackageData; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public CompiledPackage ToCompiledPackage(XDocument xml, FileInfo packageFile, string applicationRootFolder) diff --git a/src/Umbraco.Core/Packaging/PackageFileInstallation.cs b/src/Umbraco.Core/Packaging/PackageFileInstallation.cs index 4ae20cd951..4f6c622bb3 100644 --- a/src/Umbraco.Core/Packaging/PackageFileInstallation.cs +++ b/src/Umbraco.Core/Packaging/PackageFileInstallation.cs @@ -1,15 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Xml.Linq; -using Umbraco.Core.Composing; using Umbraco.Core.IO; using Umbraco.Core.Logging; -using Umbraco.Core.Models; using Umbraco.Core.Models.Packaging; -using Umbraco.Core.Services; using File = System.IO.File; namespace Umbraco.Core.Packaging diff --git a/src/Umbraco.Core/Packaging/PackagesRepository.cs b/src/Umbraco.Core/Packaging/PackagesRepository.cs index cebad06a9a..04f50eab30 100644 --- a/src/Umbraco.Core/Packaging/PackagesRepository.cs +++ b/src/Umbraco.Core/Packaging/PackagesRepository.cs @@ -5,9 +5,10 @@ using System.IO; using System.IO.Compression; using System.Linq; using System.Xml.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Packaging; @@ -61,7 +62,7 @@ namespace Umbraco.Core.Packaging IHostingEnvironment hostingEnvironment, IEntityXmlSerializer serializer, ILogger logger, IUmbracoVersion umbracoVersion, - IGlobalSettings globalSettings, + IOptions globalSettings, string packageRepositoryFileName, string tempFolderPath = null, string packagesFolderPath = null, string mediaFolderPath = null) { @@ -79,7 +80,7 @@ namespace Umbraco.Core.Packaging _tempFolderPath = tempFolderPath ?? Constants.SystemDirectories.TempData.EnsureEndsWith('/') + "PackageFiles"; _packagesFolderPath = packagesFolderPath ?? Constants.SystemDirectories.Packages; - _mediaFolderPath = mediaFolderPath ?? globalSettings.UmbracoMediaPath + "/created-packages"; + _mediaFolderPath = mediaFolderPath ?? globalSettings.Value.UmbracoMediaPath + "/created-packages"; _parser = new PackageDefinitionXmlParser(logger, umbracoVersion); _umbracoVersion = umbracoVersion; diff --git a/src/Umbraco.Core/PublishedContentExtensions.cs b/src/Umbraco.Core/PublishedContentExtensions.cs index 03ce0c066a..62f48917c3 100644 --- a/src/Umbraco.Core/PublishedContentExtensions.cs +++ b/src/Umbraco.Core/PublishedContentExtensions.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Umbraco.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -149,7 +150,7 @@ namespace Umbraco.Core } public static bool IsAllowedTemplate(this IPublishedContent content, IContentTypeService contentTypeService, - IWebRoutingSettings webRoutingSettings, int templateId) + WebRoutingSettings webRoutingSettings, int templateId) { return content.IsAllowedTemplate(contentTypeService, webRoutingSettings.DisableAlternativeTemplates, diff --git a/src/Umbraco.Core/Routing/AliasUrlProvider.cs b/src/Umbraco.Core/Routing/AliasUrlProvider.cs index e71de2f6c6..0d919614f3 100644 --- a/src/Umbraco.Core/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Core/Routing/AliasUrlProvider.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; @@ -13,17 +15,15 @@ namespace Umbraco.Web.Routing /// public class AliasUrlProvider : IUrlProvider { - private readonly IGlobalSettings _globalSettings; - private readonly IRequestHandlerSettings _requestConfig; + private readonly RequestHandlerSettings _requestConfig; private readonly ISiteDomainHelper _siteDomainHelper; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly UriUtility _uriUtility; private readonly IPublishedValueFallback _publishedValueFallback; - public AliasUrlProvider(IGlobalSettings globalSettings, IRequestHandlerSettings requestConfig, ISiteDomainHelper siteDomainHelper, UriUtility uriUtility, IPublishedValueFallback publishedValueFallback, IUmbracoContextAccessor umbracoContextAccessor) + public AliasUrlProvider(IOptions requestConfig, ISiteDomainHelper siteDomainHelper, UriUtility uriUtility, IPublishedValueFallback publishedValueFallback, IUmbracoContextAccessor umbracoContextAccessor) { - _globalSettings = globalSettings; - _requestConfig = requestConfig; + _requestConfig = requestConfig.Value; _siteDomainHelper = siteDomainHelper; _uriUtility = uriUtility; _publishedValueFallback = publishedValueFallback; @@ -100,7 +100,7 @@ namespace Umbraco.Web.Routing { var path = "/" + alias; var uri = new Uri(path, UriKind.Relative); - yield return UrlInfo.Url(_uriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString()); + yield return UrlInfo.Url(_uriUtility.UriFromUmbraco(uri, _requestConfig).ToString()); } } else @@ -127,7 +127,7 @@ namespace Umbraco.Web.Routing { var path = "/" + alias; var uri = new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path)); - yield return UrlInfo.Url(_uriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString(), domainUri.Culture.Name); + yield return UrlInfo.Url(_uriUtility.UriFromUmbraco(uri, _requestConfig).ToString(), domainUri.Culture.Name); } } } diff --git a/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs b/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs index 52787ffc0c..6128c6e158 100644 --- a/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs @@ -4,6 +4,8 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; using System.Globalization; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Routing { @@ -17,11 +19,11 @@ namespace Umbraco.Web.Routing { private readonly ILogger _logger; private readonly IRequestAccessor _requestAccessor; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; - public ContentFinderByIdPath(IWebRoutingSettings webRoutingSettings, ILogger logger, IRequestAccessor requestAccessor) + public ContentFinderByIdPath(IOptions webRoutingSettings, ILogger logger, IRequestAccessor requestAccessor) { - _webRoutingSettings = webRoutingSettings ?? throw new System.ArgumentNullException(nameof(webRoutingSettings)); + _webRoutingSettings = webRoutingSettings.Value ?? throw new System.ArgumentNullException(nameof(webRoutingSettings)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); _requestAccessor = requestAccessor; } diff --git a/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs b/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs index ccc6bd98f2..8560c6983c 100644 --- a/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByUrlAndTemplate.cs @@ -3,6 +3,8 @@ using Umbraco.Core; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Routing { @@ -19,14 +21,14 @@ namespace Umbraco.Web.Routing private readonly IFileService _fileService; private readonly IContentTypeService _contentTypeService; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; - public ContentFinderByUrlAndTemplate(ILogger logger, IFileService fileService, IContentTypeService contentTypeService, IWebRoutingSettings webRoutingSettings) + public ContentFinderByUrlAndTemplate(ILogger logger, IFileService fileService, IContentTypeService contentTypeService, IOptions webRoutingSettings) : base(logger) { _fileService = fileService; _contentTypeService = contentTypeService; - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; } /// diff --git a/src/Umbraco.Core/Routing/DefaultUrlProvider.cs b/src/Umbraco.Core/Routing/DefaultUrlProvider.cs index b0f7e309b8..c0da30305b 100644 --- a/src/Umbraco.Core/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Core/Routing/DefaultUrlProvider.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; @@ -12,18 +14,18 @@ namespace Umbraco.Web.Routing /// public class DefaultUrlProvider : IUrlProvider { - private readonly IRequestHandlerSettings _requestSettings; + private readonly RequestHandlerSettings _requestSettings; private readonly ILogger _logger; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly ISiteDomainHelper _siteDomainHelper; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly UriUtility _uriUtility; - public DefaultUrlProvider(IRequestHandlerSettings requestSettings, ILogger logger, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility) + public DefaultUrlProvider(IOptions requestSettings, ILogger logger, IOptions globalSettings, ISiteDomainHelper siteDomainHelper, IUmbracoContextAccessor umbracoContextAccessor, UriUtility uriUtility) { - _requestSettings = requestSettings; + _requestSettings = requestSettings.Value; _logger = logger; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _siteDomainHelper = siteDomainHelper; _uriUtility = uriUtility; _umbracoContextAccessor = umbracoContextAccessor; @@ -113,7 +115,7 @@ namespace Umbraco.Web.Routing var path = pos == 0 ? route : route.Substring(pos); var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); - uri = _uriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); + uri = _uriUtility.UriFromUmbraco(uri, _requestSettings); yield return UrlInfo.Url(uri.ToString(), culture); } } @@ -172,7 +174,7 @@ namespace Umbraco.Web.Routing // UriFromUmbraco will handle vdir // meaning it will add vdir into domain urls too! - return _uriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); + return _uriUtility.UriFromUmbraco(uri, _requestSettings); } string CombinePaths(string path1, string path2) diff --git a/src/Umbraco.Core/Routing/PublishedRequest.cs b/src/Umbraco.Core/Routing/PublishedRequest.cs index a46eb26e7e..3e13270fa0 100644 --- a/src/Umbraco.Core/Routing/PublishedRequest.cs +++ b/src/Umbraco.Core/Routing/PublishedRequest.cs @@ -5,6 +5,8 @@ using System.Threading; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Routing { @@ -16,7 +18,7 @@ namespace Umbraco.Web.Routing public class PublishedRequest : IPublishedRequest { private readonly IPublishedRouter _publishedRouter; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private bool _readonly; // after prepared private bool _readonlyUri; // after preparing @@ -33,11 +35,11 @@ namespace Umbraco.Web.Routing /// The published router. /// The Umbraco context. /// The request Uri. - public PublishedRequest(IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, IWebRoutingSettings webRoutingSettings, Uri uri = null) + public PublishedRequest(IPublishedRouter publishedRouter, IUmbracoContext umbracoContext, IOptions webRoutingSettings, Uri uri = null) { UmbracoContext = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext)); _publishedRouter = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter)); - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; Uri = uri ?? umbracoContext.CleanedUmbracoUrl; } diff --git a/src/Umbraco.Core/Routing/PublishedRouter.cs b/src/Umbraco.Core/Routing/PublishedRouter.cs index 6d15d323a3..b7fe066e81 100644 --- a/src/Umbraco.Core/Routing/PublishedRouter.cs +++ b/src/Umbraco.Core/Routing/PublishedRouter.cs @@ -10,6 +10,8 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Web.Security; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Routing { @@ -18,7 +20,7 @@ namespace Umbraco.Web.Routing /// public class PublishedRouter : IPublishedRouter { - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly ContentFinderCollection _contentFinders; private readonly IContentLastChanceFinder _contentLastChanceFinder; private readonly IProfilingLogger _profilingLogger; @@ -36,7 +38,7 @@ namespace Umbraco.Web.Routing /// Initializes a new instance of the class. /// public PublishedRouter( - IWebRoutingSettings webRoutingSettings, + IOptions webRoutingSettings, ContentFinderCollection contentFinders, IContentLastChanceFinder contentLastChanceFinder, IVariationContextAccessor variationContextAccessor, @@ -50,7 +52,7 @@ namespace Umbraco.Web.Routing IContentTypeService contentTypeService, IPublicAccessService publicAccessService) { - _webRoutingSettings = webRoutingSettings ?? throw new ArgumentNullException(nameof(webRoutingSettings)); + _webRoutingSettings = webRoutingSettings.Value ?? throw new ArgumentNullException(nameof(webRoutingSettings)); _contentFinders = contentFinders ?? throw new ArgumentNullException(nameof(contentFinders)); _contentLastChanceFinder = contentLastChanceFinder ?? throw new ArgumentNullException(nameof(contentLastChanceFinder)); _profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog)); @@ -68,7 +70,7 @@ namespace Umbraco.Web.Routing /// public IPublishedRequest CreateRequest(IUmbracoContext umbracoContext, Uri uri = null) { - return new PublishedRequest(this, umbracoContext, _webRoutingSettings, uri ?? umbracoContext.CleanedUmbracoUrl); + return new PublishedRequest(this, umbracoContext, Options.Create(_webRoutingSettings), uri ?? umbracoContext.CleanedUmbracoUrl); } #region Request diff --git a/src/Umbraco.Core/Routing/UriUtility.cs b/src/Umbraco.Core/Routing/UriUtility.cs index 1ff6ba7436..1bcfab6490 100644 --- a/src/Umbraco.Core/Routing/UriUtility.cs +++ b/src/Umbraco.Core/Routing/UriUtility.cs @@ -2,6 +2,7 @@ using System.Text; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; @@ -62,7 +63,7 @@ namespace Umbraco.Web // maps an internal umbraco uri to a public uri // ie with virtual directory, .aspx if required... - public Uri UriFromUmbraco(Uri uri, IGlobalSettings globalSettings, IRequestHandlerSettings requestConfig) + public Uri UriFromUmbraco(Uri uri, RequestHandlerSettings requestConfig) { var path = uri.GetSafeAbsolutePath(); diff --git a/src/Umbraco.Core/Routing/UrlProvider.cs b/src/Umbraco.Core/Routing/UrlProvider.cs index fa764cf7ff..69d2e00276 100644 --- a/src/Umbraco.Core/Routing/UrlProvider.cs +++ b/src/Umbraco.Core/Routing/UrlProvider.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Umbraco.Core.Configuration.UmbracoSettings; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Web.Routing @@ -24,10 +25,8 @@ namespace Umbraco.Web.Routing /// The list of media url providers. /// The current variation accessor. /// - public UrlProvider(IUmbracoContextAccessor umbracoContextAccessor, IWebRoutingSettings routingSettings, UrlProviderCollection urlProviders, MediaUrlProviderCollection mediaUrlProviders, IVariationContextAccessor variationContextAccessor) + public UrlProvider(IUmbracoContextAccessor umbracoContextAccessor, IOptions routingSettings, UrlProviderCollection urlProviders, MediaUrlProviderCollection mediaUrlProviders, IVariationContextAccessor variationContextAccessor) { - if (routingSettings == null) throw new ArgumentNullException(nameof(routingSettings)); - _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); _urlProviders = urlProviders; _mediaUrlProviders = mediaUrlProviders; @@ -35,7 +34,7 @@ namespace Umbraco.Web.Routing var provider = UrlMode.Auto; Mode = provider; - if (Enum.TryParse(routingSettings.UrlProviderMode, out provider)) + if (Enum.TryParse(routingSettings.Value.UrlProviderMode, out provider)) { Mode = provider; } diff --git a/src/Umbraco.Core/Scheduling/KeepAlive.cs b/src/Umbraco.Core/Scheduling/KeepAlive.cs index 57df68d072..957b25b632 100644 --- a/src/Umbraco.Core/Scheduling/KeepAlive.cs +++ b/src/Umbraco.Core/Scheduling/KeepAlive.cs @@ -2,8 +2,9 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Sync; using Microsoft.Extensions.Logging; @@ -14,24 +15,26 @@ namespace Umbraco.Web.Scheduling { private readonly IRequestAccessor _requestAccessor; private readonly IMainDom _mainDom; - private readonly IKeepAliveSettings _keepAliveSettings; + private readonly KeepAliveSettings _keepAliveSettings; private readonly Microsoft.Extensions.Logging.ILogger _logger; private readonly IProfilingLogger _profilingLogger; private readonly IServerRegistrar _serverRegistrar; private static HttpClient _httpClient; public KeepAlive(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IRequestAccessor requestAccessor, IMainDom mainDom, IKeepAliveSettings keepAliveSettings, Microsoft.Extensions.Logging.ILogger logger, IProfilingLogger profilingLogger, IServerRegistrar serverRegistrar) + IRequestAccessor requestAccessor, IMainDom mainDom, IOptions keepAliveSettings, Microsoft.Extensions.Logging.ILogger logger, IProfilingLogger profilingLogger, IServerRegistrar serverRegistrar) : base(runner, delayMilliseconds, periodMilliseconds) { _requestAccessor = requestAccessor; _mainDom = mainDom; - _keepAliveSettings = keepAliveSettings; + _keepAliveSettings = keepAliveSettings.Value; _logger = logger; _profilingLogger = profilingLogger; _serverRegistrar = serverRegistrar; if (_httpClient == null) + { _httpClient = new HttpClient(); + } } public override async Task PerformRunAsync(CancellationToken token) diff --git a/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs b/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs index c3e7fa85c3..3894525d2d 100644 --- a/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs +++ b/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs @@ -4,6 +4,8 @@ using System.IO; using System.Linq; using System.Globalization; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Core.Strings { @@ -19,9 +21,9 @@ namespace Umbraco.Core.Strings { #region Ctor, consts and vars - public DefaultShortStringHelper(IRequestHandlerSettings settings) + public DefaultShortStringHelper(IOptions settings) { - _config = new DefaultShortStringHelperConfig().WithDefault(settings); + _config = new DefaultShortStringHelperConfig().WithDefault(settings.Value); } // clones the config so it cannot be changed at runtime diff --git a/src/Umbraco.Core/Strings/DefaultShortStringHelperConfig.cs b/src/Umbraco.Core/Strings/DefaultShortStringHelperConfig.cs index 25ee781ae9..d6adf5b221 100644 --- a/src/Umbraco.Core/Strings/DefaultShortStringHelperConfig.cs +++ b/src/Umbraco.Core/Strings/DefaultShortStringHelperConfig.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; namespace Umbraco.Core.Strings @@ -57,16 +58,16 @@ namespace Umbraco.Core.Strings /// Sets the default configuration. /// /// The short string helper. - public DefaultShortStringHelperConfig WithDefault(IRequestHandlerSettings requestHandlerSettings) + public DefaultShortStringHelperConfig WithDefault(RequestHandlerSettings requestHandlerSettings) { UrlReplaceCharacters = requestHandlerSettings.CharCollection .Where(x => string.IsNullOrEmpty(x.Char) == false) .ToDictionary(x => x.Char, x => x.Replacement); var urlSegmentConvertTo = CleanStringType.Utf8; - if (requestHandlerSettings.ConvertUrlsToAscii) + if (requestHandlerSettings.ShouldConvertUrlsToAscii) urlSegmentConvertTo = CleanStringType.Ascii; - if (requestHandlerSettings.TryConvertUrlsToAscii) + if (requestHandlerSettings.ShouldTryConvertUrlsToAscii) urlSegmentConvertTo = CleanStringType.TryAscii; return WithConfig(CleanStringType.UrlSegment, new Config diff --git a/src/Umbraco.Core/Templates/HtmlUrlParser.cs b/src/Umbraco.Core/Templates/HtmlUrlParser.cs index b06c7524a1..64ffb8d787 100644 --- a/src/Umbraco.Core/Templates/HtmlUrlParser.cs +++ b/src/Umbraco.Core/Templates/HtmlUrlParser.cs @@ -1,5 +1,6 @@ using System.Text.RegularExpressions; -using Umbraco.Core.Configuration.UmbracoSettings; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -7,7 +8,7 @@ namespace Umbraco.Web.Templates { public sealed class HtmlUrlParser { - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly ILogger _logger; private readonly IIOHelper _ioHelper; private readonly IProfilingLogger _profilingLogger; @@ -15,9 +16,9 @@ namespace Umbraco.Web.Templates private static readonly Regex ResolveUrlPattern = new Regex("(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - public HtmlUrlParser(IContentSettings contentSettings, ILogger logger ,IProfilingLogger profilingLogger, IIOHelper ioHelper) + public HtmlUrlParser(IOptions contentSettings, ILogger logger ,IProfilingLogger profilingLogger, IIOHelper ioHelper) { - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _logger = logger; _ioHelper = ioHelper; _profilingLogger = profilingLogger; diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index c8342ee716..6fa21130fc 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -16,6 +16,7 @@ + @@ -26,6 +27,9 @@ <_Parameter1>Umbraco.Tests + + <_Parameter1>Umbraco.Tests.Common + <_Parameter1>Umbraco.Tests.UnitTests diff --git a/src/Umbraco.Core/UriExtensions.cs b/src/Umbraco.Core/UriExtensions.cs index 3ecc919c10..446e60e18f 100644 --- a/src/Umbraco.Core/UriExtensions.cs +++ b/src/Umbraco.Core/UriExtensions.cs @@ -4,8 +4,8 @@ using System.Linq; using Microsoft.Extensions.Logging; using Umbraco.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; namespace Umbraco.Core { @@ -39,7 +39,7 @@ namespace Umbraco.Core /// But if we've got this far we'll just have to assume it's front-end anyways. /// /// - public static bool IsBackOfficeRequest(this Uri url, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static bool IsBackOfficeRequest(this Uri url, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var applicationPath = hostingEnvironment.ApplicationVirtualPath; @@ -129,7 +129,7 @@ namespace Umbraco.Core /// /// /// - internal static bool IsDefaultBackOfficeRequest(this Uri url, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + internal static bool IsDefaultBackOfficeRequest(this Uri url, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var backOfficePath = globalSettings.GetBackOfficePath(hostingEnvironment); if (url.AbsolutePath.InvariantEquals(backOfficePath.TrimEnd("/")) diff --git a/src/Umbraco.Examine.Lucene/LuceneFileSystemDirectoryFactory.cs b/src/Umbraco.Examine.Lucene/LuceneFileSystemDirectoryFactory.cs index 8f3bf8bf69..32c441ab28 100644 --- a/src/Umbraco.Examine.Lucene/LuceneFileSystemDirectoryFactory.cs +++ b/src/Umbraco.Examine.Lucene/LuceneFileSystemDirectoryFactory.cs @@ -6,6 +6,8 @@ using Lucene.Net.Store; using System.IO; using System; using Examine.LuceneEngine.Directories; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Examine { @@ -14,13 +16,13 @@ namespace Umbraco.Examine { private readonly ITypeFinder _typeFinder; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IIndexCreatorSettings _settings; + private readonly IndexCreatorSettings _settings; - public LuceneFileSystemDirectoryFactory(ITypeFinder typeFinder, IHostingEnvironment hostingEnvironment, IIndexCreatorSettings settings) + public LuceneFileSystemDirectoryFactory(ITypeFinder typeFinder, IHostingEnvironment hostingEnvironment, IOptions settings) { _typeFinder = typeFinder; _hostingEnvironment = hostingEnvironment; - _settings = settings; + _settings = settings.Value; } public Lucene.Net.Store.Directory CreateDirectory(string indexName) => CreateFileSystemLuceneDirectory(indexName); diff --git a/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs b/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs index fe35e9ca0f..8ecb1b4421 100644 --- a/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs +++ b/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs @@ -4,11 +4,11 @@ using System.IO; using Examine; using Examine.LuceneEngine.Directories; using Lucene.Net.Store; -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; namespace Umbraco.Examine { @@ -20,13 +20,13 @@ namespace Umbraco.Examine { private readonly ITypeFinder _typeFinder; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IIndexCreatorSettings _settings; + private readonly IndexCreatorSettings _settings; - protected LuceneIndexCreator(ITypeFinder typeFinder, IHostingEnvironment hostingEnvironment, IIndexCreatorSettings settings) + protected LuceneIndexCreator(ITypeFinder typeFinder, IHostingEnvironment hostingEnvironment, IOptions settings) { _typeFinder = typeFinder; _hostingEnvironment = hostingEnvironment; - _settings = settings; + _settings = settings.Value; } public abstract IEnumerable Create(); diff --git a/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs b/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs index 27a1b6aab9..83f6362f0c 100644 --- a/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs +++ b/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs @@ -9,6 +9,8 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Hosting; using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; @@ -32,7 +34,7 @@ namespace Umbraco.Examine IUmbracoIndexConfig umbracoIndexConfig, IHostingEnvironment hostingEnvironment, IRuntimeState runtimeState, - IIndexCreatorSettings settings, + IOptions settings, ILuceneDirectoryFactory directoryFactory) : base(typeFinder, hostingEnvironment, settings) { ProfilingLogger = profilingLogger ?? throw new System.ArgumentNullException(nameof(profilingLogger)); diff --git a/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserManager.cs b/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserManager.cs index c901c14ee1..6e11e20c8f 100644 --- a/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserManager.cs +++ b/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserManager.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Security; using Umbraco.Extensions; using Umbraco.Net; @@ -26,7 +27,7 @@ namespace Umbraco.Core.BackOffice BackOfficeIdentityErrorDescriber errors, IServiceProvider services, ILogger> logger, - IUserPasswordConfiguration passwordConfiguration) + IOptions passwordConfiguration) : base(ipResolver, store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, passwordConfiguration) { } @@ -48,11 +49,11 @@ namespace Umbraco.Core.BackOffice BackOfficeIdentityErrorDescriber errors, IServiceProvider services, ILogger> logger, - IUserPasswordConfiguration passwordConfiguration) + IOptions passwordConfiguration) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { IpResolver = ipResolver ?? throw new ArgumentNullException(nameof(ipResolver)); - PasswordConfiguration = passwordConfiguration ?? throw new ArgumentNullException(nameof(passwordConfiguration)); + PasswordConfiguration = passwordConfiguration.Value ?? throw new ArgumentNullException(nameof(passwordConfiguration)); } #region What we do not currently support diff --git a/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserStore.cs b/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserStore.cs index 96b3d8559a..d14a951877 100644 --- a/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserStore.cs +++ b/src/Umbraco.Infrastructure/BackOffice/BackOfficeUserStore.cs @@ -5,7 +5,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Models.Identity; @@ -32,16 +34,16 @@ namespace Umbraco.Core.BackOffice private readonly IUserService _userService; private readonly IEntityService _entityService; private readonly IExternalLoginService _externalLoginService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly UmbracoMapper _mapper; private bool _disposed = false; - public BackOfficeUserStore(IUserService userService, IEntityService entityService, IExternalLoginService externalLoginService, IGlobalSettings globalSettings, UmbracoMapper mapper) + public BackOfficeUserStore(IUserService userService, IEntityService entityService, IExternalLoginService externalLoginService, IOptions globalSettings, UmbracoMapper mapper) { _userService = userService; _entityService = entityService; _externalLoginService = externalLoginService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; if (userService == null) throw new ArgumentNullException("userService"); if (externalLoginService == null) throw new ArgumentNullException("externalLoginService"); _mapper = mapper; diff --git a/src/Umbraco.Infrastructure/Compose/NotificationsComponent.cs b/src/Umbraco.Infrastructure/Compose/NotificationsComponent.cs index 2ddc5e1289..e1aaaf7c12 100644 --- a/src/Umbraco.Infrastructure/Compose/NotificationsComponent.cs +++ b/src/Umbraco.Infrastructure/Compose/NotificationsComponent.cs @@ -2,9 +2,10 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; @@ -187,7 +188,7 @@ namespace Umbraco.Web.Compose private readonly INotificationService _notificationService; private readonly IUserService _userService; private readonly ILocalizedTextService _textService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly ILogger _logger; /// @@ -200,14 +201,21 @@ namespace Umbraco.Web.Compose /// /// /// - public Notifier(IUmbracoContextAccessor umbracoContextAccessor, IRequestAccessor requestAccessor, INotificationService notificationService, IUserService userService, ILocalizedTextService textService, IGlobalSettings globalSettings, ILogger logger) + public Notifier( + IUmbracoContextAccessor umbracoContextAccessor, + IRequestAccessor requestAccessor, + INotificationService notificationService, + IUserService userService, + ILocalizedTextService textService, + IOptions globalSettings, + ILogger logger) { _umbracoContextAccessor = umbracoContextAccessor; _requestAccessor = requestAccessor; _notificationService = notificationService; _userService = userService; _textService = textService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _logger = logger; } diff --git a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/FileSystems.cs b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/FileSystems.cs index 98dd585981..d6b8288b88 100644 --- a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/FileSystems.cs +++ b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/FileSystems.cs @@ -1,5 +1,7 @@ using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.IO.MediaPathSchemes; @@ -97,7 +99,7 @@ namespace Umbraco.Core.Composing.CompositionExtensions var ioHelper = factory.GetInstance(); var hostingEnvironment = factory.GetInstance(); var logger = factory.GetInstance>(); - var globalSettings = factory.GetInstance(); + var globalSettings = factory.GetInstance>().Value; var rootPath = hostingEnvironment.MapPathWebRoot(globalSettings.UmbracoMediaPath); var rootUrl = hostingEnvironment.ToAbsolute(globalSettings.UmbracoMediaPath); diff --git a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Services.cs b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Services.cs index 980dd1c11e..ffd8b880f2 100644 --- a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Services.cs +++ b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Services.cs @@ -1,8 +1,10 @@ using System; using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Hosting; using Umbraco.Core.IO; @@ -94,13 +96,13 @@ namespace Umbraco.Core.Composing.CompositionExtensions factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), - factory.GetInstance(), + factory.GetInstance>(), packageRepoFileName); private static LocalizedTextServiceFileSources SourcesFactory(IFactory container) { var hostingEnvironment = container.GetInstance(); - var globalSettings = container.GetInstance(); + var globalSettings = container.GetInstance>().Value; var mainLangFolder = new DirectoryInfo(hostingEnvironment.MapPathContentRoot(WebPath.Combine(globalSettings.UmbracoPath , "config","lang"))); var appPlugins = new DirectoryInfo(hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.AppPlugins)); var configLangFolder = new DirectoryInfo(hostingEnvironment.MapPathContentRoot(WebPath.Combine(Constants.SystemDirectories.Config ,"lang"))); diff --git a/src/Umbraco.Infrastructure/Composing/RegisterFactory.cs b/src/Umbraco.Infrastructure/Composing/RegisterFactory.cs index 835bd0b9a8..d6c0e74d75 100644 --- a/src/Umbraco.Infrastructure/Composing/RegisterFactory.cs +++ b/src/Umbraco.Infrastructure/Composing/RegisterFactory.cs @@ -6,6 +6,7 @@ using System; using System.Reflection; using Umbraco.Core.Composing.LightInject; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Core.Composing { @@ -29,7 +30,7 @@ namespace Umbraco.Core.Composing /// To override the default LightInjectContainer, add an appSetting named 'Umbraco.Core.RegisterType' with /// a fully qualified type name to a class with a static method "Create" returning an IRegister. /// - public static IRegister Create(IGlobalSettings globalSettings) + public static IRegister Create(GlobalSettings globalSettings) { Type type; diff --git a/src/Umbraco.Infrastructure/Composing/UmbracoServiceProviderFactory.cs b/src/Umbraco.Infrastructure/Composing/UmbracoServiceProviderFactory.cs index d293097144..ec7c76634e 100644 --- a/src/Umbraco.Infrastructure/Composing/UmbracoServiceProviderFactory.cs +++ b/src/Umbraco.Infrastructure/Composing/UmbracoServiceProviderFactory.cs @@ -2,9 +2,11 @@ using LightInject.Microsoft.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using System; +using Microsoft.Extensions.Options; using Umbraco.Composing; using Umbraco.Core.Composing.LightInject; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; namespace Umbraco.Core.Composing @@ -86,7 +88,8 @@ namespace Umbraco.Core.Composing // after cross wiring, configure "Current" Current.Initialize( _container.GetInstance>(), - _container.GetInstance(), + _container.GetInstance>().Value, + _container.GetInstance>().Value, _container.GetInstance(), _container.GetInstance(), _container.GetInstance(), diff --git a/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs b/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs index a7b1528dc2..a3a43d2b93 100644 --- a/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs +++ b/src/Umbraco.Infrastructure/Configuration/JsonConfigManipulator.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.FileProviders; using Newtonsoft.Json; using Newtonsoft.Json.Linq; + namespace Umbraco.Core.Configuration { public class JsonConfigManipulator : IConfigManipulator diff --git a/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/EmailNotificationMethod.cs b/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/EmailNotificationMethod.cs index 0240d60f29..49981b0b9a 100644 --- a/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/EmailNotificationMethod.cs +++ b/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/EmailNotificationMethod.cs @@ -2,11 +2,11 @@ using System.Net.Mail; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.HealthChecks; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Logging; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Services; namespace Umbraco.Web.HealthCheck.NotificationMethods @@ -17,10 +17,16 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods private readonly ILocalizedTextService _textService; private readonly IRequestAccessor _requestAccessor; - private readonly IGlobalSettings _globalSettings; - private readonly IContentSettings _contentSettings; + private readonly GlobalSettings _globalSettings; + private readonly ContentSettings _contentSettings; - public EmailNotificationMethod(ILocalizedTextService textService, IRequestAccessor requestAccessor, IGlobalSettings globalSettings, IHealthChecksSettings healthChecksSettings, IContentSettings contentSettings) : base(healthChecksSettings) + public EmailNotificationMethod( + ILocalizedTextService textService, + IRequestAccessor requestAccessor, + IOptions globalSettings, + IOptions healthChecksSettings, + IOptions contentSettings) + : base(healthChecksSettings) { var recipientEmail = Settings?["recipientEmail"]?.Value; if (string.IsNullOrWhiteSpace(recipientEmail)) @@ -33,8 +39,8 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods _textService = textService ?? throw new ArgumentNullException(nameof(textService)); _requestAccessor = requestAccessor; - _globalSettings = globalSettings; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _globalSettings = globalSettings.Value; + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); } public string RecipientEmail { get; } @@ -64,7 +70,7 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods var subject = _textService.Localize("healthcheck/scheduledHealthCheckEmailSubject", new[] { host.ToString() }); - var mailSender = new EmailSender(_globalSettings); + var mailSender = new EmailSender(Options.Create(_globalSettings)); using (var mailMessage = CreateMailMessage(subject, message)) { await mailSender.SendAsync(mailMessage); @@ -73,7 +79,7 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods private MailMessage CreateMailMessage(string subject, string message) { - var to = _contentSettings.NotificationEmailAddress; + var to = _contentSettings.Notifications.Email; if (string.IsNullOrWhiteSpace(subject)) subject = "Umbraco Health Check Status"; diff --git a/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/NotificationMethodBase.cs b/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/NotificationMethodBase.cs index 3e6606e965..2c0c5bcc1f 100644 --- a/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/NotificationMethodBase.cs +++ b/src/Umbraco.Infrastructure/HealthCheck/NotificationMethods/NotificationMethodBase.cs @@ -2,13 +2,15 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration.HealthChecks; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.HealthCheck.NotificationMethods { public abstract class NotificationMethodBase : IHealthCheckNotificationMethod { - protected NotificationMethodBase(IHealthChecksSettings healthCheckSettingsConfig) + protected NotificationMethodBase(IOptions healthCheckSettings) { var type = GetType(); var attribute = type.GetCustomAttribute(); @@ -18,7 +20,7 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods return; } - var notificationMethods = healthCheckSettingsConfig.NotificationSettings.NotificationMethods; + var notificationMethods = healthCheckSettings.Value.NotificationSettings.NotificationMethods; if(!notificationMethods.TryGetValue(attribute.Alias, out var notificationMethod)) { Enabled = false; diff --git a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs index 4c3edf0a1b..7a20a1189e 100644 --- a/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs +++ b/src/Umbraco.Infrastructure/Install/FilePermissionHelper.cs @@ -8,6 +8,8 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Install; using Umbraco.Core.IO; using Umbraco.Web.PublishedCache; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Install { @@ -19,13 +21,13 @@ namespace Umbraco.Web.Install // ensure Umbraco can write to these files (the directories must exist) private readonly string[] _permissionFiles = { }; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; private readonly IPublishedSnapshotService _publishedSnapshotService; - public FilePermissionHelper(IGlobalSettings globalSettings, IIOHelper ioHelper, IPublishedSnapshotService publishedSnapshotService) + public FilePermissionHelper(IOptions globalSettings, IIOHelper ioHelper, IPublishedSnapshotService publishedSnapshotService) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _ioHelper = ioHelper; _publishedSnapshotService = publishedSnapshotService; _permissionDirs = new[] { _globalSettings.UmbracoCssPath, Constants.SystemDirectories.Config, Constants.SystemDirectories.Data, _globalSettings.UmbracoMediaPath, Constants.SystemDirectories.Preview }; diff --git a/src/Umbraco.Infrastructure/Install/InstallHelper.cs b/src/Umbraco.Infrastructure/Install/InstallHelper.cs index 08d4d40b92..e15aa0ab76 100644 --- a/src/Umbraco.Infrastructure/Install/InstallHelper.cs +++ b/src/Umbraco.Infrastructure/Install/InstallHelper.cs @@ -13,6 +13,8 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Web.Install.Models; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.Install { @@ -22,7 +24,7 @@ namespace Umbraco.Web.Install private readonly DatabaseBuilder _databaseBuilder; private readonly ILogger _logger; private readonly IUmbracoVersion _umbracoVersion; - private readonly IConnectionStrings _connectionStrings; + private readonly ConnectionStrings _connectionStrings; private readonly IInstallationService _installationService; private readonly ICookieManager _cookieManager; private readonly IUserAgentProvider _userAgentProvider; @@ -33,7 +35,7 @@ namespace Umbraco.Web.Install public InstallHelper(DatabaseBuilder databaseBuilder, ILogger logger, IUmbracoVersion umbracoVersion, - IConnectionStrings connectionStrings, + IOptions connectionStrings, IInstallationService installationService, ICookieManager cookieManager, IUserAgentProvider userAgentProvider, @@ -43,7 +45,7 @@ namespace Umbraco.Web.Install _logger = logger; _umbracoVersion = umbracoVersion; _databaseBuilder = databaseBuilder; - _connectionStrings = connectionStrings ?? throw new ArgumentNullException(nameof(connectionStrings)); + _connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); _installationService = installationService; _cookieManager = cookieManager; _userAgentProvider = userAgentProvider; @@ -114,7 +116,7 @@ namespace Umbraco.Web.Install { get { - var databaseSettings = _connectionStrings[Constants.System.UmbracoConnectionName]; + var databaseSettings = _connectionStrings.UmbracoConnectionString; if (databaseSettings.IsConnectionStringConfigured() == false) { //no version or conn string configured, must be a brand new install diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseConfigureStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseConfigureStep.cs index 3b798ec767..0dceaf9339 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseConfigureStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseConfigureStep.cs @@ -5,7 +5,8 @@ using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Migrations.Install; using Umbraco.Web.Install.Models; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Install.InstallSteps { @@ -16,12 +17,12 @@ namespace Umbraco.Web.Install.InstallSteps { private readonly DatabaseBuilder _databaseBuilder; private readonly ILogger _logger; - private readonly IConnectionStrings _connectionStrings; + private readonly ConnectionStrings _connectionStrings; - public DatabaseConfigureStep(DatabaseBuilder databaseBuilder, IConnectionStrings connectionStrings) + public DatabaseConfigureStep(DatabaseBuilder databaseBuilder, IOptions connectionStrings) { _databaseBuilder = databaseBuilder; - _connectionStrings = connectionStrings ?? throw new ArgumentNullException(nameof(connectionStrings)); + _connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); } public override Task ExecuteAsync(DatabaseModel database) @@ -107,7 +108,7 @@ namespace Umbraco.Web.Install.InstallSteps private bool ShouldDisplayView() { //If the connection string is already present in web.config we don't need to show the settings page and we jump to installing/upgrading. - var databaseSettings = _connectionStrings[Constants.System.UmbracoConnectionName]; + var databaseSettings = _connectionStrings.UmbracoConnectionString; if (databaseSettings.IsConnectionStringConfigured()) { diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseInstallStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseInstallStep.cs index b3086672d8..e5f783caba 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseInstallStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseInstallStep.cs @@ -16,19 +16,11 @@ namespace Umbraco.Web.Install.InstallSteps { private readonly DatabaseBuilder _databaseBuilder; private readonly IRuntimeState _runtime; - private readonly ILogger _logger; - private readonly IIOHelper _ioHelper; - private readonly IConnectionStrings _connectionStrings; - private readonly IConfigManipulator _configManipulator; - public DatabaseInstallStep(DatabaseBuilder databaseBuilder, IRuntimeState runtime, ILogger logger, IIOHelper ioHelper, IConnectionStrings connectionStrings, IConfigManipulator configManipulator) + public DatabaseInstallStep(DatabaseBuilder databaseBuilder, IRuntimeState runtime) { _databaseBuilder = databaseBuilder; _runtime = runtime; - _logger = logger; - _ioHelper = ioHelper; - _connectionStrings = connectionStrings; - _configManipulator = configManipulator; } public override Task ExecuteAsync(object model) diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseUpgradeStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseUpgradeStep.cs index 02e852eb90..a623a0f378 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseUpgradeStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/DatabaseUpgradeStep.cs @@ -1,8 +1,10 @@ using System; using System.Linq; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Migrations.Install; @@ -20,29 +22,20 @@ namespace Umbraco.Web.Install.InstallSteps private readonly IRuntimeState _runtime; private readonly ILogger _logger; private readonly IUmbracoVersion _umbracoVersion; - private readonly IGlobalSettings _globalSettings; - private readonly IConnectionStrings _connectionStrings; - private readonly IIOHelper _ioHelper; - private readonly IConfigManipulator _configManipulator; + private readonly ConnectionStrings _connectionStrings; public DatabaseUpgradeStep( DatabaseBuilder databaseBuilder, IRuntimeState runtime, ILogger logger, IUmbracoVersion umbracoVersion, - IGlobalSettings globalSettings, - IConnectionStrings connectionStrings, - IIOHelper ioHelper, - IConfigManipulator configManipulator) + IOptions connectionStrings) { _databaseBuilder = databaseBuilder; _runtime = runtime; _logger = logger; _umbracoVersion = umbracoVersion; - _globalSettings = globalSettings; - _connectionStrings = connectionStrings ?? throw new ArgumentNullException(nameof(connectionStrings)); - _ioHelper = ioHelper; - _configManipulator = configManipulator; + _connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); } public override Task ExecuteAsync(object model) @@ -55,7 +48,7 @@ namespace Umbraco.Web.Install.InstallSteps { _logger.LogInformation("Running 'Upgrade' service"); - var plan = new UmbracoPlan(_umbracoVersion, _globalSettings); + var plan = new UmbracoPlan(_umbracoVersion); plan.AddPostMigration(); // needed when running installer (back-office) var result = _databaseBuilder.UpgradeSchemaAndData(plan); @@ -82,7 +75,7 @@ namespace Umbraco.Web.Install.InstallSteps return false; } - var databaseSettings = _connectionStrings[Constants.System.UmbracoConnectionName]; + var databaseSettings = _connectionStrings.UmbracoConnectionString; if (databaseSettings.IsConnectionStringConfigured()) { diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs index a240eaf104..f2e9556a48 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/NewInstallStep.cs @@ -3,15 +3,16 @@ using System.Collections.Specialized; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Umbraco.Core; +using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Services; -using Umbraco.Web.Install.Models; -using Umbraco.Core.BackOffice; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Extensions; +using Umbraco.Web.Install.Models; namespace Umbraco.Web.Install.InstallSteps { @@ -29,21 +30,26 @@ namespace Umbraco.Web.Install.InstallSteps private readonly IUserService _userService; private readonly DatabaseBuilder _databaseBuilder; private static HttpClient _httpClient; - private readonly IGlobalSettings _globalSettings; - private readonly IUserPasswordConfiguration _passwordConfiguration; - private readonly ISecuritySettings _securitySettings; - private readonly IConnectionStrings _connectionStrings; + private readonly UserPasswordConfigurationSettings _passwordConfiguration; + private readonly SecuritySettings _securitySettings; + private readonly ConnectionStrings _connectionStrings; private readonly ICookieManager _cookieManager; private readonly BackOfficeUserManager _userManager; - public NewInstallStep(IUserService userService, DatabaseBuilder databaseBuilder, IGlobalSettings globalSettings, IUserPasswordConfiguration passwordConfiguration, ISecuritySettings securitySettings, IConnectionStrings connectionStrings, ICookieManager cookieManager, BackOfficeUserManager userManager) + public NewInstallStep( + IUserService userService, + DatabaseBuilder databaseBuilder, + IOptions passwordConfiguration, + IOptions securitySettings, + IOptions connectionStrings, + ICookieManager cookieManager, + BackOfficeUserManager userManager) { _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _databaseBuilder = databaseBuilder ?? throw new ArgumentNullException(nameof(databaseBuilder)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); - _passwordConfiguration = passwordConfiguration ?? throw new ArgumentNullException(nameof(passwordConfiguration)); - _securitySettings = securitySettings ?? throw new ArgumentNullException(nameof(securitySettings)); - _connectionStrings = connectionStrings ?? throw new ArgumentNullException(nameof(connectionStrings)); + _passwordConfiguration = passwordConfiguration.Value ?? throw new ArgumentNullException(nameof(passwordConfiguration)); + _securitySettings = securitySettings.Value ?? throw new ArgumentNullException(nameof(securitySettings)); + _connectionStrings = connectionStrings.Value ?? throw new ArgumentNullException(nameof(connectionStrings)); _cookieManager = cookieManager; _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); } @@ -126,7 +132,7 @@ namespace Umbraco.Web.Install.InstallSteps public override bool RequiresExecution(UserModel model) { //now we have to check if this is really a new install, the db might be configured and might contain data - var databaseSettings = _connectionStrings[Constants.System.UmbracoConnectionName]; + var databaseSettings = _connectionStrings.UmbracoConnectionString; if (databaseSettings.IsConnectionStringConfigured() && _databaseBuilder.IsDatabaseConfigured) return _databaseBuilder.HasSomeNonDefaultUser() == false; diff --git a/src/Umbraco.Infrastructure/Logging/Serilog/Enrichers/ThreadAbortExceptionEnricher.cs b/src/Umbraco.Infrastructure/Logging/Serilog/Enrichers/ThreadAbortExceptionEnricher.cs index 1f495d3a50..8428b60fde 100644 --- a/src/Umbraco.Infrastructure/Logging/Serilog/Enrichers/ThreadAbortExceptionEnricher.cs +++ b/src/Umbraco.Infrastructure/Logging/Serilog/Enrichers/ThreadAbortExceptionEnricher.cs @@ -1,11 +1,12 @@ using System; using System.Reflection; using System.Threading; +using Microsoft.Extensions.Options; using Serilog.Core; using Serilog.Events; -using Umbraco.Core.Configuration; using Umbraco.Core.Diagnostics; using Umbraco.Core.Hosting; +using CoreDebugSettings = Umbraco.Core.Configuration.Models.CoreDebugSettings; namespace Umbraco.Infrastructure.Logging.Serilog.Enrichers { @@ -14,13 +15,13 @@ namespace Umbraco.Infrastructure.Logging.Serilog.Enrichers /// public class ThreadAbortExceptionEnricher : ILogEventEnricher { - private readonly ICoreDebugSettings _coreDebugSettings; + private readonly CoreDebugSettings _coreDebugSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IMarchal _marchal; - public ThreadAbortExceptionEnricher(ICoreDebugSettings coreDebugSettings, IHostingEnvironment hostingEnvironment, IMarchal marchal) + public ThreadAbortExceptionEnricher(IOptions coreDebugSettings, IHostingEnvironment hostingEnvironment, IMarchal marchal) { - _coreDebugSettings = coreDebugSettings; + _coreDebugSettings = coreDebugSettings.Value; _hostingEnvironment = hostingEnvironment; _marchal = marchal; } diff --git a/src/Umbraco.Infrastructure/Media/UploadAutoFillProperties.cs b/src/Umbraco.Infrastructure/Media/UploadAutoFillProperties.cs index e947afe6e2..d69de29b94 100644 --- a/src/Umbraco.Infrastructure/Media/UploadAutoFillProperties.cs +++ b/src/Umbraco.Infrastructure/Media/UploadAutoFillProperties.cs @@ -1,8 +1,10 @@ using System; using System.Drawing; using System.IO; -using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -17,13 +19,16 @@ namespace Umbraco.Web.Media { private readonly IMediaFileSystem _mediaFileSystem; private readonly ILogger _logger; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; - public UploadAutoFillProperties(IMediaFileSystem mediaFileSystem, ILogger logger, IContentSettings contentSettings) + public UploadAutoFillProperties( + IMediaFileSystem mediaFileSystem, + ILogger logger, + IOptions contentSettings) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); } /// diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs index a3d7ee46d0..b27bc48c8e 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs @@ -3,7 +3,9 @@ using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Migrations.Upgrade; @@ -21,7 +23,6 @@ namespace Umbraco.Core.Migrations.Install { private readonly IUmbracoDatabaseFactory _databaseFactory; private readonly IScopeProvider _scopeProvider; - private readonly IGlobalSettings _globalSettings; private readonly IRuntimeState _runtime; private readonly IMigrationBuilder _migrationBuilder; private readonly IKeyValueService _keyValueService; @@ -39,7 +40,6 @@ namespace Umbraco.Core.Migrations.Install /// public DatabaseBuilder( IScopeProvider scopeProvider, - IGlobalSettings globalSettings, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, @@ -52,7 +52,6 @@ namespace Umbraco.Core.Migrations.Install IConfigManipulator configManipulator) { _scopeProvider = scopeProvider; - _globalSettings = globalSettings; _databaseFactory = databaseFactory; _runtime = runtime; _logger = logger; @@ -322,7 +321,7 @@ namespace Umbraco.Core.Migrations.Install return _databaseSchemaValidationResult; var database = scope.Database; - var dbSchema = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion, _globalSettings); + var dbSchema = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); _databaseSchemaValidationResult = dbSchema.ValidateSchema(); return _databaseSchemaValidationResult; } @@ -370,7 +369,7 @@ namespace Umbraco.Core.Migrations.Install if (_runtime.Level == RuntimeLevel.Run) throw new Exception("Umbraco is already configured!"); - var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion, _globalSettings); + var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); creator.InitializeDatabaseSchema(); message = message + "

Installation completed!

"; diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs index 825998c8e4..1ade2f5153 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseDataCreator.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Dtos; @@ -16,14 +17,12 @@ namespace Umbraco.Core.Migrations.Install private readonly IDatabase _database; private readonly ILogger _logger; private readonly IUmbracoVersion _umbracoVersion; - private readonly IGlobalSettings _globalSettings; - public DatabaseDataCreator(IDatabase database, ILogger logger, IUmbracoVersion umbracoVersion, IGlobalSettings globalSettings) + public DatabaseDataCreator(IDatabase database, ILogger logger, IUmbracoVersion umbracoVersion) { _database = database; _logger = logger; _umbracoVersion = umbracoVersion; - _globalSettings = globalSettings; } /// @@ -340,7 +339,7 @@ namespace Umbraco.Core.Migrations.Install { // on install, initialize the umbraco migration plan with the final state - var upgrader = new Upgrader(new UmbracoPlan(_umbracoVersion, _globalSettings)); + var upgrader = new Upgrader(new UmbracoPlan(_umbracoVersion)); var stateValueKey = upgrader.StateValueKey; var finalState = upgrader.Plan.FinalState; diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs index c601e85479..5bca64e1e1 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseSchemaCreator.cs @@ -4,6 +4,7 @@ using System.Linq; using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseModelDefinitions; @@ -21,15 +22,13 @@ namespace Umbraco.Core.Migrations.Install private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; private readonly IUmbracoVersion _umbracoVersion; - private readonly IGlobalSettings _globalSettings; - public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger logger, ILoggerFactory loggerFactory, IUmbracoVersion umbracoVersion, IGlobalSettings globalSettings) + public DatabaseSchemaCreator(IUmbracoDatabase database, ILogger logger, ILoggerFactory loggerFactory, IUmbracoVersion umbracoVersion) { _database = database; _logger = logger; _loggerFactory = loggerFactory; _umbracoVersion = umbracoVersion; - _globalSettings = globalSettings; } private ISqlSyntaxProvider SqlSyntax => _database.SqlContext.SqlSyntax; @@ -132,7 +131,7 @@ namespace Umbraco.Core.Migrations.Install if (e.Cancel == false) { - var dataCreation = new DatabaseDataCreator(_database, _loggerFactory.CreateLogger(), _umbracoVersion, _globalSettings); + var dataCreation = new DatabaseDataCreator(_database, _loggerFactory.CreateLogger(), _umbracoVersion); foreach (var table in OrderedTables) CreateTable(false, table, dataCreation); } @@ -402,7 +401,7 @@ namespace Umbraco.Core.Migrations.Install where T : new() { var tableType = typeof(T); - CreateTable(overwrite, tableType, new DatabaseDataCreator(_database, _loggerFactory.CreateLogger(), _umbracoVersion, _globalSettings)); + CreateTable(overwrite, tableType, new DatabaseDataCreator(_database, _loggerFactory.CreateLogger(), _umbracoVersion)); } /// diff --git a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs index c671b0d236..7f8c47f92f 100644 --- a/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Infrastructure/Migrations/Upgrade/UmbracoPlan.cs @@ -2,6 +2,7 @@ using Semver; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Upgrade.Common; using Umbraco.Core.Migrations.Upgrade.V_8_0_0; using Umbraco.Core.Migrations.Upgrade.V_8_0_1; @@ -16,17 +17,15 @@ namespace Umbraco.Core.Migrations.Upgrade public class UmbracoPlan : MigrationPlan { private readonly IUmbracoVersion _umbracoVersion; - private readonly IGlobalSettings _globalSettings; private const string InitPrefix = "{init-"; private const string InitSuffix = "}"; /// /// Initializes a new instance of the class. /// - public UmbracoPlan(IUmbracoVersion umbracoVersion, IGlobalSettings globalSettings) + public UmbracoPlan(IUmbracoVersion umbracoVersion) : base(Constants.System.UmbracoUpgradePlanName) { _umbracoVersion = umbracoVersion; - _globalSettings = globalSettings; DefinePlan(); } @@ -191,7 +190,7 @@ namespace Umbraco.Core.Migrations.Upgrade // to 8.7.0... To("{a78e3369-8ea3-40ec-ad3f-5f76929d2b20}"); - + //FINAL } } diff --git a/src/Umbraco.Infrastructure/Models/ContentEditing/UserInvite.cs b/src/Umbraco.Infrastructure/Models/ContentEditing/UserInvite.cs index 06e4d0748c..68a7a9bd3f 100644 --- a/src/Umbraco.Infrastructure/Models/ContentEditing/UserInvite.cs +++ b/src/Umbraco.Infrastructure/Models/ContentEditing/UserInvite.cs @@ -33,7 +33,8 @@ namespace Umbraco.Web.Models.ContentEditing if (UserGroups.Any() == false) yield return new ValidationResult("A user must be assigned to at least one group", new[] { nameof(UserGroups) }); - if (Current.Configs.Security().UsernameIsEmail == false && Username.IsNullOrWhiteSpace()) + // TODO: this will need another way of retrieving this setting if and when Configs are removed from Current. + if (Current.SecuritySettings.UsernameIsEmail == false && Username.IsNullOrWhiteSpace()) yield return new ValidationResult("A username cannot be empty", new[] { nameof(Username) }); } } diff --git a/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs b/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs index 75a64c7b1e..eb130ae13a 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs @@ -13,6 +13,8 @@ using Umbraco.Core.Exceptions; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Strings; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Models.Mapping { @@ -30,13 +32,12 @@ namespace Umbraco.Web.Models.Mapping private readonly IMemberTypeService _memberTypeService; private readonly ILogger _logger; private readonly IShortStringHelper _shortStringHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; - public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, - ILogger logger, IShortStringHelper shortStringHelper, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + ILogger logger, IShortStringHelper shortStringHelper, IOptions globalSettings, IHostingEnvironment hostingEnvironment) { _commonMapper = commonMapper; _propertyEditors = propertyEditors; @@ -47,7 +48,7 @@ namespace Umbraco.Web.Models.Mapping _memberTypeService = memberTypeService; _logger = logger; _shortStringHelper = shortStringHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.Infrastructure/Models/Mapping/DataTypeMapDefinition.cs b/src/Umbraco.Infrastructure/Models/Mapping/DataTypeMapDefinition.cs index f7719c0b08..97ce0c4b5f 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/DataTypeMapDefinition.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/DataTypeMapDefinition.cs @@ -1,8 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Models; @@ -15,13 +16,13 @@ namespace Umbraco.Web.Models.Mapping { private readonly PropertyEditorCollection _propertyEditors; private readonly ILogger _logger; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; - public DataTypeMapDefinition(PropertyEditorCollection propertyEditors, ILogger logger, IContentSettings contentSettings) + public DataTypeMapDefinition(PropertyEditorCollection propertyEditors, ILogger logger, IOptions contentSettings) { _propertyEditors = propertyEditors; _logger = logger; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); } private static readonly int[] SystemIds = diff --git a/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs b/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs index 9045be20aa..b281e18b73 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Dictionary; using Umbraco.Core.Mapping; using Umbraco.Core.Models; +using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; -using Umbraco.Core.Dictionary; -using Umbraco.Core.Configuration; -using Umbraco.Core.PropertyEditors; using Umbraco.Web.Security; namespace Umbraco.Web.Models.Mapping @@ -28,7 +29,7 @@ namespace Umbraco.Web.Models.Mapping private readonly IMemberTypeService _memberTypeService; private readonly IMemberService _memberService; private readonly IMemberGroupService _memberGroupService; - private readonly IMemberPasswordConfiguration _memberPasswordConfiguration; + private readonly MemberPasswordConfigurationSettings _memberPasswordConfiguration; private readonly PropertyEditorCollection _propertyEditorCollection; public MemberTabsAndPropertiesMapper(ICultureDictionary cultureDictionary, @@ -37,7 +38,7 @@ namespace Umbraco.Web.Models.Mapping IMemberTypeService memberTypeService, IMemberService memberService, IMemberGroupService memberGroupService, - IMemberPasswordConfiguration memberPasswordConfiguration, + IOptions memberPasswordConfiguration, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider, PropertyEditorCollection propertyEditorCollection) : base(cultureDictionary, localizedTextService, contentTypeBaseServiceProvider) @@ -47,7 +48,7 @@ namespace Umbraco.Web.Models.Mapping _memberTypeService = memberTypeService ?? throw new ArgumentNullException(nameof(memberTypeService)); _memberService = memberService ?? throw new ArgumentNullException(nameof(memberService)); _memberGroupService = memberGroupService ?? throw new ArgumentNullException(nameof(memberGroupService)); - _memberPasswordConfiguration = memberPasswordConfiguration; + _memberPasswordConfiguration = memberPasswordConfiguration.Value; _propertyEditorCollection = propertyEditorCollection; } diff --git a/src/Umbraco.Infrastructure/Models/Mapping/UserMapDefinition.cs b/src/Umbraco.Infrastructure/Models/Mapping/UserMapDefinition.cs index 043b37a654..58a0d98be1 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/UserMapDefinition.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/UserMapDefinition.cs @@ -18,6 +18,8 @@ using Umbraco.Web.Actions; using Umbraco.Web.Services; using Umbraco.Core.Media; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Models.Mapping { @@ -29,13 +31,13 @@ namespace Umbraco.Web.Models.Mapping private readonly ILocalizedTextService _textService; private readonly ActionCollection _actions; private readonly AppCaches _appCaches; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IMediaFileSystem _mediaFileSystem; private readonly IShortStringHelper _shortStringHelper; private readonly IImageUrlGenerator _imageUrlGenerator; public UserMapDefinition(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, - AppCaches appCaches, ActionCollection actions, IGlobalSettings globalSettings, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, + AppCaches appCaches, ActionCollection actions, IOptions globalSettings, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, IImageUrlGenerator imageUrlGenerator) { _sectionService = sectionService; @@ -44,7 +46,7 @@ namespace Umbraco.Web.Models.Mapping _textService = textService; _actions = actions; _appCaches = appCaches; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _mediaFileSystem = mediaFileSystem; _shortStringHelper = shortStringHelper; _imageUrlGenerator = imageUrlGenerator; diff --git a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs index 20f54dbc39..51a19fb4ba 100644 --- a/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs +++ b/src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs @@ -5,8 +5,10 @@ using System.Linq; using System.Net; using System.Xml.Linq; using System.Xml.XPath; +using Microsoft.Extensions.Options; using Umbraco.Core.Collections; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; @@ -29,7 +31,7 @@ namespace Umbraco.Core.Packaging private readonly PropertyEditorCollection _propertyEditors; private readonly IScopeProvider _scopeProvider; private readonly IShortStringHelper _shortStringHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly ILocalizedTextService _localizedTextService; private readonly IEntityService _entityService; private readonly IContentTypeService _contentTypeService; @@ -37,7 +39,7 @@ namespace Umbraco.Core.Packaging public PackageDataInstallation(ILogger logger, IFileService fileService, IMacroService macroService, ILocalizationService localizationService, IDataTypeService dataTypeService, IEntityService entityService, IContentTypeService contentTypeService, - IContentService contentService, PropertyEditorCollection propertyEditors, IScopeProvider scopeProvider, IShortStringHelper shortStringHelper, IGlobalSettings globalSettings, + IContentService contentService, PropertyEditorCollection propertyEditors, IScopeProvider scopeProvider, IShortStringHelper shortStringHelper, IOptions globalSettings, ILocalizedTextService localizedTextService) { _logger = logger; @@ -48,7 +50,7 @@ namespace Umbraco.Core.Packaging _propertyEditors = propertyEditors; _scopeProvider = scopeProvider; _shortStringHelper = shortStringHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _localizedTextService = localizedTextService; _entityService = entityService; _contentTypeService = contentTypeService; diff --git a/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs b/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs index cf31b3ea52..4970fc302e 100644 --- a/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs +++ b/src/Umbraco.Infrastructure/Packaging/PackageInstallation.cs @@ -28,7 +28,6 @@ namespace Umbraco.Core.Packaging public PackageInstallation(PackageDataInstallation packageDataInstallation, PackageFileInstallation packageFileInstallation, CompiledPackageXmlParser parser, IPackageActionRunner packageActionRunner, IHostingEnvironment hostingEnvironment) { - _packageExtraction = new PackageExtraction(); _packageFileInstallation = packageFileInstallation ?? throw new ArgumentNullException(nameof(packageFileInstallation)); _packageDataInstallation = packageDataInstallation ?? throw new ArgumentNullException(nameof(packageDataInstallation)); diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/LanguageFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/LanguageFactory.cs index 1da4a8dfac..0b5937a328 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/LanguageFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/LanguageFactory.cs @@ -1,5 +1,6 @@ using System.Globalization; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Dtos; @@ -7,7 +8,7 @@ namespace Umbraco.Core.Persistence.Factories { internal static class LanguageFactory { - public static ILanguage BuildEntity(IGlobalSettings globalSettings, LanguageDto dto) + public static ILanguage BuildEntity(GlobalSettings globalSettings, LanguageDto dto) { var lang = new Language(globalSettings, dto.IsoCode) { diff --git a/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs b/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs index b56e822e92..839f7b5ad7 100644 --- a/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/Factories/UserFactory.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Dtos; @@ -8,7 +9,7 @@ namespace Umbraco.Core.Persistence.Factories { internal static class UserFactory { - public static IUser BuildEntity(IGlobalSettings globalSettings, UserDto dto) + public static IUser BuildEntity(GlobalSettings globalSettings, UserDto dto) { var guidId = dto.Id.ToGuid(); diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/LanguageRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/LanguageRepository.cs index 9b6df8d825..fd791fe01f 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/LanguageRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/LanguageRepository.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NPoco; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence.Dtos; @@ -19,14 +21,14 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class LanguageRepository : NPocoRepositoryBase, ILanguageRepository { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly Dictionary _codeIdMap = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _idCodeMap = new Dictionary(); - public LanguageRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IGlobalSettings globalSettings) + public LanguageRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IOptions globalSettings) : base(scopeAccessor, cache, logger) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } protected override IRepositoryCachePolicy CreateCachePolicy() diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ScriptRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ScriptRepository.cs index 498cf51432..aae888e0c5 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ScriptRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/ScriptRepository.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; @@ -14,13 +16,13 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class ScriptRepository : FileRepository, IScriptRepository { private readonly IIOHelper _ioHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public ScriptRepository(IFileSystems fileSystems, IIOHelper ioHelper, IGlobalSettings globalSettings) + public ScriptRepository(IFileSystems fileSystems, IIOHelper ioHelper, IOptions globalSettings) : base(fileSystems.ScriptsFileSystem) { _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } #region Implementation of IRepository diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/StylesheetRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/StylesheetRepository.cs index f432d6959e..4243d534aa 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/StylesheetRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/StylesheetRepository.cs @@ -1,7 +1,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; @@ -13,13 +15,13 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class StylesheetRepository : FileRepository, IStylesheetRepository { private readonly IIOHelper _ioHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public StylesheetRepository(IFileSystems fileSystems, IIOHelper ioHelper, IGlobalSettings globalSettings) + public StylesheetRepository(IFileSystems fileSystems, IIOHelper ioHelper, IOptions globalSettings) : base(fileSystems.StylesheetsFileSystem) { _ioHelper = ioHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } #region Overrides of FileRepository diff --git a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs index 1a8cde3ff6..4848ed42a3 100644 --- a/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Infrastructure/Persistence/Repositories/Implement/UserRepository.cs @@ -4,9 +4,11 @@ using System.Linq; using System.Linq.Expressions; using System.Text; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NPoco; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Dtos; @@ -24,8 +26,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class UserRepository : NPocoRepositoryBase, IUserRepository { private readonly IMapperCollection _mapperCollection; - private readonly IGlobalSettings _globalSettings; - private readonly IUserPasswordConfiguration _passwordConfiguration; + private readonly GlobalSettings _globalSettings; + private readonly UserPasswordConfigurationSettings _passwordConfiguration; private readonly IJsonSerializer _jsonSerializer; private string _passwordConfigJson; private bool _passwordConfigInitialized; @@ -40,12 +42,19 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read. /// /// - public UserRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger, IMapperCollection mapperCollection, IGlobalSettings globalSettings, IUserPasswordConfiguration passwordConfiguration, IJsonSerializer jsonSerializer) + public UserRepository( + IScopeAccessor scopeAccessor, + AppCaches appCaches, + ILogger logger, + IMapperCollection mapperCollection, + IOptions globalSettings, + IOptions passwordConfiguration, + IJsonSerializer jsonSerializer) : base(scopeAccessor, appCaches, logger) { _mapperCollection = mapperCollection ?? throw new ArgumentNullException(nameof(mapperCollection)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); - _passwordConfiguration = passwordConfiguration ?? throw new ArgumentNullException(nameof(passwordConfiguration)); + _globalSettings = globalSettings.Value ?? throw new ArgumentNullException(nameof(globalSettings)); + _passwordConfiguration = passwordConfiguration.Value ?? throw new ArgumentNullException(nameof(passwordConfiguration)); _jsonSerializer = jsonSerializer; } diff --git a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs index d3c9518b18..1eaf62ebea 100644 --- a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs @@ -1,12 +1,11 @@ using System; using System.Data.Common; -using System.Data.SqlClient; using System.Threading; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using NPoco; using NPoco.FluentMappings; -using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Persistence.FaultHandling; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; @@ -28,7 +27,7 @@ namespace Umbraco.Core.Persistence internal class UmbracoDatabaseFactory : DisposableObjectSlim, IUmbracoDatabaseFactory { private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly Lazy _mappers; private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; @@ -71,8 +70,8 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . /// /// Used by core runtime. - public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, Lazy mappers,IDbProviderFactoryCreator dbProviderFactoryCreator) - : this(logger, loggerFactory, globalSettings, connectionStrings, Constants.System.UmbracoConnectionName, mappers, dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, IOptions globalSettings, IOptions connectionStrings, Lazy mappers,IDbProviderFactoryCreator dbProviderFactoryCreator) + : this(logger, loggerFactory, globalSettings.Value, connectionStrings.Value, mappers, dbProviderFactoryCreator) { } @@ -81,10 +80,8 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . ///
/// Used by the other ctor and in tests. - public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, string connectionStringName, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator) { - if (connectionStringName == null) throw new ArgumentNullException(nameof(connectionStringName)); - if (string.IsNullOrWhiteSpace(connectionStringName)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(connectionStringName)); _globalSettings = globalSettings; _mappers = mappers ?? throw new ArgumentNullException(nameof(mappers)); @@ -92,7 +89,7 @@ namespace Umbraco.Core.Persistence _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _loggerFactory = loggerFactory; - var settings = connectionStrings[connectionStringName]; + var settings = connectionStrings.UmbracoConnectionString; if (settings == null) { diff --git a/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyEditor.cs index 698fcb10b3..d4c5130b21 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyEditor.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -22,17 +24,24 @@ namespace Umbraco.Web.PropertyEditors public class FileUploadPropertyEditor : DataEditor, IMediaUrlGenerator { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly UploadAutoFillProperties _uploadAutoFillProperties; private readonly IDataTypeService _dataTypeService; private readonly ILocalizationService _localizationService; private readonly ILocalizedTextService _localizedTextService; - public FileUploadPropertyEditor(ILogger logger, IMediaFileSystem mediaFileSystem, IContentSettings contentSettings, IDataTypeService dataTypeService, ILocalizationService localizationService, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper) + public FileUploadPropertyEditor( + ILogger logger, + IMediaFileSystem mediaFileSystem, + IOptions contentSettings, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper) : base(logger, dataTypeService, localizationService, localizedTextService, shortStringHelper) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _dataTypeService = dataTypeService; _localizationService = localizationService; _localizedTextService = localizedTextService; @@ -45,8 +54,8 @@ namespace Umbraco.Web.PropertyEditors /// The corresponding property value editor. protected override IDataValueEditor CreateValueEditor() { - var editor = new FileUploadPropertyValueEditor(Attribute, _mediaFileSystem, _dataTypeService, _localizationService, _localizedTextService, ShortStringHelper, _contentSettings); - editor.Validators.Add(new UploadFileTypeValidator(_localizedTextService, _contentSettings)); + var editor = new FileUploadPropertyValueEditor(Attribute, _mediaFileSystem, _dataTypeService, _localizationService, _localizedTextService, ShortStringHelper, Options.Create(_contentSettings)); + editor.Validators.Add(new UploadFileTypeValidator(_localizedTextService, Options.Create(_contentSettings))); return editor; } diff --git a/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyValueEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyValueEditor.cs index e45896551c..db675e2e42 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyValueEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/FileUploadPropertyValueEditor.cs @@ -1,7 +1,8 @@ using System; using System.IO; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; @@ -16,13 +17,20 @@ namespace Umbraco.Web.PropertyEditors internal class FileUploadPropertyValueEditor : DataValueEditor { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; - public FileUploadPropertyValueEditor(DataEditorAttribute attribute, IMediaFileSystem mediaFileSystem, IDataTypeService dataTypeService, ILocalizationService localizationService, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper, IContentSettings contentSettings) + public FileUploadPropertyValueEditor( + DataEditorAttribute attribute, + IMediaFileSystem mediaFileSystem, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + IOptions contentSettings) : base(dataTypeService, localizationService, localizedTextService, shortStringHelper, attribute) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); } /// diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs index f2e231c390..a0bd50b3ec 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyEditor.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -29,7 +31,7 @@ namespace Umbraco.Web.PropertyEditors public class ImageCropperPropertyEditor : DataEditor, IMediaUrlGenerator { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IDataTypeService _dataTypeService; private readonly ILocalizationService _localizationService; private readonly IIOHelper _ioHelper; @@ -38,17 +40,25 @@ namespace Umbraco.Web.PropertyEditors /// /// Initializes a new instance of the class. /// - public ImageCropperPropertyEditor(ILogger logger, IMediaFileSystem mediaFileSystem, IContentSettings contentSettings, IDataTypeService dataTypeService, ILocalizationService localizationService, IIOHelper ioHelper, IShortStringHelper shortStringHelper, ILocalizedTextService localizedTextService) - : base(logger, dataTypeService, localizationService, localizedTextService,shortStringHelper) + public ImageCropperPropertyEditor( + ILogger logger, + IMediaFileSystem mediaFileSystem, + IOptions contentSettings, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + IIOHelper ioHelper, + IShortStringHelper shortStringHelper, + ILocalizedTextService localizedTextService) + : base(logger, dataTypeService, localizationService, localizedTextService, shortStringHelper) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _dataTypeService = dataTypeService; _localizationService = localizationService; _ioHelper = ioHelper; // TODO: inject? - _autoFillProperties = new UploadAutoFillProperties(_mediaFileSystem, logger, _contentSettings); + _autoFillProperties = new UploadAutoFillProperties(_mediaFileSystem, logger, contentSettings); } public bool TryGetMediaPath(string alias, object value, out string mediaPath) diff --git a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs index e634d2630d..0ab2ae0287 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/ImageCropperPropertyValueEditor.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -22,9 +22,17 @@ namespace Umbraco.Web.PropertyEditors { private readonly ILogger _logger; private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; - public ImageCropperPropertyValueEditor(DataEditorAttribute attribute, ILogger logger, IMediaFileSystem mediaFileSystem, IDataTypeService dataTypeService, ILocalizationService localizationService, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper, IContentSettings contentSettings) + public ImageCropperPropertyValueEditor( + DataEditorAttribute attribute, + ILogger logger, + IMediaFileSystem mediaFileSystem, + IDataTypeService dataTypeService, + ILocalizationService localizationService, + ILocalizedTextService localizedTextService, + IShortStringHelper shortStringHelper, + ContentSettings contentSettings) : base(dataTypeService, localizationService, localizedTextService, shortStringHelper, attribute) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); diff --git a/src/Umbraco.Infrastructure/PropertyEditors/UploadFileTypeValidator.cs b/src/Umbraco.Infrastructure/PropertyEditors/UploadFileTypeValidator.cs index b64c52648a..d3e1e7aabe 100644 --- a/src/Umbraco.Infrastructure/PropertyEditors/UploadFileTypeValidator.cs +++ b/src/Umbraco.Infrastructure/PropertyEditors/UploadFileTypeValidator.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; -using Umbraco.Composing; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; @@ -16,12 +15,12 @@ namespace Umbraco.Web.PropertyEditors internal class UploadFileTypeValidator : IValueValidator { private readonly ILocalizedTextService _localizedTextService; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; - public UploadFileTypeValidator(ILocalizedTextService localizedTextService, IContentSettings contentSettings) + public UploadFileTypeValidator(ILocalizedTextService localizedTextService, IOptions contentSettings) { _localizedTextService = localizedTextService; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; } public IEnumerable Validate(object value, string valueType, object dataTypeConfiguration) @@ -55,7 +54,7 @@ namespace Umbraco.Web.PropertyEditors } } - internal static bool IsValidFileExtension(string fileName, IContentSettings contentSettings) + internal static bool IsValidFileExtension(string fileName, ContentSettings contentSettings) { if (fileName.IndexOf('.') <= 0) return false; var extension = fileName.GetFileExtension().TrimStart("."); diff --git a/src/Umbraco.Infrastructure/Routing/ContentFinderByConfigured404.cs b/src/Umbraco.Infrastructure/Routing/ContentFinderByConfigured404.cs index e1209bafdd..d5565719eb 100644 --- a/src/Umbraco.Infrastructure/Routing/ContentFinderByConfigured404.cs +++ b/src/Umbraco.Infrastructure/Routing/ContentFinderByConfigured404.cs @@ -1,8 +1,9 @@ -using Examine; using System.Globalization; using System.Linq; +using Examine; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -16,14 +17,18 @@ namespace Umbraco.Web.Routing { private readonly ILogger _logger; private readonly IEntityService _entityService; - private readonly IContentSettings _contentConfigSettings; + private readonly ContentSettings _contentSettings; private readonly IExamineManager _examineManager; - public ContentFinderByConfigured404(ILogger logger, IEntityService entityService, IContentSettings contentConfigSettings, IExamineManager examineManager) + public ContentFinderByConfigured404( + ILogger logger, + IEntityService entityService, + IOptions contentConfigSettings, + IExamineManager examineManager) { _logger = logger; _entityService = entityService; - _contentConfigSettings = contentConfigSettings; + _contentSettings = contentConfigSettings.Value; _examineManager = examineManager; } @@ -63,7 +68,7 @@ namespace Umbraco.Web.Routing } var error404 = NotFoundHandlerHelper.GetCurrentNotFoundPageId( - _contentConfigSettings.Error404Collection.ToArray(), + _contentSettings.Error404Collection.ToArray(), _entityService, new PublishedContentQuery(frequest.UmbracoContext.PublishedSnapshot, frequest.UmbracoContext.VariationContextAccessor, _examineManager), errorCulture); diff --git a/src/Umbraco.Infrastructure/Routing/NotFoundHandlerHelper.cs b/src/Umbraco.Infrastructure/Routing/NotFoundHandlerHelper.cs index 4412a40e59..6137803c20 100644 --- a/src/Umbraco.Infrastructure/Routing/NotFoundHandlerHelper.cs +++ b/src/Umbraco.Infrastructure/Routing/NotFoundHandlerHelper.cs @@ -4,6 +4,7 @@ using System.Linq; using Microsoft.Extensions.Logging; using Umbraco.Composing; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -28,7 +29,7 @@ namespace Umbraco.Web.Routing /// /// internal static int? GetCurrentNotFoundPageId( - IContentErrorPage[] error404Collection, + ContentErrorPage[] error404Collection, string requestServerName, IEntityService entityService, IPublishedContentQuery publishedContentQuery, @@ -38,7 +39,7 @@ namespace Umbraco.Web.Routing } internal static int? GetCurrentNotFoundPageId( - IContentErrorPage[] error404Collection, + ContentErrorPage[] error404Collection, IEntityService entityService, IPublishedContentQuery publishedContentQuery, CultureInfo errorCulture) @@ -67,7 +68,7 @@ namespace Umbraco.Web.Routing /// /// /// - internal static int? GetContentIdFromErrorPageConfig(IContentErrorPage errorPage, IEntityService entityService, IPublishedContentQuery publishedContentQuery) + internal static int? GetContentIdFromErrorPageConfig(ContentErrorPage errorPage, IEntityService entityService, IPublishedContentQuery publishedContentQuery) { if (errorPage.HasContentId) return errorPage.ContentId; diff --git a/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs b/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs index 84f0ccdabd..107e224486 100644 --- a/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs +++ b/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.Models; @@ -24,15 +26,14 @@ namespace Umbraco.Web.Routing { private const string _eventStateKey = "Umbraco.Web.Redirects.RedirectTrackingEventHandler"; - - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; private readonly IRedirectUrlService _redirectUrlService; private readonly IVariationContextAccessor _variationContextAccessor; - public RedirectTrackingComponent(IWebRoutingSettings webRoutingSettings, IPublishedSnapshotAccessor publishedSnapshotAccessor, IRedirectUrlService redirectUrlService, IVariationContextAccessor variationContextAccessor) + public RedirectTrackingComponent(IOptions webRoutingSettings, IPublishedSnapshotAccessor publishedSnapshotAccessor, IRedirectUrlService redirectUrlService, IVariationContextAccessor variationContextAccessor) { - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; _publishedSnapshotAccessor = publishedSnapshotAccessor; _redirectUrlService = redirectUrlService; _variationContextAccessor = variationContextAccessor; diff --git a/src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs b/src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs index 1432e6b7f2..a473511e56 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreInitialComponent.cs @@ -1,5 +1,6 @@ -using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; namespace Umbraco.Core.Runtime @@ -7,12 +8,12 @@ namespace Umbraco.Core.Runtime public class CoreInitialComponent : IComponent { private readonly IIOHelper _ioHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public CoreInitialComponent(IIOHelper ioHelper, IGlobalSettings globalSettings) + public CoreInitialComponent(IIOHelper ioHelper, IOptions globalSettings) { _ioHelper = ioHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public void Initialize() diff --git a/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs b/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs index 0fd174ac42..8471b98ce0 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs @@ -55,6 +55,8 @@ using Umbraco.Web.Templates; using Umbraco.Web.Trees; using IntegerValidator = Umbraco.Core.PropertyEditors.Validators.IntegerValidator; using TextStringValueConverter = Umbraco.Core.PropertyEditors.ValueConverters.TextStringValueConverter; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Core.Runtime { @@ -124,7 +126,7 @@ namespace Umbraco.Core.Runtime // register a server registrar, by default it's the db registrar composition.RegisterUnique(f => { - var globalSettings = f.GetInstance(); + var globalSettings = f.GetInstance>().Value; // TODO: we still register the full IServerMessenger because // even on 1 single server we can have 2 concurrent app domains @@ -164,7 +166,7 @@ namespace Umbraco.Core.Runtime composition.RegisterUnique(); composition.RegisterUnique(factory - => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(factory.GetInstance()))); + => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(factory.GetInstance>().Value))); composition.UrlSegmentProviders() .Append(); diff --git a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs index 45a6dc6397..b1411dc383 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs @@ -3,9 +3,11 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Exceptions; using Umbraco.Core.Hosting; @@ -29,11 +31,12 @@ namespace Umbraco.Core.Runtime // runtime state, this instance will get replaced again once the essential services are available to run the check private RuntimeState _state = RuntimeState.Booting(); private readonly IUmbracoBootPermissionChecker _umbracoBootPermissionChecker; - private readonly IGlobalSettings _globalSettings; - private readonly IConnectionStrings _connectionStrings; + private readonly GlobalSettings _globalSettings; + private readonly ConnectionStrings _connectionStrings; public CoreRuntime( - Configs configs, + GlobalSettings globalSettings, + ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, @@ -47,10 +50,12 @@ namespace Umbraco.Core.Runtime ITypeFinder typeFinder, AppCaches appCaches) { + _globalSettings = globalSettings; + _connectionStrings = connectionStrings; + IOHelper = ioHelper; - Configs = configs; AppCaches = appCaches; - UmbracoVersion = umbracoVersion ; + UmbracoVersion = umbracoVersion; Profiler = profiler; HostingEnvironment = hostingEnvironment; BackOfficeInfo = backOfficeInfo; @@ -63,8 +68,8 @@ namespace Umbraco.Core.Runtime MainDom = mainDom; TypeFinder = typeFinder; - _globalSettings = Configs.Global(); - _connectionStrings = configs.ConnectionStrings(); + _globalSettings = globalSettings; + _connectionStrings = connectionStrings; } @@ -98,8 +103,8 @@ namespace Umbraco.Core.Runtime /// Gets the /// protected IIOHelper IOHelper { get; } + protected IHostingEnvironment HostingEnvironment { get; } - public Configs Configs { get; } public AppCaches AppCaches { get; } public IUmbracoVersion UmbracoVersion { get; } @@ -174,10 +179,10 @@ namespace Umbraco.Core.Runtime var typeLoader = new TypeLoader(TypeFinder, AppCaches.RuntimeCache, new DirectoryInfo(HostingEnvironment.LocalTempPath), RuntimeLoggerFactory.CreateLogger("TypeLoader"), ProfilingLogger); // re-create the state object with the essential services - _state = new RuntimeState(Configs.Global(), UmbracoVersion, databaseFactory, RuntimeLoggerFactory.CreateLogger()); + _state = new RuntimeState(_globalSettings, UmbracoVersion, databaseFactory, RuntimeLoggerFactory.CreateLogger()); // create the composition - composition = new Composition(register, typeLoader, ProfilingLogger, _state, Configs, IOHelper, AppCaches); + composition = new Composition(register, typeLoader, ProfilingLogger, _state, IOHelper, AppCaches); composition.RegisterEssentials(Logger, Profiler, ProfilingLogger, MainDom, AppCaches, databaseFactory, typeLoader, _state, TypeFinder, IOHelper, UmbracoVersion, DbProviderFactoryCreator, HostingEnvironment, BackOfficeInfo); @@ -385,7 +390,7 @@ namespace Umbraco.Core.Runtime /// /// This is strictly internal, for tests only. protected internal virtual IUmbracoDatabaseFactory CreateDatabaseFactory() - => new UmbracoDatabaseFactory(RuntimeLoggerFactory.CreateLogger(), RuntimeLoggerFactory, _globalSettings, _connectionStrings, new Lazy(() => _factory.GetInstance()), DbProviderFactoryCreator); + => new UmbracoDatabaseFactory(RuntimeLoggerFactory.CreateLogger(), RuntimeLoggerFactory, Options.Create(_globalSettings), Options.Create(_connectionStrings), new Lazy(() => _factory.GetInstance()), DbProviderFactoryCreator); #endregion diff --git a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs index b4385654c9..0f29dfe36c 100644 --- a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; @@ -31,7 +32,7 @@ namespace Umbraco.Core.Runtime private bool _errorDuringAcquiring; private object _locker = new object(); - public SqlMainDomLock(ILogger logger, ILoggerFactory loggerFactory, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment) + public SqlMainDomLock(ILogger logger, ILoggerFactory loggerFactory, GlobalSettings globalSettings, ConnectionStrings connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator, IHostingEnvironment hostingEnvironment) { // unique id for our appdomain, this is more unique than the appdomain id which is just an INT counter to its safer _lockId = Guid.NewGuid().ToString(); @@ -41,7 +42,6 @@ namespace Umbraco.Core.Runtime loggerFactory, globalSettings, connectionStrings, - Constants.System.UmbracoConnectionName, new Lazy(() => new MapperCollection(Enumerable.Empty())), dbProviderFactoryCreator); diff --git a/src/Umbraco.Infrastructure/RuntimeState.cs b/src/Umbraco.Infrastructure/RuntimeState.cs index 6adb9b852d..cb2358d083 100644 --- a/src/Umbraco.Infrastructure/RuntimeState.cs +++ b/src/Umbraco.Infrastructure/RuntimeState.cs @@ -3,6 +3,7 @@ using System.Threading; using Semver; using Microsoft.Extensions.Logging; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Exceptions; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence; @@ -14,7 +15,7 @@ namespace Umbraco.Core /// public class RuntimeState : IRuntimeState { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IUmbracoVersion _umbracoVersion; private readonly IUmbracoDatabaseFactory _databaseFactory; private readonly ILogger _logger; @@ -31,7 +32,7 @@ namespace Umbraco.Core /// /// Initializes a new instance of the class. /// - public RuntimeState(IGlobalSettings globalSettings, IUmbracoVersion umbracoVersion, IUmbracoDatabaseFactory databaseFactory, ILogger logger) + public RuntimeState(GlobalSettings globalSettings, IUmbracoVersion umbracoVersion, IUmbracoDatabaseFactory databaseFactory, ILogger logger) { _globalSettings = globalSettings; _umbracoVersion = umbracoVersion; @@ -161,7 +162,7 @@ namespace Umbraco.Core private bool EnsureUmbracoUpgradeState(IUmbracoDatabaseFactory databaseFactory, ILogger logger) { - var upgrader = new Upgrader(new UmbracoPlan(_umbracoVersion, _globalSettings)); + var upgrader = new Upgrader(new UmbracoPlan(_umbracoVersion)); var stateValueKey = upgrader.StateValueKey; // no scope, no service - just directly accessing the database diff --git a/src/Umbraco.Infrastructure/Scheduling/HealthCheckNotifier.cs b/src/Umbraco.Infrastructure/Scheduling/HealthCheckNotifier.cs index 40d6f4eb28..8ed834dd4c 100644 --- a/src/Umbraco.Infrastructure/Scheduling/HealthCheckNotifier.cs +++ b/src/Umbraco.Infrastructure/Scheduling/HealthCheckNotifier.cs @@ -2,7 +2,7 @@ using System.Threading; using System.Threading.Tasks; using Umbraco.Core; -using Umbraco.Core.Configuration.HealthChecks; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Scoping; using Umbraco.Core.Sync; @@ -20,7 +20,7 @@ namespace Umbraco.Web.Scheduling private readonly IScopeProvider _scopeProvider; private readonly IProfilingLogger _pLogger; private readonly Microsoft.Extensions.Logging.ILogger _logger; - private readonly IHealthChecksSettings _healthChecksSettingsConfig; + private readonly HealthChecksSettings _healthChecksSettings; private readonly IServerRegistrar _serverRegistrar; private readonly IRuntimeState _runtimeState; @@ -33,7 +33,7 @@ namespace Umbraco.Web.Scheduling IMainDom mainDom, IProfilingLogger pLogger, Microsoft.Extensions.Logging.ILogger logger, - IHealthChecksSettings healthChecksSettingsConfig, + HealthChecksSettings healthChecksSettings, IServerRegistrar serverRegistrar, IRuntimeState runtimeState, IScopeProvider scopeProvider) @@ -46,7 +46,7 @@ namespace Umbraco.Web.Scheduling _runtimeState = runtimeState; _pLogger = pLogger; _logger = logger; - _healthChecksSettingsConfig = healthChecksSettingsConfig; + _healthChecksSettings = healthChecksSettings; _serverRegistrar = serverRegistrar; _runtimeState = runtimeState; } @@ -79,7 +79,7 @@ namespace Umbraco.Web.Scheduling using (var scope = _scopeProvider.CreateScope()) using (_pLogger.DebugDuration("Health checks executing", "Health checks complete")) { - var healthCheckConfig = _healthChecksSettingsConfig; + var healthCheckConfig = _healthChecksSettings; // Don't notify for any checks that are disabled, nor for any disabled // just for notifications diff --git a/src/Umbraco.Infrastructure/Scheduling/LogScrubber.cs b/src/Umbraco.Infrastructure/Scheduling/LogScrubber.cs index 916309a5db..7fd8e99a4a 100644 --- a/src/Umbraco.Infrastructure/Scheduling/LogScrubber.cs +++ b/src/Umbraco.Infrastructure/Scheduling/LogScrubber.cs @@ -1,5 +1,7 @@ using System; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Scoping; @@ -10,32 +12,31 @@ using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Umbraco.Web.Scheduling { - public class LogScrubber : RecurringTaskBase { private readonly IMainDom _mainDom; private readonly IServerRegistrar _serverRegistrar; private readonly IAuditService _auditService; - private readonly ILoggingSettings _settings; + private readonly LoggingSettings _settings; private readonly IProfilingLogger _pLogger; private readonly Microsoft.Extensions.Logging.ILogger _logger; private readonly IScopeProvider _scopeProvider; public LogScrubber(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - IMainDom mainDom, IServerRegistrar serverRegistrar, IAuditService auditService, ILoggingSettings settings, IScopeProvider scopeProvider, IProfilingLogger pLogger, Microsoft.Extensions.Logging.ILogger logger) + IMainDom mainDom, IServerRegistrar serverRegistrar, IAuditService auditService, IOptions settings, IScopeProvider scopeProvider, IProfilingLogger pLogger, Microsoft.Extensions.Logging.ILogger logger) : base(runner, delayMilliseconds, periodMilliseconds) { _mainDom = mainDom; _serverRegistrar = serverRegistrar; _auditService = auditService; - _settings = settings; + _settings = settings.Value; _scopeProvider = scopeProvider; _pLogger = pLogger; _logger = logger; } // maximum age, in minutes - private int GetLogScrubbingMaximumAge(ILoggingSettings settings) + private int GetLogScrubbingMaximumAge(LoggingSettings settings) { var maximumAge = 24 * 60; // 24 hours, in minutes try diff --git a/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs index 126f5aa179..eea906b743 100644 --- a/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs +++ b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs @@ -4,12 +4,12 @@ using System.IO; using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration.HealthChecks; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -40,11 +40,11 @@ namespace Umbraco.Web.Scheduling private readonly HealthCheckCollection _healthChecks; private readonly HealthCheckNotificationMethodCollection _notifications; private readonly IUmbracoContextFactory _umbracoContextFactory; - private readonly IHealthChecksSettings _healthChecksSettingsConfig; + private readonly HealthChecksSettings _healthChecksSettings; private readonly IServerMessenger _serverMessenger; private readonly IRequestAccessor _requestAccessor; - private readonly ILoggingSettings _loggingSettings; - private readonly IKeepAliveSettings _keepAliveSettings; + private readonly LoggingSettings _loggingSettings; + private readonly KeepAliveSettings _keepAliveSettings; private readonly IHostingEnvironment _hostingEnvironment; private BackgroundTaskRunner _keepAliveRunner; @@ -61,9 +61,9 @@ namespace Umbraco.Web.Scheduling IContentService contentService, IAuditService auditService, HealthCheckCollection healthChecks, HealthCheckNotificationMethodCollection notifications, IScopeProvider scopeProvider, IUmbracoContextFactory umbracoContextFactory, IProfilingLogger pLogger, Core.Logging.ILogger logger, ILoggerFactory loggerFactory, - IApplicationShutdownRegistry applicationShutdownRegistry, IHealthChecksSettings healthChecksSettingsConfig, + IApplicationShutdownRegistry applicationShutdownRegistry, IOptions healthChecksSettings, IServerMessenger serverMessenger, IRequestAccessor requestAccessor, - ILoggingSettings loggingSettings, IKeepAliveSettings keepAliveSettings, + IOptions loggingSettings, IOptions keepAliveSettings, IHostingEnvironment hostingEnvironment) { _runtime = runtime; @@ -80,11 +80,11 @@ namespace Umbraco.Web.Scheduling _healthChecks = healthChecks; _notifications = notifications; - _healthChecksSettingsConfig = healthChecksSettingsConfig ?? throw new ArgumentNullException(nameof(healthChecksSettingsConfig)); + _healthChecksSettings = healthChecksSettings.Value ?? throw new ArgumentNullException(nameof(healthChecksSettings)); _serverMessenger = serverMessenger; _requestAccessor = requestAccessor; - _loggingSettings = loggingSettings; - _keepAliveSettings = keepAliveSettings; + _loggingSettings = loggingSettings.Value; + _keepAliveSettings = keepAliveSettings.Value; _hostingEnvironment = hostingEnvironment; } @@ -136,7 +136,7 @@ namespace Umbraco.Web.Scheduling tasks.Add(RegisterLogScrubber(_loggingSettings)); tasks.Add(RegisterTempFileCleanup()); - var healthCheckConfig = _healthChecksSettingsConfig; + var healthCheckConfig = _healthChecksSettings; if (healthCheckConfig.NotificationSettings.Enabled) tasks.Add(RegisterHealthCheckNotifier(healthCheckConfig, _healthChecks, _notifications, _pLogger)); @@ -144,11 +144,11 @@ namespace Umbraco.Web.Scheduling }); } - private IBackgroundTask RegisterKeepAlive(IKeepAliveSettings keepAliveSettings) + private IBackgroundTask RegisterKeepAlive(KeepAliveSettings keepAliveSettings) { // ping/keepalive // on all servers - var task = new KeepAlive(_keepAliveRunner, DefaultDelayMilliseconds, FiveMinuteMilliseconds, _requestAccessor, _mainDom, keepAliveSettings, _loggerFactory.CreateLogger(), _pLogger, _serverRegistrar); + var task = new KeepAlive(_keepAliveRunner, DefaultDelayMilliseconds, FiveMinuteMilliseconds, _requestAccessor, _mainDom, Options.Create(keepAliveSettings), _loggerFactory.CreateLogger(), _pLogger, _serverRegistrar); _keepAliveRunner.TryAdd(task); return task; } @@ -162,7 +162,7 @@ namespace Umbraco.Web.Scheduling return task; } - private IBackgroundTask RegisterHealthCheckNotifier(IHealthChecksSettings healthCheckSettingsConfig, + private IBackgroundTask RegisterHealthCheckNotifier(HealthChecksSettings healthCheckSettingsConfig, HealthCheckCollection healthChecks, HealthCheckNotificationMethodCollection notifications, IProfilingLogger logger) { @@ -183,16 +183,16 @@ namespace Umbraco.Web.Scheduling } var periodInMilliseconds = healthCheckSettingsConfig.NotificationSettings.PeriodInHours * 60 * 60 * 1000; - var task = new HealthCheckNotifier(_healthCheckRunner, delayInMilliseconds, periodInMilliseconds, healthChecks, notifications, _mainDom, logger, _loggerFactory.CreateLogger(), _healthChecksSettingsConfig, _serverRegistrar, _runtime, _scopeProvider); + var task = new HealthCheckNotifier(_healthCheckRunner, delayInMilliseconds, periodInMilliseconds, healthChecks, notifications, _mainDom, logger, _loggerFactory.CreateLogger(), _healthChecksSettings, _serverRegistrar, _runtime, _scopeProvider); _healthCheckRunner.TryAdd(task); return task; } - private IBackgroundTask RegisterLogScrubber(ILoggingSettings settings) + private IBackgroundTask RegisterLogScrubber(LoggingSettings settings) { // log scrubbing // install on all, will only run on non-replica servers - var task = new LogScrubber(_scrubberRunner, DefaultDelayMilliseconds, LogScrubber.GetLogScrubbingInterval(), _mainDom, _serverRegistrar, _auditService, settings, _scopeProvider, _pLogger, _loggerFactory.CreateLogger()); + var task = new LogScrubber(_scrubberRunner, DefaultDelayMilliseconds, LogScrubber.GetLogScrubbingInterval(), _mainDom, _serverRegistrar, _auditService, Options.Create(settings), _scopeProvider, _pLogger, _loggerFactory.CreateLogger()); _scrubberRunner.TryAdd(task); return task; } diff --git a/src/Umbraco.Infrastructure/Scoping/Scope.cs b/src/Umbraco.Infrastructure/Scoping/Scope.cs index d22e6b0de8..87986a6318 100644 --- a/src/Umbraco.Infrastructure/Scoping/Scope.cs +++ b/src/Umbraco.Infrastructure/Scoping/Scope.cs @@ -3,10 +3,10 @@ using System.Data; using Microsoft.Extensions.Logging; using Umbraco.Core.Cache; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Persistence; +using CoreDebugSettings = Umbraco.Core.Configuration.Models.CoreDebugSettings; namespace Umbraco.Core.Scoping { @@ -17,7 +17,7 @@ namespace Umbraco.Core.Scoping internal class Scope : IScope { private readonly ScopeProvider _scopeProvider; - private readonly ICoreDebugSettings _coreDebugSettings; + private readonly CoreDebugSettings _coreDebugSettings; private readonly IMediaFileSystem _mediaFileSystem; private readonly ILogger _logger; private readonly ITypeFinder _typeFinder; @@ -39,7 +39,7 @@ namespace Umbraco.Core.Scoping // initializes a new scope private Scope(ScopeProvider scopeProvider, - ICoreDebugSettings coreDebugSettings, + CoreDebugSettings coreDebugSettings, IMediaFileSystem mediaFileSystem, ILogger logger, ITypeFinder typeFinder, FileSystems fileSystems, Scope parent, IScopeContext scopeContext, bool detachable, IsolationLevel isolationLevel = IsolationLevel.Unspecified, @@ -118,7 +118,7 @@ namespace Umbraco.Core.Scoping // initializes a new scope public Scope(ScopeProvider scopeProvider, - ICoreDebugSettings coreDebugSettings, + CoreDebugSettings coreDebugSettings, IMediaFileSystem mediaFileSystem, ILogger logger, ITypeFinder typeFinder, FileSystems fileSystems, bool detachable, IScopeContext scopeContext, IsolationLevel isolationLevel = IsolationLevel.Unspecified, @@ -132,7 +132,7 @@ namespace Umbraco.Core.Scoping // initializes a new scope in a nested scopes chain, with its parent public Scope(ScopeProvider scopeProvider, - ICoreDebugSettings coreDebugSettings, + CoreDebugSettings coreDebugSettings, IMediaFileSystem mediaFileSystem, ILogger logger, ITypeFinder typeFinder, FileSystems fileSystems, Scope parent, IsolationLevel isolationLevel = IsolationLevel.Unspecified, diff --git a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs index f11ec145e0..52c096b224 100644 --- a/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs +++ b/src/Umbraco.Infrastructure/Scoping/ScopeProvider.cs @@ -1,14 +1,13 @@ using System; -using System.Collections.Generic; using System.Data; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core.Cache; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Persistence; -using Current = Umbraco.Composing.Current; +using CoreDebugSettings = Umbraco.Core.Configuration.Models.CoreDebugSettings; #if DEBUG_SCOPES using System.Linq; @@ -27,14 +26,14 @@ namespace Umbraco.Core.Scoping private readonly ITypeFinder _typeFinder; private readonly IRequestCache _requestCache; private readonly FileSystems _fileSystems; - private readonly ICoreDebugSettings _coreDebugSettings; + private readonly CoreDebugSettings _coreDebugSettings; private readonly IMediaFileSystem _mediaFileSystem; - public ScopeProvider(IUmbracoDatabaseFactory databaseFactory, FileSystems fileSystems, ICoreDebugSettings coreDebugSettings, IMediaFileSystem mediaFileSystem, ILogger logger, ILoggerFactory loggerFactory, ITypeFinder typeFinder, IRequestCache requestCache) + public ScopeProvider(IUmbracoDatabaseFactory databaseFactory, FileSystems fileSystems, IOptions coreDebugSettings, IMediaFileSystem mediaFileSystem, ILogger logger, ILoggerFactory loggerFactory, ITypeFinder typeFinder, IRequestCache requestCache) { DatabaseFactory = databaseFactory; _fileSystems = fileSystems; - _coreDebugSettings = coreDebugSettings; + _coreDebugSettings = coreDebugSettings.Value; _mediaFileSystem = mediaFileSystem; _logger = logger; _loggerFactory = loggerFactory; diff --git a/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs b/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs index 7d3be1d52b..4fa7dad253 100644 --- a/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs +++ b/src/Umbraco.Infrastructure/Services/Implement/AuditService.cs @@ -4,7 +4,6 @@ using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; -using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; diff --git a/src/Umbraco.Infrastructure/Services/Implement/FileService.cs b/src/Umbraco.Infrastructure/Services/Implement/FileService.cs index 188fad4c7b..e82c71d1a5 100644 --- a/src/Umbraco.Infrastructure/Services/Implement/FileService.cs +++ b/src/Umbraco.Infrastructure/Services/Implement/FileService.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Microsoft.Extensions.Options; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Hosting; using Umbraco.Core.IO; @@ -29,7 +31,7 @@ namespace Umbraco.Core.Services.Implement private readonly IPartialViewMacroRepository _partialViewMacroRepository; private readonly IAuditRepository _auditRepository; private readonly IShortStringHelper _shortStringHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private const string PartialViewHeader = "@inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage"; @@ -38,7 +40,7 @@ namespace Umbraco.Core.Services.Implement public FileService(IScopeProvider uowProvider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IStylesheetRepository stylesheetRepository, IScriptRepository scriptRepository, ITemplateRepository templateRepository, IPartialViewRepository partialViewRepository, IPartialViewMacroRepository partialViewMacroRepository, - IAuditRepository auditRepository, IShortStringHelper shortStringHelper, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + IAuditRepository auditRepository, IShortStringHelper shortStringHelper, IOptions globalSettings, IHostingEnvironment hostingEnvironment) : base(uowProvider, logger, eventMessagesFactory) { _stylesheetRepository = stylesheetRepository; @@ -48,7 +50,7 @@ namespace Umbraco.Core.Services.Implement _partialViewMacroRepository = partialViewMacroRepository; _auditRepository = auditRepository; _shortStringHelper = shortStringHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs b/src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs index 5fc195e92a..f74ad6038b 100644 --- a/src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs +++ b/src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs @@ -3,12 +3,11 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Net; using System.Net.Mail; using System.Text; using System.Threading; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -26,18 +25,18 @@ namespace Umbraco.Core.Services.Implement private readonly IContentService _contentService; private readonly ILocalizationService _localizationService; private readonly INotificationsRepository _notificationsRepository; - private readonly IGlobalSettings _globalSettings; - private readonly IContentSettings _contentSettings; + private readonly GlobalSettings _globalSettings; + private readonly ContentSettings _contentSettings; private readonly IEmailSender _emailSender; private readonly ILogger _logger; private readonly IIOHelper _ioHelper; public NotificationService(IScopeProvider provider, IUserService userService, IContentService contentService, ILocalizationService localizationService, - ILogger logger, IIOHelper ioHelper, INotificationsRepository notificationsRepository, IGlobalSettings globalSettings, IContentSettings contentSettings, IEmailSender emailSender) + ILogger logger, IIOHelper ioHelper, INotificationsRepository notificationsRepository, IOptions globalSettings, IOptions contentSettings, IEmailSender emailSender) { _notificationsRepository = notificationsRepository; - _globalSettings = globalSettings; - _contentSettings = contentSettings; + _globalSettings = globalSettings.Value; + _contentSettings = contentSettings.Value; _emailSender = emailSender; _uowProvider = provider ?? throw new ArgumentNullException(nameof(provider)); _userService = userService ?? throw new ArgumentNullException(nameof(userService)); @@ -303,7 +302,7 @@ namespace Umbraco.Core.Services.Implement if (content.ContentType.VariesByNothing()) { - if (!_contentSettings.DisableHtmlEmail) + if (!_contentSettings.Notifications.DisableHtmlEmail) { //create the HTML summary for invariant content @@ -345,7 +344,7 @@ namespace Umbraco.Core.Services.Implement { //it's variant, so detect what cultures have changed - if (!_contentSettings.DisableHtmlEmail) + if (!_contentSettings.Notifications.DisableHtmlEmail) { //Create the HTML based summary (ul of culture names) @@ -406,15 +405,15 @@ namespace Umbraco.Core.Services.Implement string.Concat(siteUri.Authority, _ioHelper.ResolveUrl(_globalSettings.UmbracoPath)), summary.ToString()); - var fromMail = _contentSettings.NotificationEmailAddress ?? _globalSettings.SmtpSettings.From; + var fromMail = _contentSettings.Notifications.Email ?? _globalSettings.Smtp.From; // create the mail message - var mail = new MailMessage(fromMail, mailingUser.Email); + var mail = new MailMessage(fromMail, fromMail); // populate the message mail.Subject = createSubject((mailingUser, subjectVars)); - if (_contentSettings.DisableHtmlEmail) + if (_contentSettings.Notifications.DisableHtmlEmail) { mail.IsBodyHtml = false; mail.Body = createBody((user: mailingUser, body: bodyVars, false)); diff --git a/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs b/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs index 561b410786..238258b8c2 100644 --- a/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Infrastructure/Services/Implement/PackagingService.cs @@ -21,7 +21,6 @@ namespace Umbraco.Core.Services.Implement /// public class PackagingService : IPackagingService { - private readonly IPackageInstallation _packageInstallation; private readonly IIOHelper _ioHelper; private readonly IAuditService _auditService; diff --git a/src/Umbraco.Infrastructure/Services/Implement/UserService.cs b/src/Umbraco.Infrastructure/Services/Implement/UserService.cs index 730510fca9..9eaa85dec6 100644 --- a/src/Umbraco.Infrastructure/Services/Implement/UserService.cs +++ b/src/Umbraco.Infrastructure/Services/Implement/UserService.cs @@ -4,7 +4,9 @@ using System.Data.Common; using System.Globalization; using System.Linq; using System.Linq.Expressions; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models.Membership; @@ -22,16 +24,16 @@ namespace Umbraco.Core.Services.Implement { private readonly IUserRepository _userRepository; private readonly IUserGroupRepository _userGroupRepository; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly bool _isUpgrading; public UserService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IRuntimeState runtimeState, - IUserRepository userRepository, IUserGroupRepository userGroupRepository, IGlobalSettings globalSettings) + IUserRepository userRepository, IUserGroupRepository userGroupRepository, IOptions globalSettings) : base(provider, logger, eventMessagesFactory) { _userRepository = userRepository; _userGroupRepository = userGroupRepository; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _isUpgrading = runtimeState.Level == RuntimeLevel.Install || runtimeState.Level == RuntimeLevel.Upgrade; } diff --git a/src/Umbraco.Infrastructure/Trees/TreeNode.cs b/src/Umbraco.Infrastructure/Trees/TreeNode.cs index 1b6945bcdd..5cf1054fc8 100644 --- a/src/Umbraco.Infrastructure/Trees/TreeNode.cs +++ b/src/Umbraco.Infrastructure/Trees/TreeNode.cs @@ -4,6 +4,7 @@ using System.Runtime.Serialization; using Umbraco.Composing; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Trees @@ -113,7 +114,11 @@ namespace Umbraco.Web.Models.Trees return Current.IOHelper.ResolveUrl("~" + Icon.TrimStart('~')); //legacy icon path - var backOfficePath = Current.Configs.Global().GetUmbracoMvcArea(Current.HostingEnvironment); + + // TODO: replace this when we have something other than Current.Configs available + var backOfficePath = Current.GlobalSettings.GetUmbracoMvcArea(Current.HostingEnvironment); + + return string.Format("{0}images/umbraco/{1}", backOfficePath.EnsureEndsWith("/"), Icon); } } diff --git a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj index a306ebe581..2b663431ae 100644 --- a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj +++ b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj @@ -41,7 +41,7 @@ - + diff --git a/src/Umbraco.Infrastructure/Users/EmailSender.cs b/src/Umbraco.Infrastructure/Users/EmailSender.cs index 9a2f425021..c45a9af0d3 100644 --- a/src/Umbraco.Infrastructure/Users/EmailSender.cs +++ b/src/Umbraco.Infrastructure/Users/EmailSender.cs @@ -2,9 +2,11 @@ using System.Linq; using System.Net.Mail; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using MimeKit; using MimeKit.Text; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using SmtpClient = MailKit.Net.Smtp.SmtpClient; @@ -17,16 +19,16 @@ namespace Umbraco.Core { // TODO: This should encapsulate a BackgroundTaskRunner with a queue to send these emails! - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly bool _enableEvents; - public EmailSender(IGlobalSettings globalSettings) : this(globalSettings, false) + public EmailSender(IOptions globalSettings) : this(globalSettings, false) { } - public EmailSender(IGlobalSettings globalSettings, bool enableEvents) + public EmailSender(IOptions globalSettings, bool enableEvents) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _enableEvents = enableEvents; _smtpConfigured = new Lazy(() => _globalSettings.IsSmtpServerConfigured); @@ -49,12 +51,12 @@ namespace Umbraco.Core using (var client = new SmtpClient()) { - client.Connect(_globalSettings.SmtpSettings.Host, _globalSettings.SmtpSettings.Port); + client.Connect(_globalSettings.Smtp.Host, _globalSettings.Smtp.Port); - if (!(_globalSettings.SmtpSettings.Username is null && - _globalSettings.SmtpSettings.Password is null)) + if (!(_globalSettings.Smtp.Username is null && + _globalSettings.Smtp.Password is null)) { - client.Authenticate(_globalSettings.SmtpSettings.Username, _globalSettings.SmtpSettings.Password); + client.Authenticate(_globalSettings.Smtp.Username, _globalSettings.Smtp.Password); } client.Send(ConstructEmailMessage(message)); @@ -78,16 +80,16 @@ namespace Umbraco.Core { using (var client = new SmtpClient()) { - await client.ConnectAsync(_globalSettings.SmtpSettings.Host, _globalSettings.SmtpSettings.Port); + await client.ConnectAsync(_globalSettings.Smtp.Host, _globalSettings.Smtp.Port); - if (!(_globalSettings.SmtpSettings.Username is null && - _globalSettings.SmtpSettings.Password is null)) + if (!(_globalSettings.Smtp.Username is null && + _globalSettings.Smtp.Password is null)) { - await client.AuthenticateAsync(_globalSettings.SmtpSettings.Username, _globalSettings.SmtpSettings.Password); + await client.AuthenticateAsync(_globalSettings.Smtp.Username, _globalSettings.Smtp.Password); } var mailMessage = ConstructEmailMessage(message); - if (_globalSettings.SmtpSettings.DeliveryMethod == SmtpDeliveryMethod.Network) + if (_globalSettings.Smtp.DeliveryMethod == SmtpDeliveryMethod.Network) { await client.SendAsync(mailMessage); } @@ -107,7 +109,7 @@ namespace Umbraco.Core /// /// We assume this is possible if either an event handler is registered or an smtp server is configured /// - public static bool CanSendRequiredEmail(IGlobalSettings globalSettings) => EventHandlerRegistered || globalSettings.IsSmtpServerConfigured; + public static bool CanSendRequiredEmail(GlobalSettings globalSettings) => EventHandlerRegistered || globalSettings.IsSmtpServerConfigured; /// /// returns true if an event handler has been registered @@ -132,7 +134,7 @@ namespace Umbraco.Core { var fromEmail = mailMessage.From?.Address; if(string.IsNullOrEmpty(fromEmail)) - fromEmail = _globalSettings.SmtpSettings.From; + fromEmail = _globalSettings.Smtp.From; var messageToSend = new MimeMessage { diff --git a/src/Umbraco.Infrastructure/WebAssets/BackOfficeJavaScriptInitializer.cs b/src/Umbraco.Infrastructure/WebAssets/BackOfficeJavaScriptInitializer.cs index 18279e35ba..77db7bcbfd 100644 --- a/src/Umbraco.Infrastructure/WebAssets/BackOfficeJavaScriptInitializer.cs +++ b/src/Umbraco.Infrastructure/WebAssets/BackOfficeJavaScriptInitializer.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.RegularExpressions; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; @@ -31,7 +32,7 @@ namespace Umbraco.Web.WebAssets /// /// /// - public static string GetJavascriptInitialization(IEnumerable scripts, string angularModule, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static string GetJavascriptInitialization(IEnumerable scripts, string angularModule, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var jarray = new StringBuilder(); jarray.AppendLine("["); diff --git a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs index fcb27f7189..5e4a1e2c7a 100644 --- a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs +++ b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Manifest; @@ -25,7 +27,7 @@ namespace Umbraco.Web.WebAssets private readonly IRuntimeMinifier _runtimeMinifier; private readonly IManifestParser _parser; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly PropertyEditorCollection _propertyEditorCollection; @@ -34,13 +36,13 @@ namespace Umbraco.Web.WebAssets IManifestParser parser, PropertyEditorCollection propertyEditorCollection, IHostingEnvironment hostingEnvironment, - IGlobalSettings globalSettings) + IOptions globalSettings) { _runtimeMinifier = runtimeMinifier; _parser = parser; _propertyEditorCollection = propertyEditorCollection; _hostingEnvironment = hostingEnvironment; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public void CreateBundles() diff --git a/src/Umbraco.Infrastructure/WebAssets/RuntimeMinifierExtensions.cs b/src/Umbraco.Infrastructure/WebAssets/RuntimeMinifierExtensions.cs index 072afa5816..cc3be4d785 100644 --- a/src/Umbraco.Infrastructure/WebAssets/RuntimeMinifierExtensions.cs +++ b/src/Umbraco.Infrastructure/WebAssets/RuntimeMinifierExtensions.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.Text; using System.Threading.Tasks; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Core.WebAssets; namespace Umbraco.Web.WebAssets @@ -15,7 +13,7 @@ namespace Umbraco.Web.WebAssets /// Returns the JavaScript to load the back office's assets /// /// - public static async Task GetScriptForLoadingBackOfficeAsync(this IRuntimeMinifier minifier, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static async Task GetScriptForLoadingBackOfficeAsync(this IRuntimeMinifier minifier, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var files = await minifier.GetAssetPathsAsync(BackOfficeWebAssets.UmbracoJsBundleName); var result = BackOfficeJavaScriptInitializer.GetJavascriptInitialization(files, "umbraco", globalSettings, hostingEnvironment); diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs index 75affe09e7..5f806883f0 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs @@ -1,4 +1,5 @@ -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice @@ -10,7 +11,7 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice // ReSharper disable once UnusedMember.Global - This is typed scanned public class ContentTypeModelValidator : ContentTypeModelValidatorBase { - public ContentTypeModelValidator(IModelsBuilderConfig config) : base(config) + public ContentTypeModelValidator(IOptions config) : base(config) { } } diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs index 9c1503389e..c1684dde7a 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs @@ -1,8 +1,9 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Editors; using Umbraco.Web.Models.ContentEditing; @@ -13,9 +14,9 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice where TModel : ContentTypeSave where TProperty : PropertyTypeBasic { - private readonly IModelsBuilderConfig _config; + private readonly IOptions _config; - public ContentTypeModelValidatorBase(IModelsBuilderConfig config) + public ContentTypeModelValidatorBase(IOptions config) { _config = config; } @@ -23,7 +24,7 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice protected override IEnumerable Validate(TModel model) { //don't do anything if we're not enabled - if (!_config.Enable) yield break; + if (!_config.Value.Enable) yield break; var properties = model.Groups.SelectMany(x => x.Properties) .Where(x => x.Inherited == false) diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs index 6e22313474..a0928fafcf 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs @@ -1,18 +1,20 @@ using System.Text; +using Microsoft.Extensions.Options; using Umbraco.Configuration; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.ModelsBuilder.Embedded.BackOffice { internal class DashboardReport { - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly OutOfDateModelsStatus _outOfDateModels; private readonly ModelsGenerationError _mbErrors; - public DashboardReport(IModelsBuilderConfig config, OutOfDateModelsStatus outOfDateModels, ModelsGenerationError mbErrors) + public DashboardReport(IOptions config, OutOfDateModelsStatus outOfDateModels, ModelsGenerationError mbErrors) { - _config = config; + _config = config.Value; _outOfDateModels = outOfDateModels; _mbErrors = mbErrors; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs index fcd42908e7..b6cc135e7c 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs @@ -1,4 +1,5 @@ -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice @@ -10,7 +11,7 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice // ReSharper disable once UnusedMember.Global - This is typed scanned public class MediaTypeModelValidator : ContentTypeModelValidatorBase { - public MediaTypeModelValidator(IModelsBuilderConfig config) : base(config) + public MediaTypeModelValidator(IOptions config) : base(config) { } } diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs index 2e249eed4d..c930642155 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs @@ -1,4 +1,5 @@ -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice @@ -10,7 +11,7 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice // ReSharper disable once UnusedMember.Global - This is typed scanned public class MemberTypeModelValidator : ContentTypeModelValidatorBase { - public MemberTypeModelValidator(IModelsBuilderConfig config) : base(config) + public MemberTypeModelValidator(IOptions config) : base(config) { } } diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs index a14880686e..1339c79052 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs @@ -1,8 +1,9 @@ using System; using System.Runtime.Serialization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Configuration; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Exceptions; using Umbraco.Core.Hosting; using Umbraco.ModelsBuilder.Embedded.Building; @@ -22,17 +23,17 @@ namespace Umbraco.ModelsBuilder.Embedded.BackOffice [UmbracoApplicationAuthorize(Core.Constants.Applications.Settings)] public class ModelsBuilderDashboardController : UmbracoAuthorizedJsonController { - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly ModelsGenerator _modelGenerator; private readonly OutOfDateModelsStatus _outOfDateModels; private readonly ModelsGenerationError _mbErrors; private readonly DashboardReport _dashboardReport; private readonly IHostingEnvironment _hostingEnvironment; - public ModelsBuilderDashboardController(IModelsBuilderConfig config, ModelsGenerator modelsGenerator, OutOfDateModelsStatus outOfDateModels, ModelsGenerationError mbErrors, IHostingEnvironment hostingEnvironment) + public ModelsBuilderDashboardController(IOptions config, ModelsGenerator modelsGenerator, OutOfDateModelsStatus outOfDateModels, ModelsGenerationError mbErrors, IHostingEnvironment hostingEnvironment) { //_umbracoServices = umbracoServices; - _config = config; + _config = config.Value; _modelGenerator = modelsGenerator; _outOfDateModels = outOfDateModels; _mbErrors = mbErrors; diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs index d49b6eb0a6..4c90234fab 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.ModelsBuilder.Embedded.Building { @@ -65,7 +66,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Building /// /// The list of models to generate. /// The models namespace. - protected Builder(IModelsBuilderConfig config, IList typeModels) + protected Builder(ModelsBuilderConfig config, IList typeModels) { _typeModels = typeModels ?? throw new ArgumentNullException(nameof(typeModels)); @@ -82,7 +83,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Building protected Builder() { } - protected IModelsBuilderConfig Config { get; } + protected ModelsBuilderConfig Config { get; } /// /// Prepares generation by processing the result of code parsing. diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs index 587e1a6bc4..0348c287cd 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs @@ -1,6 +1,9 @@ using System.IO; using System.Text; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.IO; using Umbraco.Core.Hosting; namespace Umbraco.ModelsBuilder.Embedded.Building @@ -8,14 +11,14 @@ namespace Umbraco.ModelsBuilder.Embedded.Building public class ModelsGenerator { private readonly UmbracoServices _umbracoService; - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly OutOfDateModelsStatus _outOfDateModels; private readonly IHostingEnvironment _hostingEnvironment; - public ModelsGenerator(UmbracoServices umbracoService, IModelsBuilderConfig config, OutOfDateModelsStatus outOfDateModels, IHostingEnvironment hostingEnvironment) + public ModelsGenerator(UmbracoServices umbracoService, IOptions config, OutOfDateModelsStatus outOfDateModels, IHostingEnvironment hostingEnvironment) { _umbracoService = umbracoService; - _config = config; + _config = config.Value; _outOfDateModels = outOfDateModels; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs index 40eb84b9d0..607aa129b1 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.ModelsBuilder.Embedded.Building { @@ -17,7 +18,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Building /// and the result of code parsing. /// /// The list of models to generate. - public TextBuilder(IModelsBuilderConfig config, IList typeModels) + public TextBuilder(ModelsBuilderConfig config, IList typeModels) : base(config, typeModels) { } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs index ae2cbf6dde..1088dfb470 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs @@ -2,9 +2,10 @@ using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Umbraco.Configuration; -using Umbraco.Core.Configuration; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; @@ -20,7 +21,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose { internal class ModelsBuilderComponent : IComponent { - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly IShortStringHelper _shortStringHelper; private readonly LiveModelsProvider _liveModelsProvider; private readonly OutOfDateModelsStatus _outOfDateModels; @@ -28,11 +29,11 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime; private readonly IUmbracoRequestLifetime _umbracoRequestLifetime; - public ModelsBuilderComponent(IModelsBuilderConfig config, IShortStringHelper shortStringHelper, + public ModelsBuilderComponent(IOptions config, IShortStringHelper shortStringHelper, LiveModelsProvider liveModelsProvider, OutOfDateModelsStatus outOfDateModels, LinkGenerator linkGenerator, IUmbracoRequestLifetime umbracoRequestLifetime, IUmbracoApplicationLifetime umbracoApplicationLifetime) { - _config = config; + _config = config.Value; _shortStringHelper = shortStringHelper; _liveModelsProvider = liveModelsProvider; _outOfDateModels = outOfDateModels; @@ -76,7 +77,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose private void InstallServerVars() { // register our url - for the backoffice api - ServerVariablesParser.Parsing += ServerVariablesParser_Parsing; + ServerVariablesParser.Parsing += ServerVariablesParser_Parsing; } private void ServerVariablesParser_Parsing(object sender, Dictionary serverVars) diff --git a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs index 60356f4c6c..fd5472b223 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs @@ -6,6 +6,8 @@ using Umbraco.Core.Logging; using Umbraco.Core.Composing; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded.Building; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.ModelsBuilder.Embedded.Compose { @@ -22,44 +24,43 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose composition.RegisterUnique(); composition.RegisterUnique(); - if (composition.Configs.ModelsBuilder().ModelsMode == ModelsMode.PureLive) - ComposeForLiveModels(composition); - else if (composition.Configs.ModelsBuilder().EnableFactory) - ComposeForDefaultModelsFactory(composition); - } - private void ComposeForDefaultModelsFactory(Composition composition) - { composition.RegisterUnique(factory => { - var typeLoader = factory.GetInstance(); - var publishedValueFallback = factory.GetInstance(); - var types = typeLoader - .GetTypes() // element models - .Concat(typeLoader.GetTypes()); // content models - return new PublishedModelFactory(types, publishedValueFallback); + var config = factory.GetInstance>().Value; + if (config.ModelsMode == ModelsMode.PureLive) + { + composition.RegisterUnique(); + + // the following would add @using statement in every view so user's don't + // have to do it - however, then noone understands where the @using statement + // comes from, and it cannot be avoided / removed --- DISABLED + // + /* + // no need for @using in views + // note: + // we are NOT using the in-code attribute here, config is required + // because that would require parsing the code... and what if it changes? + // we can AddGlobalImport not sure we can remove one anyways + var modelsNamespace = Configuration.Config.ModelsNamespace; + if (string.IsNullOrWhiteSpace(modelsNamespace)) + modelsNamespace = Configuration.Config.DefaultModelsNamespace; + System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(modelsNamespace); + */ + } + else if (config.EnableFactory) + { + var typeLoader = factory.GetInstance(); + var publishedValueFallback = factory.GetInstance(); + var types = typeLoader + .GetTypes() // element models + .Concat(typeLoader.GetTypes()); // content models + return new PublishedModelFactory(types, publishedValueFallback); + } + + return null; }); - } - private void ComposeForLiveModels(Composition composition) - { - composition.RegisterUnique(); - - // the following would add @using statement in every view so user's don't - // have to do it - however, then noone understands where the @using statement - // comes from, and it cannot be avoided / removed --- DISABLED - // - /* - // no need for @using in views - // note: - // we are NOT using the in-code attribute here, config is required - // because that would require parsing the code... and what if it changes? - // we can AddGlobalImport not sure we can remove one anyways - var modelsNamespace = Configuration.Config.ModelsNamespace; - if (string.IsNullOrWhiteSpace(modelsNamespace)) - modelsNamespace = Configuration.Config.DefaultModelsNamespace; - System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(modelsNamespace); - */ } } } diff --git a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs b/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs deleted file mode 100644 index d625c754c5..0000000000 --- a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Umbraco.Core.Configuration; - -namespace Umbraco.ModelsBuilder.Embedded -{ - /// - /// Provides extension methods for the class. - /// - public static class ConfigsExtensions - { - /// - /// Gets the models builder configuration. - /// - /// Getting the models builder configuration freezes its state, - /// and any attempt at modifying the configuration using the Setup method - /// will be ignored. - public static IModelsBuilderConfig ModelsBuilder(this Configs configs) - => configs.GetConfig(); - } -} diff --git a/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs b/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs index 4a514f82f5..e8bb2548ed 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs @@ -9,6 +9,8 @@ using Umbraco.Core.Hosting; using Umbraco.Core.Logging; using Umbraco.ModelsBuilder.Embedded.Building; using Umbraco.Web.Cache; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.ModelsBuilder.Embedded { @@ -18,7 +20,7 @@ namespace Umbraco.ModelsBuilder.Embedded private static Mutex _mutex; private static int _req; private readonly ILogger _logger; - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly ModelsGenerator _modelGenerator; private readonly ModelsGenerationError _mbErrors; private readonly IHostingEnvironment _hostingEnvironment; @@ -26,10 +28,10 @@ namespace Umbraco.ModelsBuilder.Embedded // we do not manage pure live here internal bool IsEnabled => _config.ModelsMode.IsLiveNotPure(); - public LiveModelsProvider(ILogger logger, IModelsBuilderConfig config, ModelsGenerator modelGenerator, ModelsGenerationError mbErrors, IHostingEnvironment hostingEnvironment) + public LiveModelsProvider(ILogger logger, IOptions config, ModelsGenerator modelGenerator, ModelsGenerationError mbErrors, IHostingEnvironment hostingEnvironment) { _logger = logger; - _config = config ?? throw new ArgumentNullException(nameof(config)); + _config = config.Value ?? throw new ArgumentNullException(nameof(config)); _modelGenerator = modelGenerator; _mbErrors = mbErrors; _hostingEnvironment = hostingEnvironment; diff --git a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs index e4b5da0a98..a5911bc9c6 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs @@ -1,20 +1,21 @@ using System; using System.IO; using System.Text; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; namespace Umbraco.ModelsBuilder.Embedded { public sealed class ModelsGenerationError { - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly IHostingEnvironment _hostingEnvironment; - public ModelsGenerationError(IModelsBuilderConfig config, IHostingEnvironment hostingEnvironment) + public ModelsGenerationError(IOptions config, IHostingEnvironment hostingEnvironment) { - _config = config; + _config = config.Value; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs index 0f034c04bc..85d08ee975 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs @@ -1,19 +1,20 @@ using System.IO; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Cache; namespace Umbraco.ModelsBuilder.Embedded { public sealed class OutOfDateModelsStatus { - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly IHostingEnvironment _hostingEnvironment; - public OutOfDateModelsStatus(IModelsBuilderConfig config, IHostingEnvironment hostingEnvironment) + public OutOfDateModelsStatus(IOptions config, IHostingEnvironment hostingEnvironment) { - _config = config; + _config = config.Value; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs index d2f846ae1b..f967060ecb 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs @@ -15,6 +15,8 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded.Building; using File = System.IO.File; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.ModelsBuilder.Embedded { @@ -37,7 +39,7 @@ namespace Umbraco.ModelsBuilder.Embedded private static readonly Regex AssemblyVersionRegex = new Regex("AssemblyVersion\\(\"[0-9]+.[0-9]+.[0-9]+.[0-9]+\"\\)", RegexOptions.Compiled); private static readonly string[] OurFiles = { "models.hash", "models.generated.cs", "all.generated.cs", "all.dll.path", "models.err", "Compiled" }; - private readonly IModelsBuilderConfig _config; + private readonly ModelsBuilderConfig _config; private readonly IHostingEnvironment _hostingEnvironment; private readonly IApplicationShutdownRegistry _hostingLifetime; private readonly ModelsGenerationError _errors; @@ -47,7 +49,7 @@ namespace Umbraco.ModelsBuilder.Embedded Lazy umbracoServices, IProfilingLogger profilingLogger, ILogger logger, - IModelsBuilderConfig config, + IOptions config, IHostingEnvironment hostingEnvironment, IApplicationShutdownRegistry hostingLifetime, IPublishedValueFallback publishedValueFallback) @@ -55,7 +57,7 @@ namespace Umbraco.ModelsBuilder.Embedded _umbracoServices = umbracoServices; _profilingLogger = profilingLogger; _logger = logger; - _config = config; + _config = config.Value; _hostingEnvironment = hostingEnvironment; _hostingLifetime = hostingLifetime; _publishedValueFallback = publishedValueFallback; diff --git a/src/Umbraco.PublishedCache.NuCache/ContentCache.cs b/src/Umbraco.PublishedCache.NuCache/ContentCache.cs index 337c61b30f..1bdb3711d1 100644 --- a/src/Umbraco.PublishedCache.NuCache/ContentCache.cs +++ b/src/Umbraco.PublishedCache.NuCache/ContentCache.cs @@ -3,9 +3,11 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml.XPath; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Core.Xml.XPath; @@ -19,7 +21,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IAppCache _snapshotCache; private readonly IAppCache _elementsCache; private readonly IDomainCache _domainCache; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IVariationContextAccessor _variationContextAccessor; #region Constructor @@ -29,14 +31,14 @@ namespace Umbraco.Web.PublishedCache.NuCache // it's too late for UmbracoContext which has captured previewDefault and stuff into these ctor vars // but, no, UmbracoContext returns snapshot.Content which comes from elements SO a resync should create a new cache - public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache, IDomainCache domainCache, IGlobalSettings globalSettings, IVariationContextAccessor variationContextAccessor) + public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache, IDomainCache domainCache, IOptions globalSettings, IVariationContextAccessor variationContextAccessor) : base(previewDefault) { _snapshot = snapshot; _snapshotCache = snapshotCache; _elementsCache = elementsCache; _domainCache = domainCache; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _variationContextAccessor = variationContextAccessor; } diff --git a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs index 00e7fd34d1..ae7393a91a 100644 --- a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs +++ b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs @@ -2,12 +2,13 @@ using CSharpTest.Net.Collections; using CSharpTest.Net.Serialization; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.PublishedCache.NuCache.DataSource { internal class BTree { - public static BPlusTree GetTree(string filepath, bool exists, INuCacheSettings settings) + public static BPlusTree GetTree(string filepath, bool exists, NuCacheSettings settings) { var keySerializer = new PrimitiveSerializer(); var valueSerializer = new ContentNodeKitSerializer(); @@ -22,7 +23,6 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource // default is 4096, min 2^9 = 512, max 2^16 = 64K FileBlockSize = GetBlockSize(settings), - //HACK: Forces FileOptions to be WriteThrough here: https://github.com/mamift/CSharpTest.Net.Collections/blob/9f93733b3af7ee0e2de353e822ff54d908209b0b/src/CSharpTest.Net.Collections/IO/TransactedCompoundFile.cs#L316-L327, // as the reflection uses otherwise will failed in .NET Core as the "_handle" field in FileStream is renamed to "_fileHandle". StoragePerformance = StoragePerformance.CommitToDisk, @@ -40,7 +40,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource return tree; } - private static int GetBlockSize(INuCacheSettings settings) + private static int GetBlockSize(NuCacheSettings settings) { var blockSize = 4096; diff --git a/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs b/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs index 335400a389..3c23e1311d 100644 --- a/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs @@ -6,12 +6,14 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using CSharpTest.Net.Collections; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Install; using Umbraco.Core.IO; @@ -48,7 +50,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IDocumentRepository _documentRepository; private readonly IMediaRepository _mediaRepository; private readonly IMemberRepository _memberRepository; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IEntityXmlSerializer _entitySerializer; private readonly IPublishedModelFactory _publishedModelFactory; private readonly IDefaultCultureAccessor _defaultCultureAccessor; @@ -56,7 +58,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IHostingEnvironment _hostingEnvironment; private readonly IShortStringHelper _shortStringHelper; private readonly IIOHelper _ioHelper; - private readonly INuCacheSettings _config; + private readonly NuCacheSettings _config; // volatile because we read it with no lock private volatile bool _isReady; @@ -90,14 +92,15 @@ namespace Umbraco.Web.PublishedCache.NuCache IScopeProvider scopeProvider, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, - IDataSource dataSource, IGlobalSettings globalSettings, + IDataSource dataSource, + IOptions globalSettings, IEntityXmlSerializer entitySerializer, IPublishedModelFactory publishedModelFactory, UrlSegmentProviderCollection urlSegmentProviders, IHostingEnvironment hostingEnvironment, IShortStringHelper shortStringHelper, IIOHelper ioHelper, - INuCacheSettings config) + IOptions config) : base(publishedSnapshotAccessor, variationContextAccessor) { //if (Interlocked.Increment(ref _singletonCheck) > 1) @@ -114,12 +117,12 @@ namespace Umbraco.Web.PublishedCache.NuCache _mediaRepository = mediaRepository; _memberRepository = memberRepository; _defaultCultureAccessor = defaultCultureAccessor; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _urlSegmentProviders = urlSegmentProviders; _hostingEnvironment = hostingEnvironment; _shortStringHelper = shortStringHelper; _ioHelper = ioHelper; - _config = config; + _config = config.Value; // we need an Xml serializer here so that the member cache can support XPath, // for members this is done by navigating the serialized-to-xml member @@ -152,7 +155,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // stores are created with a db so they can write to it, but they do not read from it, // stores need to be populated, happens in OnResolutionFrozen which uses _localDbExists to // figure out whether it can read the databases or it should populate them from sql - + _logger.LogInformation("Creating the content store, localContentDbExists? {LocalContentDbExists}", _localContentDbExists); _contentStore = new ContentStore(publishedSnapshotAccessor, variationContextAccessor, _loggerFactory.CreateLogger("ContentStore"), _loggerFactory, publishedModelFactory, _localContentDb); _logger.LogInformation("Creating the media store, localMediaDbExists? {LocalMediaDbExists}", _localMediaDbExists); @@ -1244,7 +1247,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return new PublishedSnapshot.PublishedSnapshotElements { - ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, domainCache, _globalSettings, VariationContextAccessor), + ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, domainCache, Options.Create(_globalSettings), VariationContextAccessor), MediaCache = new MediaCache(previewDefault, mediaSnap, VariationContextAccessor), MemberCache = new MemberCache(previewDefault, snapshotCache, _serviceContext.MemberService, memberTypeCache, PublishedSnapshotAccessor, VariationContextAccessor, _entitySerializer, _publishedModelFactory), DomainCache = domainCache, diff --git a/src/Umbraco.Tests.Common/Builders/ConnectionStringsBuilder.cs b/src/Umbraco.Tests.Common/Builders/ConnectionStringsBuilder.cs new file mode 100644 index 0000000000..4aba98fccd --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/ConnectionStringsBuilder.cs @@ -0,0 +1,27 @@ +using Umbraco.Core; +using Umbraco.Core.Configuration; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; + +namespace Umbraco.Tests.Common.Builders +{ + public class ConnectionStringsBuilder : BuilderBase + { + private string _umbracoConnectionString; + + public ConnectionStringsBuilder WithUmbracoConnectionString(string umbracoConnectionString) + { + _umbracoConnectionString = umbracoConnectionString; + return this; + } + + public override ConnectionStrings Build() + { + var umbracoConnectionString = _umbracoConnectionString ?? string.Empty; + + return new ConnectionStrings + { + UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, umbracoConnectionString), + }; + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/ContentSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/ContentSettingsBuilder.cs new file mode 100644 index 0000000000..f5fb1fc08f --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/ContentSettingsBuilder.cs @@ -0,0 +1,12 @@ +using Umbraco.Core.Configuration.Models; + +namespace Umbraco.Tests.Common.Builders +{ + public class ContentSettingsBuilder : BuilderBase + { + public override ContentSettings Build() + { + return new ContentSettings(); + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilder.cs new file mode 100644 index 0000000000..e14fb0ade5 --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilder.cs @@ -0,0 +1,34 @@ +using CoreDebugSettings = Umbraco.Core.Configuration.Models.CoreDebugSettings; + +namespace Umbraco.Tests.Common.Builders +{ + public class CoreDebugSettingsBuilder : BuilderBase + { + private bool? _dumpOnTimeoutThreadAbort; + private bool? _logUncompletedScopes; + + public CoreDebugSettingsBuilder WithDumpOnTimeoutThreadAbort(bool dumpOnTimeoutThreadAbort) + { + _dumpOnTimeoutThreadAbort = dumpOnTimeoutThreadAbort; + return this; + } + + public CoreDebugSettingsBuilder WithLogUncompletedScopes(bool logUncompletedScopes) + { + _logUncompletedScopes = logUncompletedScopes; + return this; + } + + public override CoreDebugSettings Build() + { + var dumpOnTimeoutThreadAbort = _dumpOnTimeoutThreadAbort ?? false; + var logUncompletedScopes = _logUncompletedScopes ?? false; + + return new CoreDebugSettings + { + DumpOnTimeoutThreadAbort = dumpOnTimeoutThreadAbort, + LogUncompletedScopes = logUncompletedScopes, + }; + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/GlobalSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/GlobalSettingsBuilder.cs index b1fe45f1f7..d39bd71d2e 100644 --- a/src/Umbraco.Tests.Common/Builders/GlobalSettingsBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/GlobalSettingsBuilder.cs @@ -1,4 +1,4 @@ -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Tests.Common.Builders { @@ -9,7 +9,7 @@ namespace Umbraco.Tests.Common.Builders } } - public class GlobalSettingsBuilder : ChildBuilderBase + public class GlobalSettingsBuilder : ChildBuilderBase { private string _configurationStatus; private string _databaseFactoryServerVersion; @@ -18,15 +18,13 @@ namespace Umbraco.Tests.Common.Builders private bool? _hideTopLevelNodeFromPath; private bool? _installEmptyDatabase; private bool? _installMissingDatabase; - private bool? _isSmtpServerConfigured; - private string _path; + private string _umbracoPath; private string _registerType; private string _reservedPaths; private string _reservedUrls; private int? _timeOutInMinutes; private string _umbracoCssPath; private string _umbracoMediaPath; - private string _umbracoPath; private string _umbracoScriptsPath; private string _mainDomLock; private string _noNodesViewPath; @@ -83,15 +81,9 @@ namespace Umbraco.Tests.Common.Builders return this; } - public GlobalSettingsBuilder WithIsSmtpServerConfigured(bool isSmtpServerConfigured) + public GlobalSettingsBuilder WithUmbracoPath(string umbracoPath) { - _isSmtpServerConfigured = isSmtpServerConfigured; - return this; - } - - public GlobalSettingsBuilder WithPath(string path) - { - _path = path; + _umbracoPath = umbracoPath; return this; } @@ -113,12 +105,6 @@ namespace Umbraco.Tests.Common.Builders return this; } - public GlobalSettingsBuilder WithUmbracoPath(string umbracoPath) - { - _umbracoPath = umbracoPath; - return this; - } - public GlobalSettingsBuilder WithUseHttps(bool useHttps) { _useHttps = useHttps; @@ -166,7 +152,7 @@ namespace Umbraco.Tests.Common.Builders return this; } - public override IGlobalSettings Build() + public override GlobalSettings Build() { var configurationStatus = _configurationStatus ?? "9.0.0"; var databaseFactoryServerVersion = _databaseFactoryServerVersion ?? null; @@ -175,11 +161,9 @@ namespace Umbraco.Tests.Common.Builders var hideTopLevelNodeFromPath = _hideTopLevelNodeFromPath ?? false; var installEmptyDatabase = _installEmptyDatabase ?? false; var installMissingDatabase = _installMissingDatabase ?? false; - var isSmtpServerConfigured = _isSmtpServerConfigured ?? false; - var path = _path ?? "/umbraco"; var registerType = _registerType ?? null; - var reservedPaths = _reservedPaths ?? "~/app_plugins/,~/install/,~/mini-profiler-resources/,"; - var reservedUrls = _reservedUrls ?? "~/config/splashes/noNodes.aspx,~/.well-known,"; + var reservedPaths = _reservedPaths ?? GlobalSettings.StaticReservedPaths; + var reservedUrls = _reservedUrls ?? GlobalSettings.StaticReservedUrls; var umbracoPath = _umbracoPath ?? "~/umbraco"; var useHttps = _useHttps ?? false; var umbracoCssPath = _umbracoCssPath ?? "~/css"; @@ -191,7 +175,7 @@ namespace Umbraco.Tests.Common.Builders var mainDomLock = _mainDomLock ?? string.Empty; var noNodesViewPath = _noNodesViewPath ?? "~/config/splashes/NoNodes.cshtml"; - return new TestGlobalSettings + return new GlobalSettings { ConfigurationStatus = configurationStatus, DatabaseFactoryServerVersion = databaseFactoryServerVersion, @@ -200,8 +184,6 @@ namespace Umbraco.Tests.Common.Builders HideTopLevelNodeFromPath = hideTopLevelNodeFromPath, InstallEmptyDatabase = installEmptyDatabase, InstallMissingDatabase = installMissingDatabase, - IsSmtpServerConfigured = isSmtpServerConfigured, - Path = path, RegisterType = registerType, ReservedPaths = reservedPaths, ReservedUrls = reservedUrls, @@ -212,40 +194,14 @@ namespace Umbraco.Tests.Common.Builders UmbracoScriptsPath = umbracoScriptsPath, VersionCheckPeriod = versionCheckPeriod, TimeOutInMinutes = timeOutInMinutes, - SmtpSettings = smtpSettings, + Smtp = smtpSettings, MainDomLock = mainDomLock, NoNodesViewPath = noNodesViewPath, }; } - - private class TestGlobalSettings : IGlobalSettings - { private string _iconsPath; - public string ReservedUrls { get; set; } - public string ReservedPaths { get; set; } public string IconsPath{ get; set; } - public string Path { get; set; } - public string ConfigurationStatus { get; set; } - public int TimeOutInMinutes { get; set; } - public string DefaultUILanguage { get; set; } - public bool HideTopLevelNodeFromPath { get; set; } - public bool UseHttps { get; set; } - public int VersionCheckPeriod { get; set; } - public string UmbracoPath { get; set; } - public string UmbracoCssPath { get; set; } - public string UmbracoScriptsPath { get; set; } - public string UmbracoMediaPath { get; set; } - public bool IsSmtpServerConfigured { get; set; } - public ISmtpSettings SmtpSettings { get; set; } - public bool InstallMissingDatabase { get; set; } - public bool InstallEmptyDatabase { get; set; } - public bool DisableElectionForSingleServer { get; set; } - public string RegisterType { get; set; } - public string DatabaseFactoryServerVersion { get; set; } - public string MainDomLock { get; set; } - public string NoNodesViewPath { get; set; } - } } } diff --git a/src/Umbraco.Tests.Common/Builders/HostingSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/HostingSettingsBuilder.cs new file mode 100644 index 0000000000..3e5e1db391 --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/HostingSettingsBuilder.cs @@ -0,0 +1,44 @@ +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; + +namespace Umbraco.Tests.Common.Builders +{ + public class HostingSettingsBuilder : BuilderBase + { + private string _applicationVirtualPath; + private bool? _debug; + private LocalTempStorage? _localTempStorageLocation; + + public HostingSettingsBuilder WithApplicationVirtualPath(string applicationVirtualPath) + { + _applicationVirtualPath = applicationVirtualPath; + return this; + } + + public HostingSettingsBuilder WithDebug(bool debug) + { + _debug = debug; + return this; + } + + public HostingSettingsBuilder WithLocalTempStorageLocation(LocalTempStorage localTempStorageLocation) + { + _localTempStorageLocation = localTempStorageLocation; + return this; + } + + public override HostingSettings Build() + { + var debug = _debug ?? false; + var localTempStorageLocation = _localTempStorageLocation ?? LocalTempStorage.Default; + var applicationVirtualPath = _applicationVirtualPath ?? null; + + return new HostingSettings + { + ApplicationVirtualPath = applicationVirtualPath, + Debug = debug, + LocalTempStorageLocation = localTempStorageLocation, + }; + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/LanguageBuilder.cs b/src/Umbraco.Tests.Common/Builders/LanguageBuilder.cs index 88c8fa4639..7174baaba1 100644 --- a/src/Umbraco.Tests.Common/Builders/LanguageBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/LanguageBuilder.cs @@ -1,7 +1,6 @@ using System; using System.Globalization; -using Moq; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Tests.Common.Builders.Interfaces; @@ -58,6 +57,7 @@ namespace Umbraco.Tests.Common.Builders public override ILanguage Build() { var cultureInfo = _cultureInfo ?? CultureInfo.GetCultureInfo("en-US"); + var globalSettings = new GlobalSettingsBuilder().WithDefaultUiLanguage(cultureInfo.Name).Build(); var key = _key ?? Guid.NewGuid(); var createDate = _createDate ?? DateTime.Now; var updateDate = _updateDate ?? DateTime.Now; @@ -66,7 +66,7 @@ namespace Umbraco.Tests.Common.Builders var isDefault = _isDefault ?? false; var isMandatory = _isMandatory ?? false; - return new Language(Mock.Of(), cultureInfo.Name) + return new Language(globalSettings, cultureInfo.Name) { Id = _id ?? 0, CultureName = cultureInfo.EnglishName, diff --git a/src/Umbraco.Tests.Common/Builders/ModelsBuilderConfigBuilder.cs b/src/Umbraco.Tests.Common/Builders/ModelsBuilderConfigBuilder.cs new file mode 100644 index 0000000000..4b94339dc0 --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/ModelsBuilderConfigBuilder.cs @@ -0,0 +1,12 @@ +using Umbraco.Core.Configuration.Models; + +namespace Umbraco.Tests.Common.Builders +{ + public class ModelsBuilderConfigBuilder : BuilderBase + { + public override ModelsBuilderConfig Build() + { + return new ModelsBuilderConfig(); + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/NuCacheSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/NuCacheSettingsBuilder.cs new file mode 100644 index 0000000000..35d5c66e4a --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/NuCacheSettingsBuilder.cs @@ -0,0 +1,12 @@ +using Umbraco.Core.Configuration.Models; + +namespace Umbraco.Tests.Common.Builders +{ + public class NuCacheSettingsBuilder : BuilderBase + { + public override NuCacheSettings Build() + { + return new NuCacheSettings(); + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilder.cs new file mode 100644 index 0000000000..3c6f652014 --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilder.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Configuration.UmbracoSettings; + +namespace Umbraco.Tests.Common.Builders +{ + public class RequestHandlerSettingsBuilder : BuilderBase + { + private bool? _addTrailingSlash; + private string _convertUrlsToAscii; + private IEnumerable _charCollection; + + public RequestHandlerSettingsBuilder WithAddTrailingSlash(bool addTrailingSlash) + { + _addTrailingSlash = addTrailingSlash; + return this; + } + + public RequestHandlerSettingsBuilder WithConvertUrlsToAscii(string convertUrlsToAscii) + { + _convertUrlsToAscii = convertUrlsToAscii; + return this; + } + + public RequestHandlerSettingsBuilder WithCharCollection(IEnumerable charCollection) + { + _charCollection = charCollection; + return this; + } + + public override RequestHandlerSettings Build() + { + var addTrailingSlash = _addTrailingSlash ?? false; + var convertUrlsToAscii = _convertUrlsToAscii ?? "false"; + var charCollection = _charCollection ?? RequestHandlerSettings.DefaultCharCollection; + + return new RequestHandlerSettings + { + AddTrailingSlash = addTrailingSlash, + ConvertUrlsToAscii = convertUrlsToAscii, + CharCollection = charCollection, + }; + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/SmtpSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/SmtpSettingsBuilder.cs index bd85807203..f979197e4c 100644 --- a/src/Umbraco.Tests.Common/Builders/SmtpSettingsBuilder.cs +++ b/src/Umbraco.Tests.Common/Builders/SmtpSettingsBuilder.cs @@ -1,6 +1,5 @@ using System.Net.Mail; -using Umbraco.Core.Configuration; -using Umbraco.Core.Models.Membership; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Tests.Common.Builders { @@ -12,7 +11,7 @@ namespace Umbraco.Tests.Common.Builders } public class SmtpSettingsBuilder - : ChildBuilderBase + : ChildBuilderBase { private string _from; private string _host; @@ -68,7 +67,7 @@ namespace Umbraco.Tests.Common.Builders return this; } - public override ISmtpSettings Build() + public override SmtpSettings Build() { var from = _from ?? null; var host = _host ?? null; @@ -78,7 +77,7 @@ namespace Umbraco.Tests.Common.Builders var username = _username ?? null; var password = _password ?? null; - return new TestSmtpSettings() + return new SmtpSettings() { From = from, Host = host, @@ -89,16 +88,5 @@ namespace Umbraco.Tests.Common.Builders Password = password, }; } - - private class TestSmtpSettings : ISmtpSettings - { - public string From { get; set; } - public string Host { get; set; } - public int Port { get; set; } - public string PickupDirectoryLocation { get; set; } - public SmtpDeliveryMethod DeliveryMethod { get; set; } - public string Username { get; set; } - public string Password { get; set; } - } } } diff --git a/src/Umbraco.Tests.Common/Builders/UserPasswordConfigurationSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/UserPasswordConfigurationSettingsBuilder.cs new file mode 100644 index 0000000000..3a0dfc3e9a --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/UserPasswordConfigurationSettingsBuilder.cs @@ -0,0 +1,12 @@ +using Umbraco.Core.Configuration.Models; + +namespace Umbraco.Tests.Common.Builders +{ + public class UserPasswordConfigurationSettingsBuilder : BuilderBase + { + public override UserPasswordConfigurationSettings Build() + { + return new UserPasswordConfigurationSettings(); + } + } +} diff --git a/src/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilder.cs b/src/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilder.cs new file mode 100644 index 0000000000..e32fff31fa --- /dev/null +++ b/src/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilder.cs @@ -0,0 +1,89 @@ +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Models.PublishedContent; + +namespace Umbraco.Tests.Common.Builders +{ + public class WebRoutingSettingsBuilder : BuilderBase + { + private bool? _trySkipIisCustomErrors; + private bool? _internalRedirectPreservesTemplate; + private bool? _disableAlternativeTemplates; + private bool? _validateAlternativeTemplates; + private bool? _disableFindContentByIdPath; + private bool? _disableRedirectUrlTracking; + private string _urlProviderMode; + private string _umbracoApplicationUrl; + + public WebRoutingSettingsBuilder WithTrySkipIisCustomErrors(bool trySkipIisCustomErrors) + { + _trySkipIisCustomErrors = trySkipIisCustomErrors; + return this; + } + + public WebRoutingSettingsBuilder WithInternalRedirectPreservesTemplate(bool internalRedirectPreservesTemplate) + { + _internalRedirectPreservesTemplate = internalRedirectPreservesTemplate; + return this; + } + + public WebRoutingSettingsBuilder WithDisableAlternativeTemplates(bool disableAlternativeTemplates) + { + _disableAlternativeTemplates = disableAlternativeTemplates; + return this; + } + + public WebRoutingSettingsBuilder WithValidateAlternativeTemplates(bool validateAlternativeTemplates) + { + _validateAlternativeTemplates = validateAlternativeTemplates; + return this; + } + + public WebRoutingSettingsBuilder WithDisableFindContentByIdPath(bool disableFindContentByIdPath) + { + _disableFindContentByIdPath = disableFindContentByIdPath; + return this; + } + + public WebRoutingSettingsBuilder WithDisableRedirectUrlTracking(bool disableRedirectUrlTracking) + { + _disableRedirectUrlTracking = disableRedirectUrlTracking; + return this; + } + + public WebRoutingSettingsBuilder WithUrlProviderMode(string urlProviderMode) + { + _urlProviderMode = urlProviderMode; + return this; + } + + public WebRoutingSettingsBuilder WithUmbracoApplicationUrl(string umbracoApplicationUrl) + { + _umbracoApplicationUrl = umbracoApplicationUrl; + return this; + } + + public override WebRoutingSettings Build() + { + var trySkipIisCustomErrors = _trySkipIisCustomErrors ?? false; + var internalRedirectPreservesTemplate = _internalRedirectPreservesTemplate ?? false; + var disableAlternativeTemplates = _disableAlternativeTemplates ?? false; + var validateAlternativeTemplates = _validateAlternativeTemplates ?? false; + var disableFindContentByIdPath = _disableFindContentByIdPath ?? false; + var disableRedirectUrlTracking = _disableRedirectUrlTracking ?? false; + var urlProviderMode = _urlProviderMode ?? UrlMode.Auto.ToString(); + var umbracoApplicationUrl = _umbracoApplicationUrl ?? string.Empty; + + return new WebRoutingSettings + { + TrySkipIisCustomErrors = trySkipIisCustomErrors, + InternalRedirectPreservesTemplate = internalRedirectPreservesTemplate, + DisableAlternativeTemplates = disableAlternativeTemplates, + ValidateAlternativeTemplates = validateAlternativeTemplates, + DisableFindContentByIdPath = disableFindContentByIdPath, + DisableRedirectUrlTracking = disableRedirectUrlTracking, + UrlProviderMode = urlProviderMode, + UmbracoApplicationUrl = umbracoApplicationUrl, + }; + } + } +} diff --git a/src/Umbraco.Tests.Common/SettingsForTests.cs b/src/Umbraco.Tests.Common/SettingsForTests.cs deleted file mode 100644 index 1a14dc6bc1..0000000000 --- a/src/Umbraco.Tests.Common/SettingsForTests.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System.Collections.Generic; -using Moq; -using Semver; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Legacy; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; -using Umbraco.Core.Models.PublishedContent; - -namespace Umbraco.Tests.Common -{ - public class SettingsForTests - { - public SettingsForTests() - { - } - - public IGlobalSettings GenerateMockGlobalSettings(IUmbracoVersion umbVersion = null) - { - var semanticVersion = umbVersion?.SemanticVersion ?? new SemVersion(9); - - var config = Mock.Of( - settings => - settings.UseHttps == false && - settings.HideTopLevelNodeFromPath == false && - settings.TimeOutInMinutes == 20 && - settings.DefaultUILanguage == "en" && - settings.ReservedPaths == (GlobalSettings.StaticReservedPaths + "~/umbraco") && - settings.ReservedUrls == GlobalSettings.StaticReservedUrls && - settings.UmbracoPath == "~/umbraco" && - settings.UmbracoMediaPath == "~/media" && - settings.UmbracoCssPath == "~/css" && - settings.UmbracoScriptsPath == "~/scripts" - ); - - - - return config; - } - - /// - /// Returns generated settings which can be stubbed to return whatever values necessary - /// - /// - public IContentSettings GenerateMockContentSettings() - { - - var content = new Mock(); - - //Now configure some defaults - the defaults in the config section classes do NOT pertain to the mocked data!! - content.Setup(x => x.ImageAutoFillProperties).Returns(ContentImagingElement.GetDefaultImageAutoFillProperties()); - content.Setup(x => x.ImageFileTypes).Returns(ContentImagingElement.GetDefaultImageFileTypes()); - return content.Object; - } - - //// from appSettings - - //private readonly IDictionary SavedAppSettings = new Dictionary(); - - //static void SaveSetting(string key) - //{ - // SavedAppSettings[key] = ConfigurationManager.AppSettings[key]; - //} - - //static void SaveSettings() - //{ - // SaveSetting("umbracoHideTopLevelNodeFromPath"); - // SaveSetting("umbracoUseDirectoryUrls"); - // SaveSetting("umbracoPath"); - // SaveSetting("umbracoReservedPaths"); - // SaveSetting("umbracoReservedUrls"); - // SaveSetting("umbracoConfigurationStatus"); - //} - - - - // reset & defaults - - //static SettingsForTests() - //{ - // //SaveSettings(); - //} - - public void Reset() - { - ResetSettings(); - GlobalSettings.Reset(); - - //foreach (var kvp in SavedAppSettings) - // ConfigurationManager.AppSettings.Set(kvp.Key, kvp.Value); - - //// set some defaults that are wrong in the config file?! - //// this is annoying, really - //HideTopLevelNodeFromPath = false; - } - - /// - /// This sets all settings back to default settings - /// - private void ResetSettings() - { - _defaultGlobalSettings.Clear(); - _defaultHostingSettings = null; - } - - private readonly Dictionary _defaultGlobalSettings = new Dictionary(); - private IHostingSettings _defaultHostingSettings; - - public IGlobalSettings GetDefaultGlobalSettings(IUmbracoVersion umbVersion) - { - if (_defaultGlobalSettings.TryGetValue(umbVersion.SemanticVersion, out var settings)) - return settings; - - settings = GenerateMockGlobalSettings(umbVersion); - _defaultGlobalSettings[umbVersion.SemanticVersion] = settings; - return settings; - } - - public IHostingSettings DefaultHostingSettings => _defaultHostingSettings ?? (_defaultHostingSettings = GenerateMockHostingSettings()); - - public IHostingSettings GenerateMockHostingSettings() - { - var config = Mock.Of( - settings => - settings.LocalTempStorageLocation == LocalTempStorage.EnvironmentTemp && - settings.DebugMode == false - ); - return config; - } - - public IWebRoutingSettings GenerateMockWebRoutingSettings() - { - var mock = new Mock(); - - mock.Setup(x => x.DisableRedirectUrlTracking).Returns(false); - mock.Setup(x => x.InternalRedirectPreservesTemplate).Returns(false); - mock.Setup(x => x.UrlProviderMode).Returns(UrlMode.Auto.ToString()); - - return mock.Object; - } - - public IRequestHandlerSettings GenerateMockRequestHandlerSettings() - { - var mock = new Mock(); - - mock.Setup(x => x.AddTrailingSlash).Returns(true); - mock.Setup(x => x.ConvertUrlsToAscii).Returns(false); - mock.Setup(x => x.TryConvertUrlsToAscii).Returns(false); - mock.Setup(x => x.CharCollection).Returns(RequestHandlerElement.GetDefaultCharReplacements); - - return mock.Object; - } - - public ISecuritySettings GenerateMockSecuritySettings() - { - var security = new Mock(); - - return security.Object; - } - - public IUserPasswordConfiguration GenerateMockUserPasswordConfiguration() - { - var mock = new Mock(); - - return mock.Object; - } - - public IMemberPasswordConfiguration GenerateMockMemberPasswordConfiguration() - { - var mock = new Mock(); - - return mock.Object; - } - } -} diff --git a/src/Umbraco.Tests.Common/TestHelperBase.cs b/src/Umbraco.Tests.Common/TestHelperBase.cs index ff0496d444..285a20d064 100644 --- a/src/Umbraco.Tests.Common/TestHelperBase.cs +++ b/src/Umbraco.Tests.Common/TestHelperBase.cs @@ -8,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Diagnostics; using Umbraco.Core.Hosting; @@ -20,6 +21,7 @@ using Umbraco.Core.Serialization; using Umbraco.Core.Strings; using Umbraco.Web; using Umbraco.Web.Routing; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Common { @@ -35,7 +37,6 @@ namespace Umbraco.Tests.Common protected TestHelperBase(Assembly entryAssembly) { - SettingsForTests = new SettingsForTests(); MainDom = new SimpleMainDom(); _typeFinder = new TypeFinder(NullLoggerFactory.Instance.CreateLogger(), new DefaultUmbracoAssemblyProvider(entryAssembly), new VaryingRuntimeHash()); } @@ -47,11 +48,11 @@ namespace Umbraco.Tests.Common return new TypeLoader(Mock.Of(), Mock.Of(), new DirectoryInfo(IOHelper.MapPath("~/App_Data/TEMP")), Mock.Of(), Mock.Of()); } - public Configs GetConfigs() => GetConfigsFactory().Create(); + // public Configs GetConfigs() => GetConfigsFactory().Create(); public abstract IBackOfficeInfo GetBackOfficeInfo(); - public IConfigsFactory GetConfigsFactory() => new ConfigsFactory(); + //public IConfigsFactory GetConfigsFactory() => new ConfigsFactory(); /// /// Gets the working directory of the test project. @@ -77,7 +78,7 @@ namespace Umbraco.Tests.Common public abstract IDbProviderFactoryCreator DbProviderFactoryCreator { get; } public abstract IBulkSqlInsertProvider BulkSqlInsertProvider { get; } public abstract IMarchal Marchal { get; } - public ICoreDebugSettings CoreDebugSettings { get; } = new CoreDebugSettings(); + public CoreDebugSettings CoreDebugSettings { get; } = new CoreDebugSettings(); public IIOHelper IOHelper { @@ -99,10 +100,6 @@ namespace Umbraco.Tests.Common return _uriUtility; } } - - public SettingsForTests SettingsForTests { get; } - public IWebRoutingSettings WebRoutingSettings => SettingsForTests.GenerateMockWebRoutingSettings(); - /// /// Some test files are copied to the /bin (/bin/debug) on build, this is a utility to return their physical path based on a virtual path name /// @@ -121,11 +118,11 @@ namespace Umbraco.Tests.Common return relativePath.Replace("~/", bin + "/"); } - public IUmbracoVersion GetUmbracoVersion() => new UmbracoVersion(GetConfigs().Global()); + public IUmbracoVersion GetUmbracoVersion() => new UmbracoVersion(); public IRegister GetRegister() { - return RegisterFactory.Create(GetConfigs().Global()); + return RegisterFactory.Create(new GlobalSettingsBuilder().Build()); } public abstract IHostingEnvironment GetHostingEnvironment(); diff --git a/src/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj b/src/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj index 0557069bd9..6882a28d5e 100644 --- a/src/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj +++ b/src/Umbraco.Tests.Common/Umbraco.Tests.Common.csproj @@ -13,7 +13,6 @@ - diff --git a/src/Umbraco.Tests.Integration/ContainerTests.cs b/src/Umbraco.Tests.Integration/ContainerTests.cs index 20e26c09d9..9f666eb37e 100644 --- a/src/Umbraco.Tests.Integration/ContainerTests.cs +++ b/src/Umbraco.Tests.Integration/ContainerTests.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.Integration // Register in the container var composition = new Composition(umbracoContainer, typeLoader, - testHelper.ProfilingLogger, runtimeState, testHelper.GetConfigs(), testHelper.IOHelper, testHelper.AppCaches); + testHelper.ProfilingLogger, runtimeState, testHelper.IOHelper, testHelper.AppCaches); composition.RegisterEssentials(testHelper.ConsoleLoggerFactory.CreateLogger("RegisterEssentials"), testHelper.Profiler, testHelper.ProfilingLogger, testHelper.MainDom, testHelper.AppCaches, umbracoDatabaseFactory, typeLoader, runtimeState, testHelper.GetTypeFinder(), testHelper.IOHelper, testHelper.GetUmbracoVersion(), dbProviderFactoryCreator, diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs index 9facef8568..964051f1d2 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHelper.cs @@ -1,22 +1,24 @@ - -using System; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Hosting; -using Moq; +using System; using System.Data.Common; using System.IO; using System.Net; using System.Reflection; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Moq; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Diagnostics; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; -using Umbraco.Net; using Umbraco.Core.Persistence; using Umbraco.Core.Runtime; +using Umbraco.Net; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Web.Common.AspNetCore; using IHostingEnvironment = Umbraco.Core.Hosting.IHostingEnvironment; using Microsoft.Extensions.FileProviders; @@ -114,16 +116,26 @@ namespace Umbraco.Tests.Integration.Implementations public override IBackOfficeInfo GetBackOfficeInfo() { if (_backOfficeInfo == null) - _backOfficeInfo = - new AspNetCoreBackOfficeInfo(SettingsForTests.GetDefaultGlobalSettings(GetUmbracoVersion())); + { + var globalSettings = new GlobalSettingsBuilder().Build(); + var mockedOptionsMonitorOfGlobalSettings = Mock.Of>(x => x.CurrentValue == globalSettings); + _backOfficeInfo = new AspNetCoreBackOfficeInfo(mockedOptionsMonitorOfGlobalSettings); + } + return _backOfficeInfo; } public override IHostingEnvironment GetHostingEnvironment() => _hostingEnvironment ??= new TestHostingEnvironment( - SettingsForTests.DefaultHostingSettings, + GetIOptionsMonitorOfHostingSettings(), _hostEnvironment); + private IOptionsMonitor GetIOptionsMonitorOfHostingSettings() + { + var hostingSettings = new HostingSettingsBuilder().Build(); + return Mock.Of>(x => x.CurrentValue == hostingSettings); + } + public override IApplicationShutdownRegistry GetHostingEnvironmentLifetime() => _hostingLifetime; public override IIpResolver GetIpResolver() => _ipResolver; diff --git a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs index 076cecef4a..1a3415634b 100644 --- a/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs +++ b/src/Umbraco.Tests.Integration/Implementations/TestHostingEnvironment.cs @@ -1,15 +1,14 @@ using Microsoft.AspNetCore.Hosting; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Common.AspNetCore; using IHostingEnvironment = Umbraco.Core.Hosting.IHostingEnvironment; namespace Umbraco.Tests.Integration.Implementations { - public class TestHostingEnvironment : AspNetCoreHostingEnvironment, IHostingEnvironment { - public TestHostingEnvironment(IHostingSettings hostingSettings, IWebHostEnvironment webHostEnvironment) + public TestHostingEnvironment(IOptionsMonitor hostingSettings, IWebHostEnvironment webHostEnvironment) : base(hostingSettings, webHostEnvironment) { } diff --git a/src/Umbraco.Tests.Integration/Persistence/Repositories/DictionaryRepositoryTest.cs b/src/Umbraco.Tests.Integration/Persistence/Repositories/DictionaryRepositoryTest.cs index a85873a761..be9a0ce5ed 100644 --- a/src/Umbraco.Tests.Integration/Persistence/Repositories/DictionaryRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Persistence/Repositories/DictionaryRepositoryTest.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core.Models; -using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -288,7 +288,8 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories { var repository = CreateRepository(); - var languageNo = new Language(GlobalSettings, "nb-NO") { CultureName = "nb-NO" }; + var globalSettings = new GlobalSettingsBuilder().Build(); + var languageNo = new Language(globalSettings, "nb-NO") { CultureName = "nb-NO" }; localizationService.Save(languageNo); // Act @@ -368,7 +369,8 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories var localizationService = GetRequiredService(); var language = localizationService.GetLanguageByIsoCode("en-US"); - var languageDK = new Language(GlobalSettings, "da-DK") { CultureName = "da-DK" }; + var globalSettings = new GlobalSettingsBuilder().Build(); + var languageDK = new Language(globalSettings, "da-DK") { CultureName = "da-DK" }; localizationService.Save(languageDK);//Id 2 var readMore = new DictionaryItem("Read More"); diff --git a/src/Umbraco.Tests.Integration/Persistence/Repositories/LanguageRepositoryTest.cs b/src/Umbraco.Tests.Integration/Persistence/Repositories/LanguageRepositoryTest.cs index 55c75c307a..59114a6dc3 100644 --- a/src/Umbraco.Tests.Integration/Persistence/Repositories/LanguageRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Persistence/Repositories/LanguageRepositoryTest.cs @@ -4,12 +4,13 @@ using System.Linq; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.Testing; @@ -19,15 +20,18 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class LanguageRepositoryTest : UmbracoIntegrationTest { + private GlobalSettings _globalSettings; + [SetUp] public void SetUp() { CreateTestData(); + _globalSettings = new GlobalSettingsBuilder().Build(); } private LanguageRepository CreateRepository(IScopeProvider provider) { - return new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), GlobalSettings); + return new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); } [Test] @@ -61,7 +65,7 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories var repository = CreateRepository(provider); var au = CultureInfo.GetCultureInfo("en-AU"); - var language = (ILanguage)new Language(GlobalSettings, au.Name) + var language = (ILanguage)new Language(_globalSettings, au.Name) { CultureName = au.DisplayName, FallbackLanguageId = 1 @@ -185,7 +189,7 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories var repository = CreateRepository(provider); // Act - var languageBR = new Language(GlobalSettings, "pt-BR") { CultureName = "pt-BR" }; + var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR" }; repository.Save(languageBR); // Assert @@ -207,7 +211,7 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories var repository = CreateRepository(provider); // Act - var languageBR = new Language(GlobalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; + var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; repository.Save(languageBR); // Assert @@ -229,7 +233,7 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories var repository = CreateRepository(provider); // Act - var languageBR = new Language(GlobalSettings, "pt-BR") + var languageBR = new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", FallbackLanguageId = 1 @@ -252,16 +256,16 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories { var repository = CreateRepository(provider); - var languageBR = (ILanguage)new Language(GlobalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; + var languageBR = (ILanguage)new Language(_globalSettings, "pt-BR") { CultureName = "pt-BR", IsDefault = true, IsMandatory = true }; repository.Save(languageBR); - var languageEN = new Language(GlobalSettings, "en-AU") { CultureName = "en-AU" }; + var languageEN = new Language(_globalSettings, "en-AU") { CultureName = "en-AU" }; repository.Save(languageEN); Assert.IsTrue(languageBR.IsDefault); Assert.IsTrue(languageBR.IsMandatory); // Act - var languageNZ = new Language(GlobalSettings, "en-NZ") { CultureName = "en-NZ", IsDefault = true, IsMandatory = true }; + var languageNZ = new Language(_globalSettings, "en-NZ") { CultureName = "en-NZ", IsDefault = true, IsMandatory = true }; repository.Save(languageNZ); languageBR = repository.Get(languageBR.Id); @@ -384,16 +388,16 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories //Id 1 is en-US - when Umbraco is installed var localizationService = GetRequiredService(); - var languageDK = new Language(GlobalSettings, "da-DK") { CultureName = "da-DK" }; + var languageDK = new Language(_globalSettings, "da-DK") { CultureName = "da-DK" }; localizationService.Save(languageDK);//Id 2 - var languageSE = new Language(GlobalSettings, "sv-SE") { CultureName = "sv-SE" }; + var languageSE = new Language(_globalSettings, "sv-SE") { CultureName = "sv-SE" }; localizationService.Save(languageSE);//Id 3 - var languageDE = new Language(GlobalSettings, "de-DE") { CultureName = "de-DE" }; + var languageDE = new Language(_globalSettings, "de-DE") { CultureName = "de-DE" }; localizationService.Save(languageDE);//Id 4 - var languagePT = new Language(GlobalSettings, "pt-PT") { CultureName = "pt-PT" }; + var languagePT = new Language(_globalSettings, "pt-PT") { CultureName = "pt-PT" }; localizationService.Save(languagePT);//Id 5 } } diff --git a/src/Umbraco.Tests.Integration/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests.Integration/Persistence/Repositories/TemplateRepositoryTest.cs index 67ea60788c..e2c5141ff0 100644 --- a/src/Umbraco.Tests.Integration/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Persistence/Repositories/TemplateRepositoryTest.cs @@ -15,6 +15,7 @@ using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Implementations; using Umbraco.Tests.Integration.Testing; using Umbraco.Tests.TestHelpers.Entities; @@ -260,10 +261,10 @@ namespace Umbraco.Tests.Integration.Persistence.Repositories using (provider.CreateScope()) { var templateRepository = CreateRepository(provider); - + var globalSettings = new GlobalSettingsBuilder().Build(); var tagRepository = new TagRepository(scopeAccessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), GlobalSettings); + var languageRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); var contentTypeRepository = new ContentTypeRepository(scopeAccessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(scopeAccessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger()); var entityRepository = new EntityRepository(scopeAccessor); diff --git a/src/Umbraco.Tests.Integration/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests.Integration/Persistence/Repositories/UserRepositoryTest.cs index fceb8da37d..8d8736adc2 100644 --- a/src/Umbraco.Tests.Integration/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests.Integration/Persistence/Repositories/UserRepositoryTest.cs @@ -1,11 +1,12 @@ using System; using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; @@ -26,7 +27,7 @@ namespace Umbraco.Tests.Persistence.Repositories private UserRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor) provider; - var repository = new UserRepository(accessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Mappers, GlobalSettings, Mock.Of(), new JsonNetSerializer()); + var repository = new UserRepository(accessor, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Mappers, Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); return repository; } @@ -118,7 +119,7 @@ namespace Umbraco.Tests.Persistence.Repositories var id = user.Id; - var repository2 = new UserRepository((IScopeAccessor) provider, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Mock.Of(),GlobalSettings, Mock.Of(), new JsonNetSerializer()); + var repository2 = new UserRepository((IScopeAccessor) provider, AppCaches.Disabled, ConsoleLoggerFactory.CreateLogger(), Mock.Of(), Options.Create(GlobalSettings), Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); repository2.Delete(user); diff --git a/src/Umbraco.Tests.Integration/RuntimeTests.cs b/src/Umbraco.Tests.Integration/RuntimeTests.cs index 294a4cde3c..85c5e0e0b6 100644 --- a/src/Umbraco.Tests.Integration/RuntimeTests.cs +++ b/src/Umbraco.Tests.Integration/RuntimeTests.cs @@ -17,6 +17,8 @@ using Umbraco.Tests.Integration.Implementations; using Umbraco.Tests.Integration.Testing; using Umbraco.Web.Common.AspNetCore; using Umbraco.Extensions; +using Umbraco.Tests.Common.Builders; +using Microsoft.Extensions.Options; using ILogger = Umbraco.Core.Logging.ILogger; namespace Umbraco.Tests.Integration @@ -55,13 +57,16 @@ namespace Umbraco.Tests.Integration var testHelper = new TestHelper(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); + // Create the core runtime - var coreRuntime = new CoreRuntime(testHelper.GetConfigs(), testHelper.GetUmbracoVersion(), + var coreRuntime = new CoreRuntime(globalSettings, connectionStrings, testHelper.GetUmbracoVersion(), testHelper.IOHelper, testHelper.ConsoleLoggerFactory.CreateLogger("CoreRunTime"), testHelper.ConsoleLoggerFactory, testHelper.Profiler, testHelper.UmbracoBootPermissionChecker, testHelper.GetHostingEnvironment(), testHelper.GetBackOfficeInfo(), testHelper.DbProviderFactoryCreator, testHelper.MainDom, testHelper.GetTypeFinder(), AppCaches.NoCache); - // boot it! + // boot it! var factory = coreRuntime.Configure(umbracoContainer); Assert.IsTrue(coreRuntime.MainDom.IsMainDom); @@ -71,6 +76,23 @@ namespace Umbraco.Tests.Integration Assert.IsFalse(MyComponent.IsInit); Assert.IsFalse(MyComponent.IsTerminated); + // TODO: found these registration were necessary here (as we haven't called the HostBuilder?), as dependencies for ComponentCollection + // are not resolved. Need to check this if these explicit registrations are the best way to handle this. + var contentSettings = new ContentSettingsBuilder().Build(); + var coreDebugSettings = new CoreDebugSettingsBuilder().Build(); + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var userPasswordConfigurationSettings = new UserPasswordConfigurationSettingsBuilder().Build(); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + + umbracoContainer.Register(x => Options.Create(globalSettings)); + umbracoContainer.Register(x => Options.Create(contentSettings)); + umbracoContainer.Register(x => Options.Create(coreDebugSettings)); + umbracoContainer.Register(x => Options.Create(nuCacheSettings)); + umbracoContainer.Register(x => Options.Create(requestHandlerSettings)); + umbracoContainer.Register(x => Options.Create(userPasswordConfigurationSettings)); + umbracoContainer.Register(x => Options.Create(webRoutingSettings)); + coreRuntime.Start(); Assert.IsTrue(MyComponent.IsInit); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs index 1a7668d755..176093cb59 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoBuilderExtensions.cs @@ -1,6 +1,7 @@ using System; using Umbraco.Core.Cache; using Umbraco.Core.Composing.LightInject; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Runtime; using Umbraco.Extensions; using Umbraco.Tests.Integration.Implementations; @@ -16,40 +17,42 @@ namespace Umbraco.Tests.Integration.TestServerTest /// /// /// - public static IUmbracoBuilder WithTestCore(this IUmbracoBuilder builder, TestHelper testHelper, LightInjectContainer container, + public static IUmbracoBuilder WithTestCore(this IUmbracoBuilder builder, TestHelper testHelper, + LightInjectContainer container, Action dbInstallEventHandler) { return builder.AddWith(nameof(global::Umbraco.Web.Common.Builder.UmbracoBuilderExtensions.WithCore), - () => - { - builder.Services.AddUmbracoCore( - builder.WebHostEnvironment, - container, - typeof(UmbracoBuilderExtensions).Assembly, - AppCaches.NoCache, // Disable caches in integration tests - testHelper.GetLoggingConfiguration(), - // TODO: Yep that's extremely ugly - (configs, umbVersion, ioHelper, logger, factory, profiler, hostingEnv, backOfficeInfo, typeFinder, appCaches, dbProviderFactoryCreator) => - { - var runtime = UmbracoIntegrationTest.CreateTestRuntime( - configs, - umbVersion, - ioHelper, - logger, - factory, - profiler, - hostingEnv, - backOfficeInfo, - typeFinder, - appCaches, - dbProviderFactoryCreator, - testHelper.MainDom, // SimpleMainDom - dbInstallEventHandler); // DB Installation event handler + () => + { + builder.Services.AddUmbracoCore( + builder.WebHostEnvironment, + container, + typeof(UmbracoBuilderExtensions).Assembly, + AppCaches.NoCache, // Disable caches in integration tests + testHelper.GetLoggingConfiguration(), + (globalSettings, connectionStrings, umbVersion, ioHelper, logger, factory, profiler, hostingEnv, + backOfficeInfo, typeFinder, appCaches, dbProviderFactoryCreator) => + { + var runtime = UmbracoIntegrationTest.CreateTestRuntime( + globalSettings, + connectionStrings, + umbVersion, + ioHelper, + logger, + factory, + profiler, + hostingEnv, + backOfficeInfo, + typeFinder, + appCaches, + dbProviderFactoryCreator, + testHelper.MainDom, // SimpleMainDom + dbInstallEventHandler); // DB Installation event handler - return runtime; - }, - out _); - }); + return runtime; + }, + out _); + }); } } } diff --git a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs index 7beebdcf83..48f0146272 100644 --- a/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs +++ b/src/Umbraco.Tests.Integration/Testing/IntegrationTestComposer.cs @@ -4,10 +4,12 @@ using System; using System.IO; using System.Linq; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -59,7 +61,7 @@ namespace Umbraco.Tests.Integration.Testing /// private ILocalizedTextService GetLocalizedTextService(IFactory factory) { - var configs = factory.GetInstance(); + var globalSettings = factory.GetInstance>(); var logger = factory.GetInstance(); var appCaches = factory.GetInstance(); @@ -73,7 +75,7 @@ namespace Umbraco.Tests.Integration.Testing currFolder = currFolder.Parent; } var netcoreUI = currFolder.GetDirectories("Umbraco.Web.UI.NetCore", SearchOption.TopDirectoryOnly).First(); - var mainLangFolder = new DirectoryInfo(Path.Combine(netcoreUI.FullName, configs.Global().UmbracoPath.TrimStart("~/"), "config", "lang")); + var mainLangFolder = new DirectoryInfo(Path.Combine(netcoreUI.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang")); return new LocalizedTextServiceFileSources( logger, diff --git a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs index 3d106e2135..10f8621b1a 100644 --- a/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs +++ b/src/Umbraco.Tests.Integration/Testing/LocalDbTestDatabase.cs @@ -11,6 +11,7 @@ using System.Threading; using Microsoft.Extensions.Logging; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; @@ -25,7 +26,6 @@ namespace Umbraco.Tests.Integration.Testing public const string DatabaseName = "UmbracoTests"; private readonly ILoggerFactory _loggerFactory; - private readonly IGlobalSettings _globalSettings; private readonly LocalDb _localDb; private readonly IUmbracoVersion _umbracoVersion; private static LocalDb.Instance _instance; @@ -38,11 +38,10 @@ namespace Umbraco.Tests.Integration.Testing private DatabasePool _currentPool; //It's internal because `Umbraco.Core.Persistence.LocalDb` is internal - internal LocalDbTestDatabase(ILoggerFactory loggerFactory, IGlobalSettings globalSettings, LocalDb localDb, string filesPath, IUmbracoDatabaseFactory dbFactory) + internal LocalDbTestDatabase(ILoggerFactory loggerFactory, LocalDb localDb, string filesPath, IUmbracoDatabaseFactory dbFactory) { _umbracoVersion = new UmbracoVersion(); _loggerFactory = loggerFactory; - _globalSettings = globalSettings; _localDb = localDb; _filesPath = filesPath; _dbFactory = dbFactory; @@ -130,7 +129,7 @@ namespace Umbraco.Tests.Integration.Testing using var trans = database.GetTransaction(); - var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion, _globalSettings); + var creator = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); creator.InitializeDatabaseSchema(); trans.Complete(); // commit it diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs index 7ea5d284dc..c00c2dde81 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs @@ -28,7 +28,10 @@ using Microsoft.Extensions.Configuration; using System.Data.SqlClient; using System.Data.Common; using System.IO; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Umbraco.Tests.Integration.Testing @@ -85,6 +88,8 @@ namespace Umbraco.Tests.Integration.Testing Services = host.Services; var app = new ApplicationBuilder(host.Services); Configure(app); + + OnFixtureTearDown(() => host.Dispose()); } #region Generic Host Builder and Runtime @@ -121,7 +126,7 @@ namespace Umbraco.Tests.Integration.Testing /// /// Creates a instance for testing and registers an event handler for database install /// - /// + /// /// /// /// @@ -132,12 +137,18 @@ namespace Umbraco.Tests.Integration.Testing /// /// /// + /// /// - public CoreRuntime CreateTestRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, + public CoreRuntime CreateTestRuntime( + GlobalSettings globalSettings, + ConnectionStrings connectionStrings, + IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, Core.Hosting.IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo, ITypeFinder typeFinder, AppCaches appCaches, IDbProviderFactoryCreator dbProviderFactoryCreator) { - var runtime = CreateTestRuntime(configs, + var runtime = CreateTestRuntime( + globalSettings, + connectionStrings, umbracoVersion, ioHelper, logger, @@ -158,7 +169,7 @@ namespace Umbraco.Tests.Integration.Testing /// /// Creates a instance for testing and registers an event handler for database install /// - /// + /// /// /// /// @@ -171,14 +182,19 @@ namespace Umbraco.Tests.Integration.Testing /// /// /// The event handler used for DB installation + /// /// - public static CoreRuntime CreateTestRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, + public static CoreRuntime CreateTestRuntime( + GlobalSettings globalSettings, + ConnectionStrings connectionStrings, + IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, Core.Hosting.IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo, ITypeFinder typeFinder, AppCaches appCaches, IDbProviderFactoryCreator dbProviderFactoryCreator, IMainDom mainDom, Action eventHandler) { var runtime = new CoreRuntime( - configs, + globalSettings, + connectionStrings, umbracoVersion, ioHelper, logger, @@ -262,7 +278,7 @@ namespace Umbraco.Tests.Integration.Testing OnTestTearDown(() => runtime.Terminate()); // This will create a db, install the schema and ensure the app is configured to run - InstallTestLocalDb(args.DatabaseFactory, runtime.RuntimeLoggerFactory, runtime.Configs.Global(), runtime.State, TestHelper.WorkingDirectory, out var connectionString); + InstallTestLocalDb(args.DatabaseFactory, runtime.RuntimeLoggerFactory, runtime.State, TestHelper.WorkingDirectory, out var connectionString); TestDBConnectionString = connectionString; InMemoryConfiguration["ConnectionStrings:" + Constants.System.UmbracoConnectionName] = TestDBConnectionString; } @@ -279,7 +295,7 @@ namespace Umbraco.Tests.Integration.Testing /// /// There must only be ONE instance shared between all tests in a session /// - private static LocalDbTestDatabase GetOrCreateDatabase(string filesPath, ILoggerFactory loggerFactory, IGlobalSettings globalSettings, IUmbracoDatabaseFactory dbFactory) + private static LocalDbTestDatabase GetOrCreateDatabase(string filesPath, ILoggerFactory loggerFactory, IUmbracoDatabaseFactory dbFactory) { lock (_dbLocker) { @@ -288,7 +304,7 @@ namespace Umbraco.Tests.Integration.Testing var localDb = new LocalDb(); if (localDb.IsAvailable == false) throw new InvalidOperationException("LocalDB is not available."); - _dbInstance = new LocalDbTestDatabase(loggerFactory, globalSettings, localDb, filesPath, dbFactory); + _dbInstance = new LocalDbTestDatabase(loggerFactory, localDb, filesPath, dbFactory); return _dbInstance; } } @@ -304,7 +320,7 @@ namespace Umbraco.Tests.Integration.Testing /// /// private void InstallTestLocalDb( - IUmbracoDatabaseFactory databaseFactory, ILoggerFactory loggerFactory, IGlobalSettings globalSettings, + IUmbracoDatabaseFactory databaseFactory, ILoggerFactory loggerFactory, IRuntimeState runtimeState, string workingDirectory, out string connectionString) { connectionString = null; @@ -322,7 +338,7 @@ namespace Umbraco.Tests.Integration.Testing if (!Directory.Exists(dbFilePath)) Directory.CreateDirectory(dbFilePath); - var db = GetOrCreateDatabase(dbFilePath, loggerFactory, globalSettings, databaseFactory); + var db = GetOrCreateDatabase(dbFilePath, loggerFactory, databaseFactory); switch (testOptions.Database) { @@ -425,7 +441,7 @@ namespace Umbraco.Tests.Integration.Testing protected AppCaches AppCaches => Services.GetRequiredService(); protected IIOHelper IOHelper => Services.GetRequiredService(); protected IShortStringHelper ShortStringHelper => Services.GetRequiredService(); - protected IGlobalSettings GlobalSettings => Services.GetRequiredService(); + protected GlobalSettings GlobalSettings => Services.GetRequiredService>().Value; protected IMapperCollection Mappers => Services.GetRequiredService(); #endregion diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementDefaultTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementDefaultTests.cs deleted file mode 100644 index 436fb45377..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementDefaultTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Linq; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class ContentElementDefaultTests : ContentElementTests - { - protected override bool TestingDefaults => true; - - [Test] - public override void DisableHtmlEmail() - { - Assert.IsTrue(ContentSettings.DisableHtmlEmail == false); - } - - [Test] - public override void Can_Set_Multiple() - { - Assert.IsTrue(ContentSettings.Error404Collection.Count() == 1); - Assert.IsTrue(ContentSettings.Error404Collection.ElementAt(0).Culture == null); - Assert.IsTrue(ContentSettings.Error404Collection.ElementAt(0).ContentId == 1); - } - - [Test] - public override void ImageAutoFillProperties() - { - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.Count() == 1); - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.ElementAt(0).Alias == "umbracoFile"); - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias == "umbracoWidth"); - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias == "umbracoHeight"); - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias == "umbracoBytes"); - Assert.IsTrue(ContentSettings.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias == "umbracoExtension"); - } - - /// - /// Whitelist is empty in default settings file and is not populated by default, but disallowed is empty and is populated by default - /// - /// - /// - [Test] - [TestCase("png", true)] - [TestCase("jpg", true)] - [TestCase("gif", true)] - [TestCase("bmp", true)] - [TestCase("php", true)] - [TestCase("ashx", false)] - [TestCase("config", false)] - [TestCase("test", true)] - public override void IsFileAllowedForUpload_WithWhitelist(string extension, bool expected) - { - Console.WriteLine("Extension being tested: {0}", extension); - Console.WriteLine("Expected IsAllowed?: {0}", expected); - Console.WriteLine("AllowedUploadFiles: {0}", ContentSettings.AllowedUploadFiles); - Console.WriteLine("DisallowedUploadFiles: {0}", ContentSettings.DisallowedUploadFiles); - - bool allowedContainsExtension = ContentSettings.AllowedUploadFiles.Any(x => x.InvariantEquals(extension)); - bool disallowedContainsExtension = ContentSettings.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension)); - - Console.WriteLine("AllowedContainsExtension: {0}", allowedContainsExtension); - Console.WriteLine("DisallowedContainsExtension: {0}", disallowedContainsExtension); - - Assert.AreEqual(expected, ContentSettings.IsFileAllowedForUpload(extension)); - } - - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementTests.cs deleted file mode 100644 index 21fd59de3a..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/ContentElementTests.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Macros; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class ContentElementTests : UmbracoSettingsTests - { - [Test] - public void EmailAddress() - { - Assert.AreEqual(ContentSettings.NotificationEmailAddress, "robot@umbraco.dk"); - } - [Test] - public virtual void DisableHtmlEmail() - { - Assert.IsTrue(ContentSettings.DisableHtmlEmail); - } - - [Test] - public virtual void Can_Set_Multiple() - { - Assert.AreEqual(3, ContentSettings.Error404Collection.Count()); - Assert.AreEqual("default", ContentSettings.Error404Collection.ElementAt(0).Culture); - Assert.AreEqual(1047, ContentSettings.Error404Collection.ElementAt(0).ContentId); - Assert.IsTrue(ContentSettings.Error404Collection.ElementAt(0).HasContentId); - Assert.IsFalse(ContentSettings.Error404Collection.ElementAt(0).HasContentKey); - Assert.AreEqual("en-US", ContentSettings.Error404Collection.ElementAt(1).Culture); - Assert.AreEqual("$site/error [@name = 'error']", ContentSettings.Error404Collection.ElementAt(1).ContentXPath); - Assert.IsFalse(ContentSettings.Error404Collection.ElementAt(1).HasContentId); - Assert.IsFalse(ContentSettings.Error404Collection.ElementAt(1).HasContentKey); - Assert.AreEqual("en-UK", ContentSettings.Error404Collection.ElementAt(2).Culture); - Assert.AreEqual(new Guid("8560867F-B88F-4C74-A9A4-679D8E5B3BFC"), ContentSettings.Error404Collection.ElementAt(2).ContentKey); - Assert.IsTrue(ContentSettings.Error404Collection.ElementAt(2).HasContentKey); - Assert.IsFalse(ContentSettings.Error404Collection.ElementAt(2).HasContentId); - } - - [Test] - public void ImageFileTypes() - { - Assert.IsTrue(ContentSettings.ImageFileTypes.All(x => "jpeg,jpg,gif,bmp,png,tiff,tif".Split(',').Contains(x))); - } - - [Test] - public virtual void ImageAutoFillProperties() - { - Assert.AreEqual(2, ContentSettings.ImageAutoFillProperties.Count()); - Assert.AreEqual("umbracoFile", ContentSettings.ImageAutoFillProperties.ElementAt(0).Alias); - Assert.AreEqual("umbracoWidth", ContentSettings.ImageAutoFillProperties.ElementAt(0).WidthFieldAlias); - Assert.AreEqual("umbracoHeight", ContentSettings.ImageAutoFillProperties.ElementAt(0).HeightFieldAlias); - Assert.AreEqual("umbracoBytes", ContentSettings.ImageAutoFillProperties.ElementAt(0).LengthFieldAlias); - Assert.AreEqual("umbracoExtension", ContentSettings.ImageAutoFillProperties.ElementAt(0).ExtensionFieldAlias); - Assert.AreEqual("umbracoFile2", ContentSettings.ImageAutoFillProperties.ElementAt(1).Alias); - Assert.AreEqual("umbracoWidth2", ContentSettings.ImageAutoFillProperties.ElementAt(1).WidthFieldAlias); - Assert.AreEqual("umbracoHeight2", ContentSettings.ImageAutoFillProperties.ElementAt(1).HeightFieldAlias); - Assert.AreEqual("umbracoBytes2", ContentSettings.ImageAutoFillProperties.ElementAt(1).LengthFieldAlias); - Assert.AreEqual("umbracoExtension2", ContentSettings.ImageAutoFillProperties.ElementAt(1).ExtensionFieldAlias); - } - - [Test] - public void PreviewBadge() - { - Assert.AreEqual(ContentSettings.PreviewBadge, @"
Preview modeClick to end
"); - } - [Test] - public void ResolveUrlsFromTextString() - { - Assert.IsFalse(ContentSettings.ResolveUrlsFromTextString); - } - [Test] - public void MacroErrors() - { - Assert.AreEqual(ContentSettings.MacroErrorBehaviour, MacroErrorBehaviour.Inline); - } - - [Test] - public void DisallowedUploadFiles() - { - Assert.IsTrue(ContentSettings.DisallowedUploadFiles.All(x => "ashx,aspx,ascx,config,cshtml,vbhtml,asmx,air,axd".Split(',').Contains(x))); - } - - [Test] - public void AllowedUploadFiles() - { - Assert.IsTrue(ContentSettings.AllowedUploadFiles.All(x => "jpg,gif,png".Split(',').Contains(x))); - } - - [Test] - [TestCase("png", true)] - [TestCase("jpg", true)] - [TestCase("gif", true)] - [TestCase("bmp", false)] - [TestCase("php", false)] - [TestCase("ashx", false)] - [TestCase("config", false)] - [TestCase("test", false)] - public virtual void IsFileAllowedForUpload_WithWhitelist(string extension, bool expected) - { - Console.WriteLine("Extension being tested: {0}", extension); - Console.WriteLine("Expected IsAllowed?: {0}", expected); - Console.WriteLine("AllowedUploadFiles: {0}", ContentSettings.AllowedUploadFiles); - Console.WriteLine("DisallowedUploadFiles: {0}", ContentSettings.DisallowedUploadFiles); - - bool allowedContainsExtension = ContentSettings.AllowedUploadFiles.Any(x => x.InvariantEquals(extension)); - bool disallowedContainsExtension = ContentSettings.DisallowedUploadFiles.Any(x => x.InvariantEquals(extension)); - - Console.WriteLine("AllowedContainsExtension: {0}", allowedContainsExtension); - Console.WriteLine("DisallowedContainsExtension: {0}", disallowedContainsExtension); - - Assert.AreEqual(expected, ContentSettings.IsFileAllowedForUpload(extension)); - } - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementDefaultTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementDefaultTests.cs deleted file mode 100644 index 084c649f11..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementDefaultTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class LoggingElementDefaultTests : LoggingElementTests - { - protected override bool TestingDefaults => true; - - [Test] - public override void MaxLogAge() - { - Assert.IsTrue(LoggingSettings.MaxLogAge == -1); - } - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementTests.cs deleted file mode 100644 index 3fd8041540..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/LoggingElementTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class LoggingElementTests : UmbracoSettingsTests - { - - [Test] - public virtual void MaxLogAge() - { - Assert.IsTrue(LoggingSettings.MaxLogAge == 1440); - - } - - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementDefaultTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementDefaultTests.cs deleted file mode 100644 index c2e21c5e2c..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementDefaultTests.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class RequestHandlerElementDefaultTests : RequestHandlerElementTests - { - protected override bool TestingDefaults => true; - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementTests.cs deleted file mode 100644 index 01a2b48e16..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/RequestHandlerElementTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Linq; -using NUnit.Framework; -using Umbraco.Core; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class RequestHandlerElementTests : UmbracoSettingsTests - { - [Test] - public void AddTrailingSlash() - { - Assert.IsTrue(RequestHandlerSettings.AddTrailingSlash == true); - } - - [Test] - public void CharCollection() - { - var chars = @" ,"",',%,.,;,/,\,:,#,+,*,&,?,æ,ø,å,ä,ö,ü,ß,Ä,Ö,|,<,>"; - var items = chars.Split(','); - Assert.AreEqual(items.Length, RequestHandlerSettings.CharCollection.Count()); - Assert.IsTrue(RequestHandlerSettings.CharCollection - .All(x => items.Contains(x.Char))); - - var vals = @"-,plus,star,ae,oe,aa,ae,oe,ue,ss,ae,oe,-"; - var splitVals = vals.Split(','); - Assert.AreEqual(splitVals.Length, RequestHandlerSettings.CharCollection.Count(x => x.Replacement.IsNullOrWhiteSpace() == false)); - Assert.IsTrue(RequestHandlerSettings.CharCollection - .All(x => string.IsNullOrEmpty(x.Replacement) || vals.Split(',').Contains(x.Replacement))); - } - - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementDefaultTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementDefaultTests.cs deleted file mode 100644 index f5566df5ed..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementDefaultTests.cs +++ /dev/null @@ -1,10 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class SecurityElementDefaultTests : SecurityElementTests - { - protected override bool TestingDefaults => true; - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementTests.cs deleted file mode 100644 index 6a8fc854d7..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/SecurityElementTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -using NUnit.Framework; -using Umbraco.Core; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class SecurityElementTests : UmbracoSettingsTests - { - [Test] - public void KeepUserLoggedIn() - { - Assert.IsTrue(SecuritySettings.KeepUserLoggedIn == true); - } - - [Test] - public void HideDisabledUsersInBackoffice() - { - Assert.IsTrue(SecuritySettings.HideDisabledUsersInBackoffice == false); - } - - [Test] - public void AllowPasswordReset() - { - Assert.IsTrue(SecuritySettings.AllowPasswordReset == true); - } - - [Test] - public void AuthCookieDomain() - { - Assert.IsTrue(SecuritySettings.AuthCookieDomain == null); - } - - [Test] - public void AuthCookieName() - { - Assert.IsTrue(SecuritySettings.AuthCookieName == "UMB_UCONTEXT"); - } - - [Test] - public void UserPasswordConfiguration_RequiredLength() - { - Assert.IsTrue(UserPasswordConfiguration.RequiredLength == 12); - } - - [Test] - public void UserPasswordConfiguration_RequireNonLetterOrDigit() - { - Assert.IsTrue(UserPasswordConfiguration.RequireNonLetterOrDigit == false); - } - - [Test] - public void UserPasswordConfiguration_RequireDigit() - { - Assert.IsTrue(UserPasswordConfiguration.RequireDigit == false); - } - - [Test] - public void UserPasswordConfiguration_RequireLowercase() - { - Assert.IsTrue(UserPasswordConfiguration.RequireLowercase == false); - } - - [Test] - public void UserPasswordConfiguration_RequireUppercase() - { - Assert.IsTrue(UserPasswordConfiguration.RequireUppercase == false); - } - - [Test] - public void UserPasswordConfiguration_HashAlgorithmType() - { - Assert.AreEqual(Constants.Security.AspNetCoreV3PasswordHashAlgorithmName, UserPasswordConfiguration.HashAlgorithmType); - } - - [Test] - public void UserPasswordConfiguration_MaxFailedAccessAttemptsBeforeLockout() - { - Assert.IsTrue(UserPasswordConfiguration.MaxFailedAccessAttemptsBeforeLockout == 5); - } - - [Test] - public void MemberPasswordConfiguration_RequiredLength() - { - Assert.IsTrue(MemberPasswordConfiguration.RequiredLength == 12); - } - - [Test] - public void MemberPasswordConfiguration_RequireNonLetterOrDigit() - { - Assert.IsTrue(MemberPasswordConfiguration.RequireNonLetterOrDigit == false); - } - - [Test] - public void MemberPasswordConfiguration_RequireDigit() - { - Assert.IsTrue(MemberPasswordConfiguration.RequireDigit == false); - } - - [Test] - public void MemberPasswordConfiguration_RequireLowercase() - { - Assert.IsTrue(MemberPasswordConfiguration.RequireLowercase == false); - } - - [Test] - public void MemberPasswordConfiguration_RequireUppercase() - { - Assert.IsTrue(MemberPasswordConfiguration.RequireUppercase == false); - } - - [Test] - public void MemberPasswordConfiguration_HashAlgorithmType() - { - Assert.AreEqual(Constants.Security.AspNetCoreV3PasswordHashAlgorithmName, MemberPasswordConfiguration.HashAlgorithmType); - } - - [Test] - public void MemberPasswordConfiguration_MaxFailedAccessAttemptsBeforeLockout() - { - Assert.IsTrue(MemberPasswordConfiguration.MaxFailedAccessAttemptsBeforeLockout == 5); - } - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsTests.cs deleted file mode 100644 index e869a972f5..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/UmbracoSettingsTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Configuration; -using System.Diagnostics; -using System.IO; -using NUnit.Framework; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Tests.Integration.Implementations; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - public abstract class UmbracoSettingsTests - { - protected virtual bool TestingDefaults { get; set; } - - [SetUp] - public void Init() - { - var testHelper = new TestHelper(); - var config = new FileInfo(testHelper.MapPathForTestFiles("~/Umbraco.Configuration/Configurations/web.config")); - - var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = config.FullName }; - var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); - - Debug.WriteLine("Testing defaults? {0}", TestingDefaults); - if (TestingDefaults) - { - Settings = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection; - } - else - { - Settings = configuration.GetSection("umbracoConfiguration/settings") as UmbracoSettingsSection; - } - - Assert.IsNotNull(Settings); - } - private UmbracoSettingsSection Settings { get; set; } - - protected ILoggingSettings LoggingSettings => Settings.Logging; - protected IWebRoutingSettings WebRoutingSettings => Settings.WebRouting; - protected IRequestHandlerSettings RequestHandlerSettings => Settings.RequestHandler; - protected ISecuritySettings SecuritySettings => Settings.Security; - protected IUserPasswordConfiguration UserPasswordConfiguration => Settings.Security.UserPasswordConfiguration; - protected IMemberPasswordConfiguration MemberPasswordConfiguration => Settings.Security.MemberPasswordConfiguration; - protected IContentSettings ContentSettings => Settings.Content; - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementDefaultTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementDefaultTests.cs deleted file mode 100644 index e85911d559..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementDefaultTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class WebRoutingElementDefaultTests : WebRoutingElementTests - { - protected override bool TestingDefaults => true; - - [Test] - public override void UrlProviderMode() - { - Assert.IsTrue(WebRoutingSettings.UrlProviderMode == "Auto"); - } - - [Test] - public void DisableAlternativeTemplates() - { - Assert.IsTrue(WebRoutingSettings.DisableAlternativeTemplates == false); - } - - [Test] - public void ValidateAlternativeTemplates() - { - Assert.IsTrue(WebRoutingSettings.ValidateAlternativeTemplates == false); - } - - [Test] - public void DisableFindContentByIdPath() - { - Assert.IsTrue(WebRoutingSettings.DisableFindContentByIdPath == false); - } - - [Test] - public void DisableRedirectUrlTracking() - { - Assert.IsTrue(WebRoutingSettings.DisableRedirectUrlTracking == false); - } - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementTests.cs deleted file mode 100644 index 532b27494f..0000000000 --- a/src/Umbraco.Tests.Integration/Umbraco.Configuration/UmbracoSettings/WebRoutingElementTests.cs +++ /dev/null @@ -1,26 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Integration.Umbraco.Configuration.UmbracoSettings -{ - [TestFixture] - public class WebRoutingElementTests : UmbracoSettingsTests - { - [Test] - public void TrySkipIisCustomErrors() - { - Assert.IsTrue(WebRoutingSettings.TrySkipIisCustomErrors == false); - } - - [Test] - public void InternalRedirectPreservesTemplate() - { - Assert.IsTrue(WebRoutingSettings.InternalRedirectPreservesTemplate == false); - } - - [Test] - public virtual void UrlProviderMode() - { - Assert.IsTrue(WebRoutingSettings.UrlProviderMode == "Auto"); - } - } -} diff --git a/src/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj b/src/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj index 635c4591cb..92abedd26e 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj +++ b/src/Umbraco.Tests.Integration/Umbraco.Tests.Integration.csproj @@ -11,6 +11,9 @@ + + +
diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice.Security/BackOfficeCookieManagerTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice.Security/BackOfficeCookieManagerTests.cs index 3464259052..6fd5672085 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice.Security/BackOfficeCookieManagerTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice.Security/BackOfficeCookieManagerTests.cs @@ -9,6 +9,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Hosting; using Umbraco.Extensions; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Integration.Implementations; using Umbraco.Web; using Umbraco.Web.BackOffice.Controllers; @@ -25,7 +26,7 @@ namespace Umbraco.Tests.Security var testHelper = new TestHelper(); var httpContextAccessor = testHelper.GetHttpContextAccessor(); - var globalSettings = testHelper.SettingsForTests.GenerateMockGlobalSettings(); + var globalSettings = new GlobalSettingsBuilder().Build(); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); var mgr = new BackOfficeCookieManager( @@ -50,8 +51,8 @@ namespace Umbraco.Tests.Security //hostingEnvironment.ToAbsolute(globalSettings.UmbracoPath); var httpContextAccessor = testHelper.GetHttpContextAccessor(); - var globalSettings = testHelper.SettingsForTests.GenerateMockGlobalSettings(); - + var globalSettings = new GlobalSettingsBuilder().Build(); + var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); var mgr = new BackOfficeCookieManager( Mock.Of(), @@ -72,7 +73,7 @@ namespace Umbraco.Tests.Security var testHelper = new TestHelper(); var httpContextAccessor = testHelper.GetHttpContextAccessor(); - var globalSettings = testHelper.SettingsForTests.GenerateMockGlobalSettings(); + var globalSettings = new GlobalSettingsBuilder().Build(); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); @@ -97,7 +98,7 @@ namespace Umbraco.Tests.Security var testHelper = new TestHelper(); var httpContextAccessor = testHelper.GetHttpContextAccessor(); - var globalSettings = testHelper.SettingsForTests.GenerateMockGlobalSettings(); + var globalSettings = new GlobalSettingsBuilder().Build(); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); @@ -119,7 +120,7 @@ namespace Umbraco.Tests.Security var testHelper = new TestHelper(); var httpContextAccessor = testHelper.GetHttpContextAccessor(); - var globalSettings = testHelper.SettingsForTests.GenerateMockGlobalSettings(); + var globalSettings = new GlobalSettingsBuilder().Build(); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); diff --git a/src/Umbraco.Tests.Integration/Views/template1.cshtml b/src/Umbraco.Tests.Integration/Views/template1.cshtml deleted file mode 100644 index 3fa17ab54c..0000000000 --- a/src/Umbraco.Tests.Integration/Views/template1.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage -@{ - Layout = null; -} \ No newline at end of file diff --git a/src/Umbraco.Tests.Integration/Views/template2.cshtml b/src/Umbraco.Tests.Integration/Views/template2.cshtml deleted file mode 100644 index 3fa17ab54c..0000000000 --- a/src/Umbraco.Tests.Integration/Views/template2.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage -@{ - Layout = null; -} \ No newline at end of file diff --git a/src/Umbraco.Tests.Integration/Views/test.cshtml b/src/Umbraco.Tests.Integration/Views/test.cshtml deleted file mode 100644 index 3fa17ab54c..0000000000 --- a/src/Umbraco.Tests.Integration/Views/test.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@inherits Umbraco.Web.Common.AspNetCore.UmbracoViewPage -@{ - Layout = null; -} \ No newline at end of file diff --git a/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs b/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs index 625e1ca619..c2ef2b4f04 100644 --- a/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs +++ b/src/Umbraco.Tests.UnitTests/AutoFixture/AutoMoqDataAttribute.cs @@ -1,14 +1,19 @@ using System; +using System.Linq; +using System.Reflection; using AutoFixture; using AutoFixture.AutoMoq; using AutoFixture.Kernel; using AutoFixture.NUnit3; using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; using Moq; +using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Tests.Common.Builders; using Umbraco.Web.BackOffice.Controllers; -using Umbraco.Core; using Umbraco.Web.Common.Install; namespace Umbraco.Tests.UnitTests.AutoFixture @@ -35,15 +40,15 @@ namespace Umbraco.Tests.UnitTests.AutoFixture { fixture.Customize( u => u.FromFactory( - (a,b,c) => BackOfficeIdentityUser.CreateNew(Mock.Of(),a,b,c))); + (a,b,c) => BackOfficeIdentityUser.CreateNew(new GlobalSettingsBuilder().Build(),a,b,c))); fixture .Customize(new ConstructorCustomization(typeof(UsersController), new GreedyConstructorQuery())) .Customize(new ConstructorCustomization(typeof(InstallController), new GreedyConstructorQuery())) .Customize(new ConstructorCustomization(typeof(PreviewController), new GreedyConstructorQuery())) .Customize(new ConstructorCustomization(typeof(BackOfficeController), new GreedyConstructorQuery())) - .Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery())) - .Customize(new AutoMoqCustomization()); + .Customize(new ConstructorCustomization(typeof(BackOfficeUserManager), new GreedyConstructorQuery())); + fixture.Customize(new AutoMoqCustomization()); // When requesting an IUserStore ensure we actually uses a IUserLockoutStore fixture.Customize>(cc => cc.FromFactory(() => Mock.Of>())); @@ -55,9 +60,9 @@ namespace Umbraco.Tests.UnitTests.AutoFixture u => u.FromFactory( () => new UmbracoVersion())); - var connectionStrings = Mock.Of(); - Mock.Get(connectionStrings).Setup(x => x[Constants.System.UmbracoConnectionName]).Returns((ConfigConnectionString)new ConfigConnectionString(string.Empty, string.Empty, string.Empty)); - fixture.Customize(x => x.FromFactory(() => connectionStrings )); + var connectionStrings = new ConnectionStrings(); + fixture.Customize(x => x.FromFactory(() => connectionStrings )); + diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs index c5acba362b..544765ee9c 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Configuration/Models/ConnectionStringsTests.cs @@ -1,8 +1,7 @@ -using Microsoft.Extensions.Configuration; -using Moq; -using NUnit.Framework; -using Umbraco.Configuration.Models; +using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Tests.UnitTests.Umbraco.Configuration.Models { @@ -15,25 +14,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Configuration.Models [TestCase(@"Server=(LocalDb)\Umbraco;Database=NetCore;Integrated Security=true", ExpectedResult = Constants.DbProviderNames.SqlServer)] public string ParseProviderName(string connectionString) { - var key = Constants.System.UmbracoConnectionName; - var configuration = new Mock(); - - - //This is the underlying method that is called by Configuration.GetConnectionString(string) - if (connectionString != null) + var connectionStrings = new ConnectionStrings { - configuration.Setup(x => x.GetSection("ConnectionStrings")[key]).Returns(connectionString); - } + UmbracoConnectionString = new ConfigConnectionString(Constants.System.UmbracoConnectionName, connectionString) + }; - - var connectionStrings = new ConnectionStrings(configuration.Object); - - var actual = connectionStrings[key]; + var actual = connectionStrings.UmbracoConnectionString; Assert.AreEqual(connectionString, actual.ConnectionString); - Assert.AreEqual(key, actual.Name); + Assert.AreEqual(Constants.System.UmbracoConnectionName, actual.Name); - return connectionStrings[key].ProviderName; + return connectionStrings.UmbracoConnectionString.ProviderName; } } } diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs index 87cff07475..7d977fe686 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/BackOffice/BackOfficeClaimsPrincipalFactoryTests.cs @@ -11,6 +11,7 @@ using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; using Umbraco.Core.Models.Membership; using Umbraco.Extensions; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice { @@ -137,10 +138,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.BackOffice [SetUp] public void Setup() { - var mockGlobalSettings = new Mock(); - mockGlobalSettings.Setup(x => x.DefaultUILanguage).Returns("test"); + var globalSettings = new GlobalSettingsBuilder().WithDefaultUiLanguage("test").Build(); - _testUser = new BackOfficeIdentityUser(mockGlobalSettings.Object, _testUserId, new List()) + _testUser = new BackOfficeIdentityUser(globalSettings, _testUserId, new List()) { UserName = _testUserName, Name = _testUserGivenName, diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs index 4c8903735a..77a7ba1732 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Extensions/UriExtensionsTests.cs @@ -1,11 +1,12 @@ using System; -using System.Reflection; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Web.Common.AspNetCore; namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions @@ -16,14 +17,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions [OneTimeSetUp] public void Setup() { - _settingsForTests = new SettingsForTests(); _hostEnvironment = Mock.Of(); - _globalSettings = _settingsForTests.GenerateMockGlobalSettings(); + _globalSettings = new GlobalSettingsBuilder().Build(); } - private SettingsForTests _settingsForTests; private IWebHostEnvironment _hostEnvironment; - private IGlobalSettings _globalSettings; + private GlobalSettings _globalSettings; [TestCase("http://www.domain.com/umbraco/preview/frame?id=1234", "", true)] [TestCase("http://www.domain.com/umbraco", "", true)] @@ -47,12 +46,8 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions [TestCase("http://www.domain.com/umbraco/test/legacyAjaxCalls.ashx?some=query&blah=js", "", true)] public void Is_Back_Office_Request(string input, string virtualPath, bool expected) { - - var mockHostingSettings = Mock.Get(_settingsForTests.GenerateMockHostingSettings()); - mockHostingSettings.Setup(x => x.ApplicationVirtualPath).Returns(virtualPath); - var hostingEnvironment = new AspNetCoreHostingEnvironment(mockHostingSettings.Object, _hostEnvironment); - var source = new Uri(input); + var hostingEnvironment = CreateHostingEnvironment(virtualPath); Assert.AreEqual(expected, source.IsBackOfficeRequest(_globalSettings, hostingEnvironment)); } @@ -68,11 +63,17 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Extensions public void Is_Installer_Request(string input, bool expected) { var source = new Uri(input); - var mockHostingSettings = Mock.Get(_settingsForTests.GenerateMockHostingSettings()); - var hostingEnvironment = new AspNetCoreHostingEnvironment(mockHostingSettings.Object, _hostEnvironment); + var hostingEnvironment = CreateHostingEnvironment(); Assert.AreEqual(expected, source.IsInstallerRequest(hostingEnvironment)); } + private AspNetCoreHostingEnvironment CreateHostingEnvironment(string virtualPath = "") + { + var hostingSettings = new HostingSettingsBuilder().WithApplicationVirtualPath(virtualPath).Build(); + var mockedOptionsMonitorOfHostingSettings = Mock.Of>(x => x.CurrentValue == hostingSettings); + return new AspNetCoreHostingEnvironment(mockedOptionsMonitorOfHostingSettings, _hostEnvironment); + } + [TestCase("http://www.domain.com/foo/bar", "/", "http://www.domain.com/")] [TestCase("http://www.domain.com/foo/bar#hop", "/", "http://www.domain.com/")] [TestCase("http://www.domain.com/foo/bar?q=2#hop", "/", "http://www.domain.com/?q=2")] diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs index 15a9599674..7a2a4c5965 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/UriUtilityTests.cs @@ -4,6 +4,7 @@ using NUnit.Framework; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; +using Umbraco.Tests.Common.Builders; using Umbraco.Web; namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing @@ -70,12 +71,11 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Core.Routing { // Arrange var sourceUri = new Uri(sourceUrl, UriKind.Relative); - var mockRequestHandlerSettings = new Mock(); - mockRequestHandlerSettings.Setup(x => x.AddTrailingSlash).Returns(trailingSlash); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(trailingSlash).Build(); var uriUtility = BuildUriUtility("/"); // Act - var resultUri = uriUtility.UriFromUmbraco(sourceUri, Mock.Of(), mockRequestHandlerSettings.Object); + var resultUri = uriUtility.UriFromUmbraco(sourceUri, requestHandlerSettings); // Assert var expectedUri = new Uri(expectedUrl, UriKind.Relative); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ConnectionStringsBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ConnectionStringsBuilderTests.cs new file mode 100644 index 0000000000..7a95df708e --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/ConnectionStringsBuilderTests.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; +using Umbraco.Tests.Common.Builders; + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +{ + [TestFixture] + public class ConnectionStringsBuilderTests + { + [Test] + public void Is_Built_Correctly() + { + // Arrange + const string umbracoConnectionString = "Server=(LocalDB)\\Umbraco;Database=FakeName;Integrated Security=true"; + + var builder = new ConnectionStringsBuilder(); + + // Act + var connectionStrings = builder + .WithUmbracoConnectionString(umbracoConnectionString) + .Build(); + + // Assert + Assert.AreEqual(umbracoConnectionString, connectionStrings.UmbracoConnectionString.ConnectionString); + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilderTests.cs new file mode 100644 index 0000000000..d576f44072 --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/CoreDebugSettingsBuilderTests.cs @@ -0,0 +1,29 @@ +using NUnit.Framework; +using Umbraco.Tests.Common.Builders; + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +{ + [TestFixture] + public class CoreDebugSettingsBuilderTests + { + [Test] + public void Is_Built_Correctly() + { + // Arrange + const bool dumpOnTimeoutThreadAbort = true; + const bool logUncompletedScopes = true; + + var builder = new CoreDebugSettingsBuilder(); + + // Act + var coreDebugSettings = builder + .WithDumpOnTimeoutThreadAbort(dumpOnTimeoutThreadAbort) + .WithLogUncompletedScopes(logUncompletedScopes) + .Build(); + + // Assert + Assert.AreEqual(dumpOnTimeoutThreadAbort, coreDebugSettings.DumpOnTimeoutThreadAbort); + Assert.AreEqual(logUncompletedScopes, coreDebugSettings.LogUncompletedScopes); + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/HostingSettingsBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/HostingSettingsBuilderTests.cs new file mode 100644 index 0000000000..377e143b97 --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/HostingSettingsBuilderTests.cs @@ -0,0 +1,30 @@ +using NUnit.Framework; +using Umbraco.Core.Configuration; +using Umbraco.Tests.Common.Builders; + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +{ + [TestFixture] + public class HostingSettingsBuilderTests + { + [Test] + public void Is_Built_Correctly() + { + // Arrange + const bool debugMode = true; + const LocalTempStorage localTempStorageLocation = LocalTempStorage.AspNetTemp; + + var builder = new HostingSettingsBuilder(); + + // Act + var hostingSettings = builder + .WithDebug(debugMode) + .WithLocalTempStorageLocation(localTempStorageLocation) + .Build(); + + // Assert + Assert.AreEqual(debugMode, hostingSettings.Debug); + Assert.AreEqual(localTempStorageLocation, hostingSettings.LocalTempStorageLocation); + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilderTests.cs new file mode 100644 index 0000000000..199b3dadde --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/RequestHandlerSettingsBuilderTests.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Tests.Common.Builders; +using static Umbraco.Core.Configuration.Models.RequestHandlerSettings; + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +{ + [TestFixture] + public class RequestHandlerSettingsBuilderTests + { + [Test] + public void Is_Built_Correctly() + { + // Arrange + const bool addTrailingSlash = true; + const string convertUrlsToAscii = "try"; + var charCollection = new List { new CharItem { Char = "a", Replacement = "b" } }; + + var builder = new RequestHandlerSettingsBuilder(); + + // Act + var requestHandlerSettings = builder + .WithAddTrailingSlash(addTrailingSlash) + .WithConvertUrlsToAscii(convertUrlsToAscii) + .WithCharCollection(charCollection) + .Build(); + + // Assert + Assert.AreEqual(addTrailingSlash, requestHandlerSettings.AddTrailingSlash); + Assert.AreEqual(convertUrlsToAscii, requestHandlerSettings.ConvertUrlsToAscii); + Assert.AreEqual("a-b", string.Join(",", requestHandlerSettings.CharCollection.Select(x => $"{x.Char}-{x.Replacement}"))); + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilderTests.cs new file mode 100644 index 0000000000..e3f4bcf04e --- /dev/null +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/Builders/WebRoutingSettingsBuilderTests.cs @@ -0,0 +1,47 @@ +using NUnit.Framework; +using Umbraco.Tests.Common.Builders; + +namespace Umbraco.Tests.UnitTests.Umbraco.Tests.Common.Builders +{ + [TestFixture] + public class WebRoutingSettingsBuilderTests + { + [Test] + public void Is_Built_Correctly() + { + // Arrange + const bool disableAlternativeTemplates = true; + const bool disableFindContentByIdPath = true; + const bool disableRedirectUrlTracking = true; + const bool internalRedirectPreservesTemplate = true; + const bool trySkipIisCustomErrors = true; + const string umbracoApplicationUrl = "/test/"; + const string urlProviderMode = "test"; + const bool validateAlternativeTemplates = true; + + var builder = new WebRoutingSettingsBuilder(); + + // Act + var webRoutingSettings = builder + .WithDisableAlternativeTemplates(disableAlternativeTemplates) + .WithDisableFindContentByIdPath(disableFindContentByIdPath) + .WithDisableRedirectUrlTracking(disableRedirectUrlTracking) + .WithInternalRedirectPreservesTemplate(internalRedirectPreservesTemplate) + .WithTrySkipIisCustomErrors(trySkipIisCustomErrors) + .WithUmbracoApplicationUrl(umbracoApplicationUrl) + .WithUrlProviderMode(urlProviderMode) + .WithValidateAlternativeTemplates(validateAlternativeTemplates) + .Build(); + + // Assert + Assert.AreEqual(disableAlternativeTemplates, webRoutingSettings.DisableAlternativeTemplates); + Assert.AreEqual(disableFindContentByIdPath, webRoutingSettings.DisableFindContentByIdPath); + Assert.AreEqual(disableRedirectUrlTracking, webRoutingSettings.DisableRedirectUrlTracking); + Assert.AreEqual(internalRedirectPreservesTemplate, webRoutingSettings.InternalRedirectPreservesTemplate); + Assert.AreEqual(trySkipIisCustomErrors, webRoutingSettings.TrySkipIisCustomErrors); + Assert.AreEqual(umbracoApplicationUrl, webRoutingSettings.UmbracoApplicationUrl); + Assert.AreEqual(urlProviderMode, webRoutingSettings.UrlProviderMode); + Assert.AreEqual(validateAlternativeTemplates, webRoutingSettings.ValidateAlternativeTemplates); + } + } +} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/BuilderTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/BuilderTests.cs index e7cf0de197..f185a56868 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/BuilderTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/BuilderTests.cs @@ -8,6 +8,7 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded; using Umbraco.ModelsBuilder.Embedded.Building; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.ModelsBuilder { @@ -42,7 +43,8 @@ namespace Umbraco.Tests.ModelsBuilder { }; - var builder = new TextBuilder(Mock.Of(), types); + var modelsBuilderConfig = new ModelsBuilderConfigBuilder().Build(); + var builder = new TextBuilder(modelsBuilderConfig, types); var btypes = builder.TypeModels; var sb = new StringBuilder(); @@ -152,7 +154,8 @@ namespace Umbraco.Web.PublishedModels " } }; - var builder = new TextBuilder(Mock.Of(), types); + var modelsBuilderConfig = new ModelsBuilderConfigBuilder().Build(); + var builder = new TextBuilder(modelsBuilderConfig, types); var btypes = builder.TypeModels; builder.ModelsNamespace = "Umbraco.Web.PublishedModels"; @@ -263,7 +266,8 @@ namespace Umbraco.Web.PublishedModels { }; - var builder = new TextBuilder(Mock.Of(), types); + var modelsBuilderConfig = new ModelsBuilderConfigBuilder().Build(); + var builder = new TextBuilder(modelsBuilderConfig, types); builder.ModelsNamespace = "Umbraco.ModelsBuilder.Models"; // forces conflict with Umbraco.ModelsBuilder.Umbraco var btypes = builder.TypeModels; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/ConfigTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/ConfigTests.cs deleted file mode 100644 index 2e15381d18..0000000000 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Tests.Common/ModelsBuilder/ConfigTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Configuration; -using NUnit.Framework; -using Umbraco.Configuration.Legacy; -using Umbraco.Core; -using Umbraco.Core.Configuration; - -namespace Umbraco.Tests.ModelsBuilder -{ - [TestFixture] - public class ModelsBuilderConfigTests - { - [Test] - public void Test1() - { - var config = new ModelsBuilderConfig(modelsNamespace: "test1"); - Assert.AreEqual("test1", config.ModelsNamespace); - } - - [Test] - public void Test2() - { - var config = new ModelsBuilderConfig(modelsNamespace: "test2"); - Assert.AreEqual("test2", config.ModelsNamespace); - } - - [Test] - public void DefaultModelsNamespace() - { - var config = new ModelsBuilderConfig(); - Assert.AreEqual(Constants.ModelsBuilder.DefaultModelsNamespace, config.ModelsNamespace); - } - - [TestCase("c:/path/to/root", "~/dir/models", false, "c:\\path\\to\\root\\dir\\models")] - [TestCase("c:/path/to/root", "~/../../dir/models", true, "c:\\path\\dir\\models")] - [TestCase("c:/path/to/root", "c:/another/path/to/elsewhere", true, "c:\\another\\path\\to\\elsewhere")] - public void GetModelsDirectoryTests(string root, string config, bool acceptUnsafe, string expected) - { - Assert.AreEqual(expected, ModelsBuilderConfigExtensions.GetModelsDirectory(root, config, acceptUnsafe)); - } - - [TestCase("c:/path/to/root", "~/../../dir/models", false)] - [TestCase("c:/path/to/root", "c:/another/path/to/elsewhere", false)] - public void GetModelsDirectoryThrowsTests(string root, string config, bool acceptUnsafe) - { - Assert.Throws(() => - { - var modelsDirectory = ModelsBuilderConfigExtensions.GetModelsDirectory(root, config, acceptUnsafe); - }); - } - } -} diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs index c1c331903e..e7cf097dd5 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/FileNameTests.cs @@ -5,9 +5,11 @@ using System.Threading.Tasks; using AutoFixture.NUnit3; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Tests.UnitTests.AutoFixture; using Umbraco.Web.BackOffice.Controllers; @@ -53,10 +55,10 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] [AutoMoqData] public void PreviewViewExists( - [Frozen] IGlobalSettings globalSettings, + [Frozen] IOptions globalSettings, PreviewController sut) { - Mock.Get(globalSettings).Setup(x => x.UmbracoPath).Returns("/"); + globalSettings.Value.UmbracoPath = "/"; var viewResult = sut.Index() as ViewResult; var fileName = GetViewName(viewResult); @@ -69,12 +71,12 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common [Test] [AutoMoqData] public async Task BackOfficeDefaultExists( - [Frozen] IGlobalSettings globalSettings, + [Frozen] IOptions globalSettings, [Frozen] IHostingEnvironment hostingEnvironment, [Frozen] ITempDataDictionary tempDataDictionary, BackOfficeController sut) { - Mock.Get(globalSettings).Setup(x => x.UmbracoPath).Returns("/"); + globalSettings.Value.UmbracoPath = "/"; Mock.Get(hostingEnvironment).Setup(x => x.ToAbsolute("/")).Returns("http://localhost/"); Mock.Get(hostingEnvironment).SetupGet(x => x.ApplicationVirtualPath).Returns("/"); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs index 7d0c3c8e04..2a096bbd47 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Common/Routing/BackOfficeAreaRoutesTests.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using System.Linq; @@ -7,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Hosting; using Umbraco.Extensions; +using Umbraco.Tests.Common.Builders; using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.BackOffice.Routing; using Umbraco.Web.Common.Attributes; @@ -94,8 +96,9 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.Common.Routing private BackOfficeAreaRoutes GetBackOfficeAreaRoutes(RuntimeLevel level) { + var globalSettings = new GlobalSettingsBuilder().Build(); var routes = new BackOfficeAreaRoutes( - Mock.Of(x => x.UmbracoPath == "~/umbraco"), + Options.Create(globalSettings), Mock.Of(x => x.ToAbsolute(It.IsAny()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty), Mock.Of(x => x.Level == level), new UmbracoApiControllerTypeCollection(new[] { typeof(Testing1Controller) })); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs index 7a202d7902..0d288b6310 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Core.Cache; @@ -45,7 +46,7 @@ namespace Umbraco.Tests.Integration Mock.Of(), new TestVariationContextAccessor(), new TestDefaultCultureAccessor(), - globalSettings, + Options.Create(globalSettings), Mock.Of(), hostingEnvironment, new UriUtility(hostingEnvironment), @@ -78,7 +79,7 @@ namespace Umbraco.Tests.Integration Mock.Of(), new TestVariationContextAccessor(), new TestDefaultCultureAccessor(), - globalSettings, + Options.Create(globalSettings), Mock.Of(), hostingEnvironment, new UriUtility(hostingEnvironment), @@ -115,7 +116,7 @@ namespace Umbraco.Tests.Integration publishedSnapshotService.Object, new TestVariationContextAccessor(), new TestDefaultCultureAccessor(), - globalSettings, + Options.Create(globalSettings), Mock.Of(), hostingEnvironment, new UriUtility(hostingEnvironment), @@ -152,7 +153,7 @@ namespace Umbraco.Tests.Integration Mock.Of(), new TestVariationContextAccessor(), new TestDefaultCultureAccessor(), - globalSettings, + Options.Create(globalSettings), Mock.Of(), hostingEnvironment, new UriUtility(hostingEnvironment), diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 932a974b75..13f58f8021 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -5,9 +5,11 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Services; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -58,7 +60,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _httpContextFactory = new FakeHttpContextFactory("~/Home"); - var globalSettings = Factory.GetInstance(); + var globalSettings = new GlobalSettingsBuilder().Build(); var umbracoContextAccessor = Factory.GetInstance(); _xml = new XmlDocument(); diff --git a/src/Umbraco.Tests/Components/ComponentTests.cs b/src/Umbraco.Tests/Components/ComponentTests.cs index 1a687d2ea4..bfc3066590 100644 --- a/src/Umbraco.Tests/Components/ComponentTests.cs +++ b/src/Umbraco.Tests/Components/ComponentTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -15,6 +16,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using ILogger = Microsoft.Extensions.Logging.ILogger; @@ -26,7 +28,6 @@ namespace Umbraco.Tests.Components private static readonly List Composed = new List(); private static readonly List Initialized = new List(); private static readonly List Terminated = new List(); - private static readonly Configs Configs = TestHelper.GetConfigs(); private static IFactory MockFactory(Action> setup = null) { @@ -36,11 +37,13 @@ namespace Umbraco.Tests.Components var loggerFactory = NullLoggerFactory.Instance; var logger = loggerFactory.CreateLogger("GenericLogger"); var typeFinder = TestHelper.GetTypeFinder(); - var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, SettingsForTests.DefaultGlobalSettings, Mock.Of(), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator); - var fs = new FileSystems(mock.Object, loggerFactory.CreateLogger(), loggerFactory, TestHelper.IOHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment()); - var coreDebug = Mock.Of(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); + var f = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator); + var fs = new FileSystems(mock.Object, loggerFactory.CreateLogger(), loggerFactory, TestHelper.IOHelper, Options.Create(globalSettings), TestHelper.GetHostingEnvironment()); + var coreDebug = new CoreDebugSettingsBuilder().Build(); var mediaFileSystem = Mock.Of(); - var p = new ScopeProvider(f, fs, coreDebug, mediaFileSystem, loggerFactory.CreateLogger(), loggerFactory, typeFinder, NoAppCache.Instance); + var p = new ScopeProvider(f, fs, Microsoft.Extensions.Options.Options.Create(coreDebug), mediaFileSystem, loggerFactory.CreateLogger(), loggerFactory, typeFinder, NoAppCache.Instance); mock.Setup(x => x.GetInstance(typeof (ILogger))).Returns(logger); mock.Setup(x => x.GetInstance(typeof (Umbraco.Core.Logging.ILogger))).Returns(Mock.Of()); @@ -76,7 +79,7 @@ namespace Umbraco.Tests.Components { var register = MockRegister(); var typeLoader = MockTypeLoader(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -116,7 +119,7 @@ namespace Umbraco.Tests.Components public void Boot1B() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -132,7 +135,7 @@ namespace Umbraco.Tests.Components public void Boot2() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -147,7 +150,7 @@ namespace Umbraco.Tests.Components public void Boot3() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -164,7 +167,7 @@ namespace Umbraco.Tests.Components public void BrokenRequire() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -187,7 +190,7 @@ namespace Umbraco.Tests.Components public void BrokenRequired() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = TypeArray(); var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -223,7 +226,7 @@ namespace Umbraco.Tests.Components throw new NotSupportedException(type.FullName); }); }); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer1), typeof(Composer5), typeof(Composer5a) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -249,7 +252,7 @@ namespace Umbraco.Tests.Components public void Requires1() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer6), typeof(Composer7), typeof(Composer8) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -264,7 +267,7 @@ namespace Umbraco.Tests.Components public void Requires2A() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), Configs, TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -282,7 +285,7 @@ namespace Umbraco.Tests.Components var register = MockRegister(); var typeLoader = MockTypeLoader(); var factory = MockFactory(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Run), Configs, TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer9), typeof(Composer2), typeof(Composer4) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -301,7 +304,7 @@ namespace Umbraco.Tests.Components public void WeakDependencies() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), Configs, TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer10) }; var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -340,7 +343,7 @@ namespace Umbraco.Tests.Components public void DisableMissing() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), Configs, TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer6), typeof(Composer8) }; // 8 disables 7 which is not in the list var composers = new Composers(composition, types, Enumerable.Empty(), Mock.Of(), Mock.Of()); @@ -355,7 +358,7 @@ namespace Umbraco.Tests.Components public void AttributesPriorities() { var register = MockRegister(); - var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), Configs, TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, MockTypeLoader(), Mock.Of(), MockRuntimeState(RuntimeLevel.Unknown), TestHelper.IOHelper, AppCaches.NoCache); var types = new[] { typeof(Composer26) }; var enableDisableAttributes = new[] { new DisableComposerAttribute(typeof(Composer26)) }; @@ -382,7 +385,7 @@ namespace Umbraco.Tests.Components var register = MockRegister(); var composition = new Composition(register, typeLoader, Mock.Of(), - MockRuntimeState(RuntimeLevel.Run), Configs, TestHelper.IOHelper, AppCaches.NoCache); + MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); var allComposers = typeLoader.GetTypes().ToList(); var types = allComposers.Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web")).ToList(); diff --git a/src/Umbraco.Tests/Composing/CollectionBuildersTests.cs b/src/Umbraco.Tests/Composing/CollectionBuildersTests.cs index 2d977e89c7..4986c3ac53 100644 --- a/src/Umbraco.Tests/Composing/CollectionBuildersTests.cs +++ b/src/Umbraco.Tests/Composing/CollectionBuildersTests.cs @@ -24,7 +24,7 @@ namespace Umbraco.Tests.Composing Current.Reset(); var register = TestHelper.GetRegister(); - _composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + _composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); } [TearDown] @@ -490,7 +490,7 @@ namespace Umbraco.Tests.Composing for (var i = 0; i < col1A.Length; i++) { Assert.AreNotSame(col1A[i], col2A[i]); - } + } } #endregion diff --git a/src/Umbraco.Tests/Composing/CompositionTests.cs b/src/Umbraco.Tests/Composing/CompositionTests.cs index 56a94bf3ee..e9b24f1038 100644 --- a/src/Umbraco.Tests/Composing/CompositionTests.cs +++ b/src/Umbraco.Tests/Composing/CompositionTests.cs @@ -43,7 +43,7 @@ namespace Umbraco.Tests.Composing var typeFinder = TestHelper.GetTypeFinder(); var ioHelper = TestHelper.IOHelper; var typeLoader = new TypeLoader(typeFinder, Mock.Of(), new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")), Mock.Of(), logger); - var composition = new Composition(mockedRegister, typeLoader, logger, Mock.Of(), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(mockedRegister, typeLoader, logger, Mock.Of(), TestHelper.IOHelper, AppCaches.NoCache); // create the factory, ensure it is the mocked factory var factory = composition.CreateFactory(); diff --git a/src/Umbraco.Tests/Composing/LazyCollectionBuilderTests.cs b/src/Umbraco.Tests/Composing/LazyCollectionBuilderTests.cs index 4d0135d6c4..c17e80a34a 100644 --- a/src/Umbraco.Tests/Composing/LazyCollectionBuilderTests.cs +++ b/src/Umbraco.Tests/Composing/LazyCollectionBuilderTests.cs @@ -41,7 +41,7 @@ namespace Umbraco.Tests.Composing public void LazyCollectionBuilderHandlesTypes() { var container = CreateRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Add() @@ -67,7 +67,7 @@ namespace Umbraco.Tests.Composing public void LazyCollectionBuilderHandlesProducers() { var container = CreateRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Add(() => new[] { typeof(TransientObject3), typeof(TransientObject2) }) @@ -92,7 +92,7 @@ namespace Umbraco.Tests.Composing public void LazyCollectionBuilderHandlesTypesAndProducers() { var container = CreateRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Add() @@ -118,7 +118,7 @@ namespace Umbraco.Tests.Composing public void LazyCollectionBuilderThrowsOnIllegalTypes() { var container = CreateRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Add() @@ -140,7 +140,7 @@ namespace Umbraco.Tests.Composing public void LazyCollectionBuilderCanExcludeTypes() { var container = CreateRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Add() diff --git a/src/Umbraco.Tests/Composing/PackageActionCollectionTests.cs b/src/Umbraco.Tests/Composing/PackageActionCollectionTests.cs index 390997173b..118eaab41a 100644 --- a/src/Umbraco.Tests/Composing/PackageActionCollectionTests.cs +++ b/src/Umbraco.Tests/Composing/PackageActionCollectionTests.cs @@ -22,7 +22,7 @@ namespace Umbraco.Tests.Composing { var container = TestHelper.GetRegister(); - var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); var expectedPackageActions = TypeLoader.GetPackageActions(); composition.WithCollectionBuilder() diff --git a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs index 56237f562c..a7b148c8e5 100644 --- a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs +++ b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs @@ -1,7 +1,8 @@ using Moq; using NUnit.Framework; using Umbraco.Core.Configuration; -using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Hosting; @@ -18,17 +19,14 @@ namespace Umbraco.Tests.Configurations [TestCase("~/some-wacky/nestedPath", "/MyVirtualDir/NestedVDir/", "some-wacky-nestedpath")] public void Umbraco_Mvc_Area(string path, string rootPath, string outcome) { + var hostingEnvironment = new AspNetHostingEnvironment(Microsoft.Extensions.Options.Options.Create(new HostingSettings() + { + ApplicationVirtualPath = rootPath + })); - var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); - var mockHostingSettings = Mock.Get(SettingsForTests.GenerateMockHostingSettings()); - mockHostingSettings.Setup(x => x.ApplicationVirtualPath).Returns(rootPath); + var globalSettings = new GlobalSettingsBuilder().WithUmbracoPath(path).Build(); - var hostingEnvironment = new AspNetHostingEnvironment(mockHostingSettings.Object); - - var globalSettingsMock = Mock.Get(globalSettings); - globalSettingsMock.Setup(x => x.UmbracoPath).Returns(() => path); - - Assert.AreEqual(outcome, globalSettingsMock.Object.GetUmbracoMvcAreaNoCache(hostingEnvironment)); + Assert.AreEqual(outcome, globalSettings.GetUmbracoMvcAreaNoCache(hostingEnvironment)); } } } diff --git a/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs b/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs index fbb89b1c5d..cd26bf914f 100644 --- a/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs +++ b/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs @@ -1,6 +1,8 @@ using System; +using Microsoft.Extensions.Options; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Strings; using Umbraco.Tests.Testing; @@ -14,7 +16,7 @@ namespace Umbraco.Tests.CoreThings { base.Compose(); - Composition.RegisterUnique(f => new DefaultShortStringHelper(f.GetInstance())); + Composition.RegisterUnique(f => new DefaultShortStringHelper(f.GetInstance>())); } [Test] diff --git a/src/Umbraco.Tests/IO/FileSystemsTests.cs b/src/Umbraco.Tests/IO/FileSystemsTests.cs index 6fde147f10..20f217c1d5 100644 --- a/src/Umbraco.Tests/IO/FileSystemsTests.cs +++ b/src/Umbraco.Tests/IO/FileSystemsTests.cs @@ -19,6 +19,7 @@ using Umbraco.Core.Composing.CompositionExtensions; using Current = Umbraco.Web.Composing.Current; using FileSystems = Umbraco.Core.IO.FileSystems; using ILogger = Umbraco.Core.Logging.ILogger; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.IO { @@ -33,29 +34,24 @@ namespace Umbraco.Tests.IO { _register = TestHelper.GetRegister(); - var composition = new Composition(_register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(_register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.Register(_ => Mock.Of()); composition.Register(_ => Mock.Of()); - composition.Register(_ => Mock.Of()); - composition.Register(new NullLoggerFactory()); composition.Register(typeof(Microsoft.Extensions.Logging.ILogger<>), typeof(Logger<>)); - composition.Register(_ => TestHelper.ShortStringHelper); composition.Register(_ => TestHelper.IOHelper); composition.RegisterUnique(); composition.RegisterUnique(TestHelper.IOHelper); composition.RegisterUnique(TestHelper.GetHostingEnvironment()); - composition.Configs.Add(() => SettingsForTests.DefaultGlobalSettings); - composition.Configs.Add(SettingsForTests.GenerateMockContentSettings); + var globalSettings = new GlobalSettingsBuilder().Build(); + composition.Register(x => Microsoft.Extensions.Options.Options.Create(globalSettings)); composition.ComposeFileSystems(); - composition.Configs.Add(SettingsForTests.GenerateMockContentSettings); - _factory = composition.CreateFactory(); Current.Reset(); diff --git a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs index e9f2a307f8..15b33f3dff 100644 --- a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs +++ b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -11,6 +12,7 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.IO; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.IO @@ -437,7 +439,8 @@ namespace Umbraco.Tests.IO var phy = new PhysicalFileSystem(ioHelper, hostingEnvironment, loggerFactory.CreateLogger(), path, "ignore"); var container = Mock.Of(); - var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; + var globalSettings = Options.Create(new GlobalSettingsBuilder().Build()); + var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, globalSettings, TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem(phy); var sw = (ShadowWrapper) fs.InnerFileSystem; @@ -533,7 +536,8 @@ namespace Umbraco.Tests.IO var phy = new PhysicalFileSystem(ioHelper, hostingEnvironment, loggerFactory.CreateLogger(), path, "ignore"); var container = Mock.Of(); - var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; + var globalSettings = Options.Create(new GlobalSettingsBuilder().Build()); + var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, globalSettings, TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem( phy); var sw = (ShadowWrapper) fs.InnerFileSystem; @@ -588,7 +592,8 @@ namespace Umbraco.Tests.IO var phy = new PhysicalFileSystem(ioHelper, hostingEnvironment, loggerFactory.CreateLogger(), path, "ignore"); var container = Mock.Of(); - var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; + var globalSettings = Options.Create(new GlobalSettingsBuilder().Build()); + var fileSystems = new FileSystems(container, loggerFactory.CreateLogger(), loggerFactory, ioHelper, globalSettings, TestHelper.GetHostingEnvironment()) { IsScoped = () => scopedFileSystems }; var fs = fileSystems.GetFileSystem( phy); var sw = (ShadowWrapper)fs.InnerFileSystem; diff --git a/src/Umbraco.Tests/LegacyXmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Tests/LegacyXmlPublishedCache/PublishedContentCache.cs index afdb71c28e..fe02e6fa48 100644 --- a/src/Umbraco.Tests/LegacyXmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Tests/LegacyXmlPublishedCache/PublishedContentCache.cs @@ -7,6 +7,7 @@ using System.Xml.XPath; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Tests.TestHelpers; @@ -18,7 +19,7 @@ namespace Umbraco.Tests.LegacyXmlPublishedCache internal class PublishedContentCache : PublishedCacheBase, IPublishedContentCache { private readonly IAppCache _appCache; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly RoutesCache _routesCache; private readonly IVariationContextAccessor _variationContextAccessor; private readonly IDomainCache _domainCache; @@ -33,7 +34,7 @@ namespace Umbraco.Tests.LegacyXmlPublishedCache XmlStore xmlStore, // an XmlStore containing the master xml IDomainCache domainCache, // an IDomainCache implementation IAppCache appCache, // an IAppCache that should be at request-level - IGlobalSettings globalSettings, + GlobalSettings globalSettings, PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache RoutesCache routesCache, // a RoutesCache IVariationContextAccessor variationContextAccessor, diff --git a/src/Umbraco.Tests/LegacyXmlPublishedCache/XmlPublishedSnapshotService.cs b/src/Umbraco.Tests/LegacyXmlPublishedCache/XmlPublishedSnapshotService.cs index 42ecd971f2..c02c795f85 100644 --- a/src/Umbraco.Tests/LegacyXmlPublishedCache/XmlPublishedSnapshotService.cs +++ b/src/Umbraco.Tests/LegacyXmlPublishedCache/XmlPublishedSnapshotService.cs @@ -3,6 +3,7 @@ using System.Linq; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -35,7 +36,7 @@ namespace Umbraco.Tests.LegacyXmlPublishedCache private readonly IMediaService _mediaService; private readonly IUserService _userService; private readonly IAppCache _requestCache; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IDefaultCultureAccessor _defaultCultureAccessor; private readonly ISiteDomainHelper _siteDomainHelper; private readonly IEntityXmlSerializer _entitySerializer; @@ -56,7 +57,7 @@ namespace Umbraco.Tests.LegacyXmlPublishedCache IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, Microsoft.Extensions.Logging.ILogger logger, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IApplicationShutdownRegistry hostingLifetime, IShortStringHelper shortStringHelper, @@ -84,7 +85,7 @@ namespace Umbraco.Tests.LegacyXmlPublishedCache IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, Microsoft.Extensions.Logging.ILogger logger, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IApplicationShutdownRegistry hostingLifetime, IShortStringHelper shortStringHelper, diff --git a/src/Umbraco.Tests/Migrations/AdvancedMigrationTests.cs b/src/Umbraco.Tests/Migrations/AdvancedMigrationTests.cs index 9abc624577..8e08e57f80 100644 --- a/src/Umbraco.Tests/Migrations/AdvancedMigrationTests.cs +++ b/src/Umbraco.Tests/Migrations/AdvancedMigrationTests.cs @@ -11,6 +11,7 @@ using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -44,7 +45,7 @@ namespace Umbraco.Tests.Migrations upgrader.Execute(ScopeProvider, builder, Mock.Of(), _loggerFactory.CreateLogger(), _loggerFactory); - var helper = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion, TestObjects.GetGlobalSettings()); + var helper = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion); var exists = helper.TableExists("umbracoUser"); Assert.IsTrue(exists); diff --git a/src/Umbraco.Tests/Migrations/MigrationPlanTests.cs b/src/Umbraco.Tests/Migrations/MigrationPlanTests.cs index f9b8566cfd..0a8c6cfb3f 100644 --- a/src/Umbraco.Tests/Migrations/MigrationPlanTests.cs +++ b/src/Umbraco.Tests/Migrations/MigrationPlanTests.cs @@ -10,10 +10,10 @@ using Umbraco.Core; using Umbraco.Core.Migrations; using Umbraco.Core.Migrations.Upgrade; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Persistance.SqlCe; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -140,7 +140,7 @@ namespace Umbraco.Tests.Migrations [Test] public void ValidateUmbracoPlan() { - var plan = new UmbracoPlan(TestHelper.GetUmbracoVersion(), SettingsForTests.GenerateMockGlobalSettings()); + var plan = new UmbracoPlan(TestHelper.GetUmbracoVersion()); plan.Validate(); Console.WriteLine(plan.FinalState); Assert.IsFalse(plan.FinalState.IsNullOrWhiteSpace()); diff --git a/src/Umbraco.Tests/Models/ContentExtensionsTests.cs b/src/Umbraco.Tests/Models/ContentExtensionsTests.cs index bab3a540be..1b2f30db16 100644 --- a/src/Umbraco.Tests/Models/ContentExtensionsTests.cs +++ b/src/Umbraco.Tests/Models/ContentExtensionsTests.cs @@ -29,7 +29,6 @@ namespace Umbraco.Tests.Models Composition.ComposeFileSystems(); Composition.Register(_ => Mock.Of()); - Composition.Register(_ => Mock.Of()); // all this is required so we can validate properties... var editor = new TextboxPropertyEditor(Mock.Of(), Mock.Of(), Mock.Of(), IOHelper, ShortStringHelper, LocalizedTextService) { Alias = "test" }; diff --git a/src/Umbraco.Tests/Models/ContentTests.cs b/src/Umbraco.Tests/Models/ContentTests.cs index dec3c2944c..9e56d07348 100644 --- a/src/Umbraco.Tests/Models/ContentTests.cs +++ b/src/Umbraco.Tests/Models/ContentTests.cs @@ -4,6 +4,8 @@ using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; +using Microsoft.CodeAnalysis.Options; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Moq; using Newtonsoft.Json; @@ -41,7 +43,6 @@ namespace Umbraco.Tests.Models Composition.ComposeFileSystems(); Composition.Register(_ => Mock.Of()); - Composition.Register(_ => Mock.Of()); // all this is required so we can validate properties... var editor = new TextboxPropertyEditor(Mock.Of(), Mock.Of(), Mock.Of(), IOHelper, ShortStringHelper, LocalizedTextService) { Alias = "test" }; diff --git a/src/Umbraco.Tests/Models/MediaXmlTest.cs b/src/Umbraco.Tests/Models/MediaXmlTest.cs index 632f433c5b..593a581f85 100644 --- a/src/Umbraco.Tests/Models/MediaXmlTest.cs +++ b/src/Umbraco.Tests/Models/MediaXmlTest.cs @@ -8,6 +8,7 @@ using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Services; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; @@ -31,10 +32,10 @@ namespace Umbraco.Tests.Models // and then, this will reset the width, height... because the file does not exist, of course ;-( var logger = Mock.Of(); var scheme = Mock.Of(); - var config = Mock.Of(); + var contentSettings = new ContentSettingsBuilder().Build(); var mediaFileSystem = new MediaFileSystem(Mock.Of(), scheme, logger, ShortStringHelper); - var ignored = new FileUploadPropertyEditor(Mock.Of(), mediaFileSystem, config, DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); + var ignored = new FileUploadPropertyEditor(Mock.Of(), mediaFileSystem, Microsoft.Extensions.Options.Options.Create(contentSettings), DataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper); var media = MockedMedia.CreateMediaImage(mediaType, -1); media.WriterId = -1; // else it's zero and that's not a user and it breaks the tests diff --git a/src/Umbraco.Tests/Models/VariationTests.cs b/src/Umbraco.Tests/Models/VariationTests.cs index e67cb10cf1..e811d06db1 100644 --- a/src/Umbraco.Tests/Models/VariationTests.cs +++ b/src/Umbraco.Tests/Models/VariationTests.cs @@ -23,9 +23,6 @@ namespace Umbraco.Tests.Models [SetUp] public void SetUp() { - // annoying, but content type wants short string helper ;( - SettingsForTests.Reset(); - // well, this is also annoying, but... // validating a value is performed by its data editor, // based upon the configuration in the data type, so we @@ -33,10 +30,6 @@ namespace Umbraco.Tests.Models Current.Reset(); - var configs = TestHelper.GetConfigs(); - configs.Add(() => SettingsForTests.DefaultGlobalSettings); - configs.Add(SettingsForTests.GenerateMockContentSettings); - _factory = Mock.Of(); var dataTypeService = Mock.Of(); @@ -65,7 +58,7 @@ namespace Umbraco.Tests.Models .Setup(x => x.GetInstance(It.IsAny())) .Returns(x => { - if (x == typeof(Configs)) return configs; + //if (x == typeof(Configs)) return configs; if (x == typeof(PropertyEditorCollection)) return propertyEditors; if (x == typeof(ServiceContext)) return serviceContext; if (x == typeof(ILocalizedTextService)) return serviceContext.LocalizationService; diff --git a/src/Umbraco.Tests/Packaging/CreatedPackagesRepositoryTests.cs b/src/Umbraco.Tests/Packaging/CreatedPackagesRepositoryTests.cs index 6533dd6113..90a352ad39 100644 --- a/src/Umbraco.Tests/Packaging/CreatedPackagesRepositoryTests.cs +++ b/src/Umbraco.Tests/Packaging/CreatedPackagesRepositoryTests.cs @@ -6,13 +6,10 @@ using System.Linq; using System.Xml.Linq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; -using Umbraco.Core.IO; using Umbraco.Core.Models.Packaging; using Umbraco.Core.Packaging; using Umbraco.Core.Services; -using Umbraco.Tests.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -44,7 +41,7 @@ namespace Umbraco.Tests.Packaging HostingEnvironment, Factory.GetInstance(), Logger, UmbracoVersion, - Factory.GetInstance(), + Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build()), "createdPackages.config", //temp paths tempFolderPath: "~/" + _testBaseFolder + "/temp", diff --git a/src/Umbraco.Tests/Packaging/PackageDataInstallationTests.cs b/src/Umbraco.Tests/Packaging/PackageDataInstallationTests.cs index d089c4aaa2..ed1cd5424d 100644 --- a/src/Umbraco.Tests/Packaging/PackageDataInstallationTests.cs +++ b/src/Umbraco.Tests/Packaging/PackageDataInstallationTests.cs @@ -18,6 +18,7 @@ using Umbraco.Tests.Services.Importing; using Umbraco.Tests.Testing; using Umbraco.Core.Composing.CompositionExtensions; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Packaging { @@ -712,8 +713,9 @@ namespace Umbraco.Tests.Packaging private void AddLanguages() { - var norwegian = new Core.Models.Language(TestObjects.GetGlobalSettings(), "nb-NO"); - var english = new Core.Models.Language(TestObjects.GetGlobalSettings(), "en-GB"); + var globalSettings = new GlobalSettingsBuilder().Build(); + var norwegian = new Core.Models.Language(globalSettings, "nb-NO"); + var english = new Core.Models.Language(globalSettings, "en-GB"); ServiceContext.LocalizationService.Save(norwegian, 0); ServiceContext.LocalizationService.Save(english, 0); } diff --git a/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs b/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs index 90db389002..3b4edd28c1 100644 --- a/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs +++ b/src/Umbraco.Tests/Packaging/PackageInstallationTest.cs @@ -16,6 +16,7 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using File = System.IO.File; @@ -46,7 +47,11 @@ namespace Umbraco.Tests.Packaging _testBaseFolder.Delete(true); } - private CompiledPackageXmlParser Parser => new CompiledPackageXmlParser(new ConflictingPackageData(ServiceContext.MacroService, ServiceContext.FileService),Factory.GetInstance()); + private CompiledPackageXmlParser Parser => new CompiledPackageXmlParser( + new ConflictingPackageData( + ServiceContext.MacroService, + ServiceContext.FileService), + Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build())); private PackageDataInstallation PackageDataInstallation => new PackageDataInstallation( Logger, ServiceContext.FileService, ServiceContext.MacroService, ServiceContext.LocalizationService, @@ -55,9 +60,8 @@ namespace Umbraco.Tests.Packaging Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - Factory.GetInstance(), - Factory.GetInstance() - ); + Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build()), + Factory.GetInstance()); private IPackageInstallation PackageInstallation => new PackageInstallation( PackageDataInstallation, diff --git a/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs b/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs index 13d0fc3cc8..1399e117f7 100644 --- a/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs +++ b/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs @@ -3,6 +3,7 @@ using System.Configuration; using System.Data.SqlServerCe; using System.IO; using System.Threading; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -16,6 +17,7 @@ using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Services; using Umbraco.Persistance.SqlCe; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Security; @@ -41,9 +43,9 @@ namespace Umbraco.Tests.Persistence _logger = Mock.Of>(); _loggerFactory = NullLoggerFactory.Instance; _umbracoVersion = TestHelper.GetUmbracoVersion(); - var globalSettings = TestHelper.GetConfigs().Global(); - var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); - _databaseFactory = new UmbracoDatabaseFactory(_logger, _loggerFactory, globalSettings, connectionStrings, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); + _databaseFactory = new UmbracoDatabaseFactory(_logger, _loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator); } [TearDown] @@ -97,7 +99,7 @@ namespace Umbraco.Tests.Persistence using (var database = _databaseFactory.CreateDatabase()) using (var transaction = database.GetTransaction()) { - schemaHelper = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion, SettingsForTests.GenerateMockGlobalSettings()); + schemaHelper = new DatabaseSchemaCreator(database, _loggerFactory.CreateLogger(), _loggerFactory, _umbracoVersion); schemaHelper.InitializeDatabaseSchema(); transaction.Complete(); } diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs index 4dbfafff11..3a17ac5928 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -1,16 +1,19 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -22,21 +25,25 @@ namespace Umbraco.Tests.Persistence.Repositories [UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class ContentTypeRepositoryTest : TestWithDatabaseBase { + private IOptions _globalSettings; + public override void SetUp() { base.SetUp(); CreateTestData(); + + _globalSettings = Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build()); } private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository) { - var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(),TestObjects.GetGlobalSettings()); + var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), _globalSettings); var templateRepository = new TemplateRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, AppCaches.Disabled, ShortStringHelper); contentTypeRepository = new ContentTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, langRepository, ShortStringHelper); - var languageRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), _globalSettings); var relationTypeRepository = new RelationTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(scopeAccessor); var relationRepository = new RelationRepository(scopeAccessor, LoggerFactory_.CreateLogger(), relationTypeRepository, entityRepository); @@ -48,7 +55,7 @@ namespace Umbraco.Tests.Persistence.Repositories private ContentTypeRepository CreateRepository(IScopeAccessor scopeAccessor) { - var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), _globalSettings); var templateRepository = new TemplateRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, AppCaches.Disabled, ShortStringHelper); var contentTypeRepository = new ContentTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, langRepository, ShortStringHelper); @@ -59,7 +66,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var templateRepository = new TemplateRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, AppCaches.Disabled, ShortStringHelper); - var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var langRepository = new LanguageRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), _globalSettings); var contentTypeRepository = new MediaTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, langRepository, ShortStringHelper); return contentTypeRepository; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index e318123c83..8a2d9547e7 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -21,6 +21,7 @@ using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Tests.Testing; using Umbraco.Web.PropertyEditors; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Persistence.Repositories { @@ -63,12 +64,14 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository, AppCaches appCaches = null) { + var globalSettings = Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build()); + appCaches = appCaches ?? AppCaches; templateRepository = new TemplateRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, appCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), globalSettings); contentTypeRepository = new ContentTypeRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(scopeAccessor); diff --git a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs index e92a02519a..e65a2f5407 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs @@ -10,6 +10,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -22,11 +23,13 @@ namespace Umbraco.Tests.Persistence.Repositories { private DomainRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository, out DocumentRepository documentRepository, out LanguageRepository languageRepository) { + var globalSettings = Microsoft.Extensions.Options.Options.Create(new GlobalSettingsBuilder().Build()); + var accessor = (IScopeAccessor) provider; var templateRepository = new TemplateRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - languageRepository = new LanguageRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + languageRepository = new LanguageRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger(), globalSettings); contentTypeRepository = new ContentTypeRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, Core.Cache.AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); @@ -49,7 +52,8 @@ namespace Umbraco.Tests.Persistence.Repositories var repo = CreateRepository(provider, out contentTypeRepo, out documentRepo, out langRepo); - var lang = new Language(TestObjects.GetGlobalSettings(), isoName); + var globalSettings = new GlobalSettingsBuilder().Build(); + var lang = new Language(globalSettings, isoName); langRepo.Save(lang); ct = MockedContentTypes.CreateBasicContentType("test", "Test"); @@ -204,7 +208,8 @@ namespace Umbraco.Tests.Persistence.Repositories //more test data var lang1 = langRepo.GetByIsoCode("en-AU"); - var lang2 = new Language(TestObjects.GetGlobalSettings(), "es"); + var globalSettings = new GlobalSettingsBuilder().Build(); + var lang2 = new Language(globalSettings, "es"); langRepo.Save(lang2); var content2 = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 }; documentRepo.Save(content2); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs index 90640adb76..50fa257b60 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs @@ -17,6 +17,7 @@ using Umbraco.Tests.Testing; using Umbraco.Core.Services; using Umbraco.Core; using Umbraco.Core.PropertyEditors; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Persistence.Repositories { @@ -35,10 +36,10 @@ namespace Umbraco.Tests.Persistence.Repositories { appCaches = appCaches ?? AppCaches; var scopeAccessor = (IScopeAccessor) provider; - + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var commonRepository = new ContentTypeCommonRepository(scopeAccessor, templateRepository, appCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); mediaTypeRepository = new MediaTypeRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var tagRepository = new TagRepository(scopeAccessor, appCaches, LoggerFactory_.CreateLogger()); var relationTypeRepository = new RelationTypeRepository(scopeAccessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs index a62202657d..7d11e30585 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs @@ -9,6 +9,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -22,9 +23,10 @@ namespace Umbraco.Tests.Persistence.Repositories private MediaTypeRepository CreateRepository(IScopeProvider provider) { var cacheHelper = AppCaches.Disabled; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository((IScopeAccessor)provider, cacheHelper, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var commonRepository = new ContentTypeCommonRepository((IScopeAccessor)provider, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository((IScopeAccessor)provider, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository((IScopeAccessor)provider, AppCaches, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); return new MediaTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); } diff --git a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs index 0532ee463d..6299358a36 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs @@ -18,6 +18,7 @@ using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -31,9 +32,10 @@ namespace Umbraco.Tests.Persistence.Repositories private MemberRepository CreateRepository(IScopeProvider provider, out MemberTypeRepository memberTypeRepository, out MemberGroupRepository memberGroupRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = Mock.Of(); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); memberTypeRepository = new MemberTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); memberGroupRepository = new MemberGroupRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var tagRepo = new TagRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs index 7be125527d..28ba83440f 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs @@ -10,6 +10,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -23,8 +24,9 @@ namespace Umbraco.Tests.Persistence.Repositories private MemberTypeRepository CreateRepository(IScopeProvider provider) { var templateRepository = Mock.Of(); + var globalSettings = new GlobalSettingsBuilder().Build(); var commonRepository = new ContentTypeCommonRepository((IScopeAccessor)provider, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository((IScopeAccessor)provider, AppCaches.Disabled, Mock.Of>(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository((IScopeAccessor)provider, AppCaches.Disabled, Mock.Of>(), Microsoft.Extensions.Options.Options.Create(globalSettings)); return new MemberTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); } diff --git a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs index 43569099c7..24f8b3793f 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs @@ -10,6 +10,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -307,10 +308,11 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); contentTypeRepository = new ContentTypeRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); diff --git a/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs index 8a060a4ba2..d0ab678c1e 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ScriptRepositoryTest.cs @@ -8,12 +8,14 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -31,7 +33,7 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory_.CreateLogger(), SettingsForTests.GenerateMockGlobalSettings().UmbracoScriptsPath); + _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory_.CreateLogger(), new GlobalSettings().UmbracoScriptsPath); Mock.Get(_fileSystems).Setup(x => x.ScriptsFileSystem).Returns(_fileSystem); using (var stream = CreateStream("Umbraco.Sys.registerNamespace(\"Umbraco.Utils\");")) { @@ -41,7 +43,8 @@ namespace Umbraco.Tests.Persistence.Repositories private IScriptRepository CreateRepository() { - return new ScriptRepository(_fileSystems, IOHelper, TestObjects.GetGlobalSettings()); + var globalSettings = new GlobalSettingsBuilder().Build(); + return new ScriptRepository(_fileSystems, IOHelper, Microsoft.Extensions.Options.Options.Create(globalSettings)); } protected override void Compose() diff --git a/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs index 298f3eb278..196e959ea3 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/StylesheetRepositoryTest.cs @@ -9,10 +9,12 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -30,7 +32,7 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory_.CreateLogger(), SettingsForTests.GenerateMockGlobalSettings().UmbracoCssPath); + _fileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, LoggerFactory_.CreateLogger(), new GlobalSettings().UmbracoCssPath); Mock.Get(_fileSystems).Setup(x => x.StylesheetsFileSystem).Returns(_fileSystem); var stream = CreateStream("body {background:#EE7600; color:#FFF;}"); _fileSystem.AddFile("styles.css", stream); @@ -38,7 +40,8 @@ namespace Umbraco.Tests.Persistence.Repositories private IStylesheetRepository CreateRepository() { - return new StylesheetRepository(_fileSystems, IOHelper, TestObjects.GetGlobalSettings()); + var globalSettings = new GlobalSettingsBuilder().Build(); + return new StylesheetRepository(_fileSystems, IOHelper, Microsoft.Extensions.Options.Options.Create(globalSettings)); } [Test] diff --git a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs index f85da11da7..fe7259b777 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs @@ -11,6 +11,7 @@ using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -956,10 +957,11 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateDocumentRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches.Disabled, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); contentTypeRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); @@ -973,10 +975,11 @@ namespace Umbraco.Tests.Persistence.Repositories private MediaRepository CreateMediaRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches.Disabled, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); mediaTypeRepository = new MediaTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs index 133266969e..c8f5314de7 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs @@ -5,16 +5,17 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; +using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Core.Serialization; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; -using Umbraco.Core.PropertyEditors; -using Umbraco.Core.Configuration; -using Umbraco.Core.Serialization; using MockedUser = Umbraco.Tests.TestHelpers.Entities.MockedUser; namespace Umbraco.Tests.Persistence.Repositories @@ -28,9 +29,10 @@ namespace Umbraco.Tests.Persistence.Repositories private MediaRepository CreateMediaRepository(IScopeProvider provider, out IMediaTypeRepository mediaTypeRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); mediaTypeRepository = new MediaTypeRepository(accessor, AppCaches, Mock.Of>(), commonRepository, languageRepository, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches, Mock.Of>()); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); @@ -52,10 +54,11 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateContentRepository(IScopeProvider provider, out IContentTypeRepository contentTypeRepository, out ITemplateRepository templateRepository) { var accessor = (IScopeAccessor) provider; + var globalSettings = new GlobalSettingsBuilder().Build(); templateRepository = new TemplateRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); contentTypeRepository = new ContentTypeRepository(accessor, AppCaches, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); @@ -69,7 +72,8 @@ namespace Umbraco.Tests.Persistence.Repositories private UserRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor) provider; - var repository = new UserRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Mappers, TestObjects.GetGlobalSettings(), Mock.Of(), new JsonNetSerializer()); + var globalSettings = new GlobalSettingsBuilder().Build(); + var repository = new UserRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Mappers, Microsoft.Extensions.Options.Options.Create(globalSettings), Microsoft.Extensions.Options.Options.Create(new UserPasswordConfigurationSettings()), new JsonNetSerializer()); return repository; } diff --git a/src/Umbraco.Tests/Persistence/SchemaValidationTest.cs b/src/Umbraco.Tests/Persistence/SchemaValidationTest.cs index 2fa60bc54a..7c5b174208 100644 --- a/src/Umbraco.Tests/Persistence/SchemaValidationTest.cs +++ b/src/Umbraco.Tests/Persistence/SchemaValidationTest.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Umbraco.Core.Configuration; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence.SqlSyntax; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -22,7 +23,7 @@ namespace Umbraco.Tests.Persistence using (var scope = ScopeProvider.CreateScope()) { - var schema = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion, TestObjects.GetGlobalSettings()); + var schema = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion); result = schema.ValidateSchema( //TODO: When we remove the xml cache from tests we can remove this too DatabaseSchemaCreator.OrderedTables.Concat(new []{typeof(ContentXmlDto), typeof(PreviewXmlDto)})); diff --git a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs index a13f70b70c..ae30ca4328 100644 --- a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs +++ b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs @@ -4,9 +4,11 @@ using Moq; using NPoco; using NUnit.Framework; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -17,7 +19,7 @@ namespace Umbraco.Tests.Persistence [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class SqlCeTableByTableTest : TestWithDatabaseBase { - public IGlobalSettings GlobalSettings => SettingsForTests.GenerateMockGlobalSettings(); + public GlobalSettings GlobalSettings => new GlobalSettingsBuilder().Build(); private static ILoggerFactory _loggerFactory = NullLoggerFactory.Instance; [Test] @@ -25,7 +27,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -38,7 +40,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -52,7 +54,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -67,7 +69,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -81,7 +83,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -96,7 +98,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -110,7 +112,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -126,7 +128,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -142,7 +144,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -156,7 +158,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -169,7 +171,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -184,7 +186,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -198,7 +200,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -215,7 +217,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -231,7 +233,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -245,7 +247,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -258,7 +260,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -271,7 +273,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -284,7 +286,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -300,7 +302,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -317,7 +319,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -332,7 +334,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -349,7 +351,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -367,7 +369,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -384,7 +386,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -399,7 +401,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -414,7 +416,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -427,7 +429,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -440,7 +442,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -461,7 +463,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); @@ -474,7 +476,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -488,7 +490,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -502,7 +504,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); @@ -517,7 +519,7 @@ namespace Umbraco.Tests.Persistence { using (var scope = ScopeProvider.CreateScope()) { - var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion, GlobalSettings); + var helper = new DatabaseSchemaCreator(scope.Database, _loggerFactory.CreateLogger(), _loggerFactory, UmbracoVersion); helper.CreateTable(); helper.CreateTable(); diff --git a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs index 6301be051d..439036fa16 100644 --- a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs +++ b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs @@ -9,6 +9,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Components; using Umbraco.Tests.TestHelpers; using Current = Umbraco.Web.Composing.Current; @@ -25,10 +26,11 @@ namespace Umbraco.Tests.PropertyEditors Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture; var register = TestHelper.GetRegister(); - var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); register.Register(_ - => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()))); + => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings))); Current.Factory = composition.CreateFactory(); } diff --git a/src/Umbraco.Tests/Published/ConvertersTests.cs b/src/Umbraco.Tests/Published/ConvertersTests.cs index 27658f0858..5f1fd7c3fd 100644 --- a/src/Umbraco.Tests/Published/ConvertersTests.cs +++ b/src/Umbraco.Tests/Published/ConvertersTests.cs @@ -182,7 +182,7 @@ namespace Umbraco.Tests.Published // Current.Reset(); var register = TestHelper.GetRegister(); - var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.WithCollectionBuilder() .Append() diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs index f9320b3e60..d132e47a7c 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs @@ -2,17 +2,14 @@ using System.Collections.Generic; using System.Data; using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Legacy; using Umbraco.Core.Events; using Umbraco.Core.Hosting; -using Umbraco.Core.Install; -using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; @@ -23,6 +20,7 @@ using Umbraco.Core.Services; using Umbraco.Core.Services.Changes; using Umbraco.Core.Strings; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing.Objects; @@ -62,12 +60,7 @@ namespace Umbraco.Tests.PublishedContent var factory = Mock.Of(); Current.Factory = factory; - var configs = TestHelper.GetConfigs(); - Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs); - var globalSettings = new GlobalSettings(); var hostingEnvironment = Mock.Of(); - configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); - configs.Add(() => globalSettings); Mock.Get(factory).Setup(x => x.GetInstance(typeof(IPublishedModelFactory))).Returns(PublishedModelFactory); @@ -147,8 +140,9 @@ namespace Umbraco.Tests.PublishedContent _source = new TestDataSource(kits()); var typeFinder = TestHelper.GetTypeFinder(); - var settings = Mock.Of(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); // at last, create the complete NuCache snapshot service! var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; @@ -168,14 +162,14 @@ namespace Umbraco.Tests.PublishedContent Mock.Of(), new TestDefaultCultureAccessor(), _source, - globalSettings, + Options.Create(globalSettings), Mock.Of(), PublishedModelFactory, new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider(TestHelper.ShortStringHelper) }), hostingEnvironment, new MockShortStringHelper(), TestHelper.IOHelper, - settings); + Options.Create(nuCacheSettings)); // invariant is the current default _variationAccesor.VariationContext = new VariationContext(); diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs index 07b9c36d4a..90525e2b32 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs @@ -7,10 +7,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Legacy; using Umbraco.Core.Events; -using Umbraco.Core.Install; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; @@ -21,6 +18,7 @@ using Umbraco.Core.Services; using Umbraco.Core.Services.Changes; using Umbraco.Core.Strings; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing.Objects; @@ -55,12 +53,6 @@ namespace Umbraco.Tests.PublishedContent var factory = Mock.Of(); Current.Factory = factory; - var configs = TestHelper.GetConfigs(); - Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs); - var globalSettings = new GlobalSettings(); - configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); - configs.Add(() => globalSettings); - var publishedModelFactory = new NoopPublishedModelFactory(); Mock.Get(factory).Setup(x => x.GetInstance(typeof(IPublishedModelFactory))).Returns(publishedModelFactory); @@ -188,7 +180,9 @@ namespace Umbraco.Tests.PublishedContent _variationAccesor = new TestVariationContextAccessor(); var typeFinder = TestHelper.GetTypeFinder(); - var settings = Mock.Of(); + + var globalSettings = new GlobalSettingsBuilder().Build(); + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); // at last, create the complete NuCache snapshot service! var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; @@ -208,14 +202,14 @@ namespace Umbraco.Tests.PublishedContent Mock.Of(), new TestDefaultCultureAccessor(), dataSource, - globalSettings, + Microsoft.Extensions.Options.Options.Create(globalSettings), Mock.Of(), publishedModelFactory, new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider(TestHelper.ShortStringHelper) }), TestHelper.GetHostingEnvironment(), new MockShortStringHelper(), TestHelper.IOHelper, - settings); + Microsoft.Extensions.Options.Options.Create(nuCacheSettings)); // invariant is the current default _variationAccesor.VariationContext = new VariationContext(); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentLanguageVariantTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentLanguageVariantTests.cs index 8c1024351b..50e82998f9 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentLanguageVariantTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentLanguageVariantTests.cs @@ -7,6 +7,7 @@ using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web; @@ -34,11 +35,11 @@ namespace Umbraco.Tests.PublishedContent private static void MockLocalizationService(ServiceContext serviceContext) { - var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); // Set up languages. // Spanish falls back to English and Italian to Spanish (and then to English). // French has no fall back. // Danish, Swedish and Norweigan create an invalid loop. + var globalSettings = new GlobalSettingsBuilder().Build(); var languages = new List { new Language(globalSettings, "en-US") { Id = 1, CultureName = "English", IsDefault = true }, diff --git a/src/Umbraco.Tests/Routing/BaseUrlProviderTest.cs b/src/Umbraco.Tests/Routing/BaseUrlProviderTest.cs new file mode 100644 index 0000000000..a4f472898e --- /dev/null +++ b/src/Umbraco.Tests/Routing/BaseUrlProviderTest.cs @@ -0,0 +1,45 @@ +using System.Linq; +using Moq; +using Umbraco.Core; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web; +using Umbraco.Web.Routing; + +namespace Umbraco.Tests.Routing +{ + public abstract class BaseUrlProviderTest : BaseWebTest + { + protected IUmbracoContextAccessor UmbracoContextAccessor { get; } = new TestUmbracoContextAccessor(); + + protected abstract bool HideTopLevelNodeFromPath { get; } + + protected override void Compose() + { + base.Compose(); + Composition.Register(); + } + + protected override void ComposeSettings() + { + var contentSettings = new ContentSettingsBuilder().Build(); + var userPasswordConfigurationSettings = new UserPasswordConfigurationSettingsBuilder().Build(); + + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(contentSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(userPasswordConfigurationSettings)); + } + + protected IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext, DefaultUrlProvider urlProvider) + { + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + return new UrlProvider( + new TestUmbracoContextAccessor(umbracoContext), + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), + new UrlProviderCollection(new[] { urlProvider }), + new MediaUrlProviderCollection(Enumerable.Empty()), + Mock.Of()); + } + } +} diff --git a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs index d3c820d239..069aead6b3 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using Umbraco.Core; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.Routing; @@ -17,7 +18,8 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlAsString); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByIdPath(SettingsForTests.GenerateMockWebRoutingSettings(), Logger, Factory.GetInstance()); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + var lookup = new ContentFinderByIdPath(Microsoft.Extensions.Options.Options.Create(webRoutingSettings), Logger, Factory.GetInstance()); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs index e8b8bab22b..14a7ec3ab1 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs @@ -8,6 +8,7 @@ using Umbraco.Web.Routing; using Umbraco.Core.Models; using Umbraco.Tests.Testing; using Current = Umbraco.Web.Composing.Current; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Routing { @@ -30,15 +31,17 @@ namespace Umbraco.Tests.Routing [TestCase("/home/Sub1.aspx/blah")] public void Match_Document_By_Url_With_Template(string urlAsString) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder() + .WithHideTopLevelNodeFromPath(false) + .Build(); var template1 = CreateTemplate("test"); var template2 = CreateTemplate("blah"); - var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings: globalSettings); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByUrlAndTemplate(Logger, ServiceContext.FileService, ServiceContext.ContentTypeService, SettingsForTests.GenerateMockWebRoutingSettings()); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + var lookup = new ContentFinderByUrlAndTemplate(Logger, ServiceContext.FileService, ServiceContext.ContentTypeService, Microsoft.Extensions.Options.Options.Create(webRoutingSettings)); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs index f7b6762774..0614d4a2bb 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Web.Composing; using Umbraco.Core.Configuration; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web.Routing; @@ -28,15 +29,15 @@ namespace Umbraco.Tests.Routing [TestCase("/test-page", 1172)] public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId) { - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(true).Build(); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettings, snapshotService: snapshotService); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); - Assert.IsTrue(Current.Configs.Global().HideTopLevelNodeFromPath); + Assert.IsTrue(globalSettings.HideTopLevelNodeFromPath); // FIXME: debugging - going further down, the routes cache is NOT empty?! if (urlString == "/home/sub1") @@ -63,15 +64,14 @@ namespace Umbraco.Tests.Routing [TestCase("/home/Sub1.aspx", 1173)] public void Match_Document_By_Url(string urlString, int expectedId) { - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); - Assert.IsFalse(Current.Configs.Global().HideTopLevelNodeFromPath); + Assert.IsFalse(globalSettings.HideTopLevelNodeFromPath); var result = lookup.TryFindContent(frequest); @@ -88,10 +88,9 @@ namespace Umbraco.Tests.Routing [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] public void Match_Document_By_Url_With_Special_Characters(string urlString, int expectedId) { - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); @@ -115,10 +114,9 @@ namespace Umbraco.Tests.Routing [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] public void Match_Document_By_Url_With_Special_Characters_Using_Hostname(string urlString, int expectedId) { - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/")); @@ -144,10 +142,9 @@ namespace Umbraco.Tests.Routing [TestCase("/æøå/home/sub1/custom-sub-4-with-æøå", 1180)] public void Match_Document_By_Url_With_Special_Characters_In_Hostname(string urlString, int expectedId) { - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå")); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs index ac2e62b1ef..622df53d9e 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs @@ -4,6 +4,7 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; @@ -127,10 +128,9 @@ namespace Umbraco.Tests.Routing { SetDomains3(); - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(true).Build(); - var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(Factory); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -169,10 +169,9 @@ namespace Umbraco.Tests.Routing // defaults depend on test environment expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(true).Build(); - var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(Factory); var frequest = publishedRouter.CreateRequest(umbracoContext); diff --git a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs index a81f345e38..0d39092b88 100644 --- a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs +++ b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs @@ -6,6 +6,7 @@ using Umbraco.Web.Routing; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Routing { @@ -266,10 +267,10 @@ namespace Umbraco.Tests.Routing { SetDomains1(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); + + var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(Factory); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -315,10 +316,9 @@ namespace Umbraco.Tests.Routing // defaults depend on test environment expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(Factory); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -370,9 +370,8 @@ namespace Umbraco.Tests.Routing { SetDomains3(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); + var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings); var publishedRouter = CreatePublishedRouter(Factory); var frequest = publishedRouter.CreateRequest(umbracoContext); diff --git a/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs b/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs index 4f11802b43..27027c007f 100644 --- a/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs +++ b/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs @@ -1,26 +1,35 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Globalization; using System.Linq; using Moq; using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Web.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; -using Umbraco.Web; -using Umbraco.Web.Routing; using Umbraco.Tests.Common; -using SettingsForTests = Umbraco.Tests.TestHelpers.SettingsForTests; +using Umbraco.Tests.Common.Builders; +using Umbraco.Tests.TestHelpers.Entities; +using Umbraco.Web.Routing; namespace Umbraco.Tests.Routing { [TestFixture] public class GetContentUrlsTests : UrlRoutingTestBase { + private GlobalSettings _globalSettings; + private WebRoutingSettings _webRoutingSettings; + private RequestHandlerSettings _requestHandlerSettings; + + public override void SetUp() + { + base.SetUp(); + + _globalSettings = new GlobalSettingsBuilder().Build(); + _webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + _requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); + } + private ILocalizedTextService GetTextService() { var textService = Mock.Of( @@ -34,7 +43,7 @@ namespace Umbraco.Tests.Routing { var allLangs = isoCodes .Select(CultureInfo.GetCultureInfo) - .Select(culture => new Language(TestObjects.GetGlobalSettings(), culture.Name) + .Select(culture => new Language(_globalSettings, culture.Name) { CultureName = culture.DisplayName, IsDefault = true, @@ -78,15 +87,17 @@ namespace Umbraco.Tests.Routing content.Path = "-1,1046"; content.Published = true; - var umbracoSettings = SettingsForTests.GenerateMockRequestHandlerSettings(); - var umbContext = GetUmbracoContext("http://localhost:8000"); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbContext); - var urlProvider = new DefaultUrlProvider(umbracoSettings, Logger, TestObjects.GetGlobalSettings(), new SiteDomainHelper(), + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(_requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), + new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = new UrlProvider( umbracoContextAccessor, - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(_webRoutingSettings), new UrlProviderCollection(new []{urlProvider}), new MediaUrlProviderCollection(Enumerable.Empty()), Mock.Of() @@ -123,15 +134,16 @@ namespace Umbraco.Tests.Routing child.Path = "-1,1046,1173"; child.Published = true; - var umbracoSettings = SettingsForTests.GenerateMockRequestHandlerSettings(); - - var umbContext = GetUmbracoContext("http://localhost:8000"); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbContext); - var urlProvider = new DefaultUrlProvider(umbracoSettings, Logger, TestObjects.GetGlobalSettings(), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(_requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), + new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = new UrlProvider( umbracoContextAccessor, - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(_webRoutingSettings), new UrlProviderCollection(new []{urlProvider}), new MediaUrlProviderCollection(Enumerable.Empty()), Mock.Of() diff --git a/src/Umbraco.Tests/Routing/MediaUrlProviderTests.cs b/src/Umbraco.Tests/Routing/MediaUrlProviderTests.cs index e55a22065b..b134934ee9 100644 --- a/src/Umbraco.Tests/Routing/MediaUrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/MediaUrlProviderTests.cs @@ -13,6 +13,7 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.ValueConverters; using Umbraco.Core.Services; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -34,12 +35,12 @@ namespace Umbraco.Tests.Routing var logger = Mock.Of(); var mediaFileSystemMock = Mock.Of(); - var contentSection = Mock.Of(); + var contentSettings = new ContentSettingsBuilder().Build(); var dataTypeService = Mock.Of(); var propertyEditors = new MediaUrlGeneratorCollection(new IMediaUrlGenerator[] { - new FileUploadPropertyEditor(logger, mediaFileSystemMock, contentSection, dataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper), - new ImageCropperPropertyEditor(logger, mediaFileSystemMock, contentSection, dataTypeService, LocalizationService, IOHelper, ShortStringHelper, LocalizedTextService), + new FileUploadPropertyEditor(logger, mediaFileSystemMock, Microsoft.Extensions.Options.Options.Create(contentSettings), dataTypeService, LocalizationService, LocalizedTextService, ShortStringHelper), + new ImageCropperPropertyEditor(logger, mediaFileSystemMock, Microsoft.Extensions.Options.Options.Create(contentSettings), dataTypeService, LocalizationService, IOHelper, ShortStringHelper, LocalizedTextService), }); _mediaUrlProvider = new DefaultMediaUrlProvider(propertyEditors, UriUtility); } @@ -149,9 +150,10 @@ namespace Umbraco.Tests.Routing private IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext) { + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); return new UrlProvider( new TestUmbracoContextAccessor(umbracoContext), - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(Enumerable.Empty()), new MediaUrlProviderCollection(new []{_mediaUrlProvider}), Mock.Of() diff --git a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index 3692e1a0cc..866c113d5b 100644 --- a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs +++ b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs @@ -2,32 +2,37 @@ using System.Linq; using System.Web.Mvc; using System.Web.Routing; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Stubs; -using Umbraco.Web; -using Umbraco.Web.Models; -using Umbraco.Web.Mvc; -using Umbraco.Web.WebApi; -using Umbraco.Core.Strings; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; +using Umbraco.Core.Logging; +using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Runtime; using Umbraco.Core.Services; +using Umbraco.Core.Strings; +using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.PublishedContent; +using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Tests.Testing; +using Umbraco.Web; +using Umbraco.Web.Models; +using Umbraco.Web.Mvc; using Umbraco.Web.Runtime; +using Umbraco.Web.WebApi; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; using Current = Umbraco.Web.Composing.Current; using ILogger = Umbraco.Core.Logging.ILogger; -using Umbraco.Tests.Common; namespace Umbraco.Tests.Routing { @@ -50,8 +55,8 @@ namespace Umbraco.Tests.Routing public class TestRuntime : CoreRuntime { - public TestRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) - : base(configs, umbracoVersion, ioHelper, Mock.Of(), Mock.Of(), Mock.Of(), new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, TestHelper.GetTypeFinder(), AppCaches.NoCache) + public TestRuntime(GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) + : base(globalSettings, connectionStrings,umbracoVersion, ioHelper, Mock.Of(), NullLoggerFactory.Instance, Mock.Of(), new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, TestHelper.GetTypeFinder(), AppCaches.NoCache) { } @@ -70,7 +75,8 @@ namespace Umbraco.Tests.Routing var umbracoApiControllerTypes = new UmbracoApiControllerTypeCollection(Composition.TypeLoader.GetUmbracoApiControllers()); Composition.RegisterUnique(umbracoApiControllerTypes); - Composition.RegisterUnique(_ => new DefaultShortStringHelper(TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings())); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + Composition.RegisterUnique(_ => new DefaultShortStringHelper(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings))); } public override void TearDown() @@ -150,7 +156,7 @@ namespace Umbraco.Tests.Routing var handler = new RenderRouteHandler(umbracoContext, new TestControllerFactory(umbracoContextAccessor, Mock.Of(), context => { - return new CustomDocumentController(Factory.GetInstance(), + return new CustomDocumentController(Factory.GetInstance>(), umbracoContextAccessor, Factory.GetInstance(), Factory.GetInstance(), @@ -192,7 +198,7 @@ namespace Umbraco.Tests.Routing /// public class CustomDocumentController : RenderMvcController { - public CustomDocumentController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, Umbraco.Core.Logging.ILogger logger) + public CustomDocumentController(IOptions globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, Umbraco.Core.Logging.ILogger logger) : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, logger) { } diff --git a/src/Umbraco.Tests/Routing/RoutableDocumentFilterTests.cs b/src/Umbraco.Tests/Routing/RoutableDocumentFilterTests.cs index a78459fa39..c0b83b08cb 100644 --- a/src/Umbraco.Tests/Routing/RoutableDocumentFilterTests.cs +++ b/src/Umbraco.Tests/Routing/RoutableDocumentFilterTests.cs @@ -1,9 +1,8 @@ -using System.Web.Mvc; +using System; +using System.Web.Mvc; using System.Web.Routing; -using Moq; using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web; @@ -51,12 +50,13 @@ namespace Umbraco.Tests.Routing public void Is_Reserved_By_Route(string url, bool shouldMatch) { //reset the app config, we only want to test routes not the hard coded paths - // TODO: Why are we using and modifying the global IGlobalSettings and not just a custom one? - var globalSettingsMock = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.ReservedPaths).Returns(""); - globalSettingsMock.Setup(x => x.ReservedUrls).Returns(""); - var routableDocFilter = new RoutableDocumentFilter(globalSettingsMock.Object, IOHelper); + var globalSettings = new GlobalSettingsBuilder() + .WithReservedPaths(string.Empty) + .WithReservedUrls(String.Empty) + .Build(); + + var routableDocFilter = new RoutableDocumentFilter(globalSettings, IOHelper); var routes = new RouteCollection(); diff --git a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs index 4e28949ca7..b1dcc6de9d 100644 --- a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs +++ b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs @@ -1,20 +1,13 @@ using System; -using System.IO; using System.Threading; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Logging; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Web; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Sync; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.Services; -using Umbraco.Web.PublishedCache; -using Umbraco.Web.Routing; namespace Umbraco.Tests.Routing { @@ -31,7 +24,9 @@ namespace Umbraco.Tests.Routing // FIXME: be able to get the UmbracoModule from the container. any reason settings were from testobjects? //create the module var logger = Mock.Of(); - var globalSettings = TestObjects.GetGlobalSettings(); + var globalSettings = new GlobalSettingsBuilder() + .WithReservedPaths((GlobalSettings.StaticReservedPaths + "~/umbraco")) + .Build(); var runtime = Umbraco.Core.RuntimeState.Booting(); _module = new UmbracoInjectedModule diff --git a/src/Umbraco.Tests/Routing/UrlProviderWithHideTopLevelNodeFromPathTests.cs b/src/Umbraco.Tests/Routing/UrlProviderWithHideTopLevelNodeFromPathTests.cs new file mode 100644 index 0000000000..2c5bfc52e9 --- /dev/null +++ b/src/Umbraco.Tests/Routing/UrlProviderWithHideTopLevelNodeFromPathTests.cs @@ -0,0 +1,59 @@ +using NUnit.Framework; +using Umbraco.Core.Configuration.Models; +using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; +using Umbraco.Tests.Testing; +using Umbraco.Web.Routing; + +namespace Umbraco.Tests.Routing +{ + [TestFixture] + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] + public class UrlProviderWithHideTopLevelNodeFromPathTests : BaseUrlProviderTest + { + private GlobalSettings _globalSettings; + + public override void SetUp() + { + _globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(HideTopLevelNodeFromPath).Build(); + base.SetUp(); + PublishedSnapshotService = CreatePublishedSnapshotService(_globalSettings); + + + } + + protected override bool HideTopLevelNodeFromPath => true; + + protected override void ComposeSettings() + { + base.ComposeSettings(); + Composition.RegisterUnique(x => Microsoft.Extensions.Options.Options.Create(_globalSettings)); + } + + [TestCase(1046, "/")] + [TestCase(1173, "/sub1/")] + [TestCase(1174, "/sub1/sub2/")] + [TestCase(1176, "/sub1/sub-3/")] + [TestCase(1177, "/sub1/custom-sub-1/")] + [TestCase(1178, "/sub1/custom-sub-2/")] + [TestCase(1175, "/sub-2/")] + [TestCase(1172, "/test-page/")] // not hidden because not first root + public void Get_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) + { + + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); + + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: _globalSettings, snapshotService:PublishedSnapshotService); + var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), + new SiteDomainHelper(), umbracoContextAccessor, UriUtility); + var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); + + var result = publishedUrlProvider.GetUrl(nodeId); + Assert.AreEqual(niceUrlMatch, result); + } + } +} diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs similarity index 66% rename from src/Umbraco.Tests/Routing/UrlProviderTests.cs rename to src/Umbraco.Tests/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs index 1ff0a2b33d..e8f3bf97fd 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderWithoutHideTopLevelNodeFromPathTests.cs @@ -4,38 +4,36 @@ using System.Globalization; using System.Linq; using Moq; using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Web.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; +using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.PublishedContent; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; -using Umbraco.Web; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; -using Umbraco.Tests.Common; namespace Umbraco.Tests.Routing { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] - public class UrlProviderTests : BaseWebTest + public class UrlProviderWithoutHideTopLevelNodeFromPathTests : BaseUrlProviderTest { - private IUmbracoContextAccessor UmbracoContextAccessor { get; } = new TestUmbracoContextAccessor(); + private readonly GlobalSettings _globalSettings; - protected override void Compose() + public UrlProviderWithoutHideTopLevelNodeFromPathTests() { - base.Compose(); - Composition.Register(); + _globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(HideTopLevelNodeFromPath).Build(); } + protected override bool HideTopLevelNodeFromPath => false; + protected override void ComposeSettings() { - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockGlobalSettings); + base.ComposeSettings(); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(_globalSettings)); } /// @@ -45,19 +43,17 @@ namespace Umbraco.Tests.Routing [Test] public void Ensure_Cache_Is_Correct() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(false).Build(); - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: _globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); - var requestHandlerMock = Mock.Get(requestHandlerSettings); - requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none) var samples = new Dictionary { { 1046, "/home" }, @@ -98,18 +94,6 @@ namespace Umbraco.Tests.Routing Assert.AreEqual(0, cachedIds.Count); } - private IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext, DefaultUrlProvider urlProvider) - { - return new UrlProvider( - new TestUmbracoContextAccessor(umbracoContext), - TestHelper.WebRoutingSettings, - new UrlProviderCollection(new []{urlProvider}), - new MediaUrlProviderCollection(Enumerable.Empty()), - Mock.Of() - ); - } - - // test hideTopLevelNodeFromPath false [TestCase(1046, "/home/")] [TestCase(1173, "/home/sub1/")] [TestCase(1174, "/home/sub1/sub2/")] @@ -120,42 +104,14 @@ namespace Umbraco.Tests.Routing [TestCase(1172, "/test-page/")] public void Get_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - - - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: _globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, - new SiteDomainHelper(), umbracoContextAccessor, UriUtility); - var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); - - var result = publishedUrlProvider.GetUrl(nodeId); - Assert.AreEqual(niceUrlMatch, result); - } - - // no need for umbracoUseDirectoryUrls test = should be handled by UriUtilityTests - - // test hideTopLevelNodeFromPath true - [TestCase(1046, "/")] - [TestCase(1173, "/sub1/")] - [TestCase(1174, "/sub1/sub2/")] - [TestCase(1176, "/sub1/sub-3/")] - [TestCase(1177, "/sub1/custom-sub-1/")] - [TestCase(1178, "/sub1/custom-sub-2/")] - [TestCase(1175, "/sub-2/")] - [TestCase(1172, "/test-page/")] // not hidden because not first root - public void Get_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) - { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); - - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings.Object); - var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -168,11 +124,7 @@ namespace Umbraco.Tests.Routing { const string currentUri = "http://example.us/test"; - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Culture); var publishedContent = new SolidPublishedContent(contentType) { Id = 1234 }; @@ -193,12 +145,14 @@ namespace Umbraco.Tests.Routing snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())) .Returns(snapshot); - var umbracoContext = GetUmbracoContext(currentUri, - globalSettings: globalSettings.Object, + globalSettings: _globalSettings, snapshotService: snapshotService.Object); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -216,10 +170,7 @@ namespace Umbraco.Tests.Routing { const string currentUri = "http://example.fr/test"; - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Culture); var publishedContent = new SolidPublishedContent(contentType) { Id = 1234 }; @@ -249,12 +200,14 @@ namespace Umbraco.Tests.Routing snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())) .Returns(snapshot); - var umbracoContext = GetUmbracoContext(currentUri, - globalSettings: globalSettings.Object, + globalSettings: _globalSettings, snapshotService: snapshotService.Object); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -272,10 +225,7 @@ namespace Umbraco.Tests.Routing { const string currentUri = "http://example.us/test"; - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); var contentType = new PublishedContentType(Guid.NewGuid(), 666, "alias", PublishedItemType.Content, Enumerable.Empty(), Enumerable.Empty(), ContentVariation.Culture); var publishedContent = new SolidPublishedContent(contentType) { Id = 1234 }; @@ -306,10 +256,13 @@ namespace Umbraco.Tests.Routing .Returns(snapshot); var umbracoContext = GetUmbracoContext(currentUri, - globalSettings: globalSettings.Object, + globalSettings: _globalSettings, snapshotService: snapshotService.Object); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); @@ -323,15 +276,14 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_Relative_Or_Absolute() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - - - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, globalSettings: globalSettings.Object); + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, globalSettings: _globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -344,14 +296,13 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_Unpublished() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); - var requestHandlerSettings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); - - var urlProvider = new DefaultUrlProvider(requestHandlerSettings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(_globalSettings), new SiteDomainHelper(), UmbracoContextAccessor, UriUtility); - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, globalSettings: globalSettings.Object); + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, globalSettings: _globalSettings); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); //mock the Umbraco settings that we need diff --git a/src/Umbraco.Tests/Routing/UrlRoutesTests.cs b/src/Umbraco.Tests/Routing/UrlRoutesTests.cs index 0c608d3e94..d0dd708561 100644 --- a/src/Umbraco.Tests/Routing/UrlRoutesTests.cs +++ b/src/Umbraco.Tests/Routing/UrlRoutesTests.cs @@ -5,6 +5,7 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -196,10 +197,9 @@ DetermineRouteById(id): [TestCase(2006, false, "/x/b/e")] public void GetRouteByIdNoHide(int id, bool hide, string expected) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(hide).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); @@ -220,10 +220,10 @@ DetermineRouteById(id): [TestCase(2006, true, "/b/e")] // risky! public void GetRouteByIdHide(int id, bool hide, string expected) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(hide).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings, snapshotService: snapshotService); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); @@ -234,10 +234,10 @@ DetermineRouteById(id): [Test] public void GetRouteByIdCache() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings, snapshotService: snapshotService); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); @@ -265,10 +265,10 @@ DetermineRouteById(id): [TestCase("/x", false, 2000)] public void GetByRouteNoHide(string route, bool hide, int expected) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(hide).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings, snapshotService: snapshotService); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); @@ -296,10 +296,10 @@ DetermineRouteById(id): [TestCase("/b/c", true, 1002)] // (hence the 2005 collision) public void GetByRouteHide(string route, bool hide, int expected) { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(hide).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings, snapshotService: snapshotService); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); @@ -319,10 +319,10 @@ DetermineRouteById(id): [Test] public void GetByRouteCache() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); + var snapshotService = CreatePublishedSnapshotService(globalSettings); + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings, snapshotService:snapshotService); var cache = umbracoContext.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); diff --git a/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs index d8e373b428..a960cdba53 100644 --- a/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs @@ -4,13 +4,12 @@ using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; -using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.Routing; @@ -178,14 +177,15 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "https://domain1.com", false, "/1001-1/")] public void Get_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -212,14 +212,14 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")] public void Get_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains - - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -238,14 +238,15 @@ namespace Umbraco.Tests.Routing [TestCase(1002, "http://domain1.com", false, "/1002/")] public void Get_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -270,14 +271,16 @@ namespace Umbraco.Tests.Routing [TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")] public void Get_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -292,14 +295,16 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_DomainsAndCache() { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -356,14 +361,16 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_Relative_Or_Absolute() { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -381,14 +388,16 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_Alternate() { - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); - var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -408,9 +417,10 @@ namespace Umbraco.Tests.Routing private IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext, DefaultUrlProvider urlProvider) { + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); return new UrlProvider( new TestUmbracoContextAccessor(umbracoContext), - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(new []{urlProvider}), new MediaUrlProviderCollection(Enumerable.Empty()), Mock.Of() diff --git a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs index 13ee5afa3e..03faa70d8c 100644 --- a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs +++ b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs @@ -3,15 +3,14 @@ using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; -using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; using Umbraco.Core.Services; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Web; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Routing { @@ -33,19 +32,20 @@ namespace Umbraco.Tests.Routing [Test] public void DoNotPolluteCache() { - var globalSettings = Mock.Get(Factory.GetInstance()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); - - var settings = TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings(); + var globalSettings = new GlobalSettingsBuilder().WithHideTopLevelNodeFromPath(false).Build(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().WithAddTrailingSlash(true).Build(); SetDomains1(); const string url = "http://domain1.com/1001-1/1001-1-1"; // get the nice url for 100111 - var umbracoContext = GetUmbracoContext(url, 9999, globalSettings:globalSettings.Object); + var umbracoContext = GetUmbracoContext(url, 9999, globalSettings: globalSettings); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var urlProvider = new DefaultUrlProvider(settings, Logger, globalSettings.Object, + var urlProvider = new DefaultUrlProvider( + Microsoft.Extensions.Options.Options.Create(requestHandlerSettings), + Logger, + Microsoft.Extensions.Options.Options.Create(globalSettings), new SiteDomainHelper(), umbracoContextAccessor, UriUtility); var publishedUrlProvider = GetPublishedUrlProvider(umbracoContext, urlProvider); @@ -97,9 +97,10 @@ namespace Umbraco.Tests.Routing private IPublishedUrlProvider GetPublishedUrlProvider(IUmbracoContext umbracoContext, DefaultUrlProvider urlProvider) { + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); return new UrlProvider( new TestUmbracoContextAccessor(umbracoContext), - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(new []{urlProvider}), new MediaUrlProviderCollection(Enumerable.Empty()), Mock.Of() diff --git a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs index 65aa625f8e..4416647f15 100644 --- a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs +++ b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Data; using Examine; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; @@ -9,21 +9,20 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Events; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Exceptions; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Runtime; -using Umbraco.Core.Scoping; using Umbraco.Net; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web; using Umbraco.Web.Hosting; using Umbraco.Web.Runtime; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; using Current = Umbraco.Web.Composing.Current; using ILogger = Umbraco.Core.Logging.ILogger; @@ -86,7 +85,11 @@ namespace Umbraco.Tests.Runtimes // test application public class TestUmbracoApplication : UmbracoApplicationBase { - public TestUmbracoApplication() : base(_logger, _configs, _ioHelper, _profiler, new AspNetHostingEnvironment(_hostingSettings), new AspNetBackOfficeInfo(_globalSettings, _ioHelper, _loggerFactory.CreateLogger(), _settings)) + public TestUmbracoApplication() : base(_logger, + new SecuritySettings(), + new GlobalSettings(), + new ConnectionStrings(), + _ioHelper, _profiler, new AspNetHostingEnvironment(Options.Create(new HostingSettings())), new AspNetBackOfficeInfo(_globalSettings, _ioHelper, _loggerFactory.CreateLogger(), Options.Create(new WebRoutingSettings()))) { _loggerFactory = LoggerFactory.Create(builder => builder.AddDebug()); _logger = _loggerFactory.CreateLogger(); @@ -96,34 +99,21 @@ namespace Umbraco.Tests.Runtimes private static Microsoft.Extensions.Logging.ILogger _logger; private static readonly IIOHelper _ioHelper = TestHelper.IOHelper; private static readonly IProfiler _profiler = new TestProfiler(); - private static readonly Configs _configs = GetConfigs(); - private static readonly IGlobalSettings _globalSettings = SettingsForTests.DefaultGlobalSettings; - private static readonly IHostingSettings _hostingSettings = SettingsForTests.DefaultHostingSettings; - private static readonly IContentSettings _contentSettings = SettingsForTests.GenerateMockContentSettings(); - private static readonly IWebRoutingSettings _settings = _configs.WebRouting(); - - private static Configs GetConfigs() - { - var configs = new ConfigsFactory().Create(); - configs.Add(() => _globalSettings); - configs.Add(() => _contentSettings); - configs.Add(() => _hostingSettings); - return configs; - } + private static readonly GlobalSettings _globalSettings = new GlobalSettings(); public IRuntime Runtime { get; private set; } - protected override IRuntime GetRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, Microsoft.Extensions.Logging.ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) + protected override IRuntime GetRuntime(GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, Microsoft.Extensions.Logging.ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) { - return Runtime = new TestRuntime(configs, umbracoVersion, ioHelper, logger, loggerFactory, profiler, hostingEnvironment, backOfficeInfo); + return Runtime = new TestRuntime(globalSettings, connectionStrings, umbracoVersion, ioHelper, logger, loggerFactory, profiler, hostingEnvironment, backOfficeInfo); } } // test runtime public class TestRuntime : CoreRuntime { - public TestRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, Microsoft.Extensions.Logging.ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) - :base(configs, umbracoVersion, ioHelper, logger, loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, TestHelper.GetTypeFinder(), AppCaches.NoCache) + public TestRuntime(GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, Microsoft.Extensions.Logging.ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) + :base(globalSettings, connectionStrings,umbracoVersion, ioHelper, logger, loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, TestHelper.GetTypeFinder(), AppCaches.NoCache) { } @@ -175,7 +165,6 @@ namespace Umbraco.Tests.Runtimes public void Compose(Composition composition) { - composition.Register(factory => SettingsForTests.GenerateMockContentSettings()); composition.RegisterUnique(); composition.Components().Append(); diff --git a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs index a3b5de755f..ec081926f4 100644 --- a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs +++ b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs @@ -38,6 +38,8 @@ using Current = Umbraco.Web.Composing.Current; using Umbraco.Tests.Common; using Umbraco.Tests.Common.Composing; using Umbraco.Core.Media; +using Umbraco.Tests.Common.Builders; +using Microsoft.Extensions.Options; namespace Umbraco.Tests.Runtimes { @@ -65,10 +67,10 @@ namespace Umbraco.Tests.Runtimes var profiler = new LogProfiler(logger); var profilingLogger = new ProfilingLogger(loggerFactory.CreateLogger("ProfilingLogger"), profiler); var appCaches = AppCaches.Disabled; - var globalSettings = TestHelper.GetConfigs().Global(); - var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); var typeFinder = TestHelper.GetTypeFinder(); - var databaseFactory = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connectionStrings, new Lazy(() => factory.GetInstance()), TestHelper.DbProviderFactoryCreator); + var databaseFactory = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), loggerFactory, Options.Create(globalSettings), Options.Create(connectionStrings), new Lazy(() => factory.GetInstance()), TestHelper.DbProviderFactoryCreator); var ioHelper = TestHelper.IOHelper; var hostingEnvironment = Mock.Of(); var typeLoader = new TypeLoader(typeFinder, appCaches.RuntimeCache, new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")), loggerFactory.CreateLogger("TypeLoader"), profilingLogger); @@ -76,17 +78,15 @@ namespace Umbraco.Tests.Runtimes var umbracoVersion = TestHelper.GetUmbracoVersion(); var backOfficeInfo = TestHelper.GetBackOfficeInfo(); var runtimeState = new RuntimeState(globalSettings, umbracoVersion, databaseFactory, loggerFactory.CreateLogger()); - var configs = TestHelper.GetConfigs(); var variationContextAccessor = TestHelper.VariationContextAccessor; - // create the register and the composition var register = TestHelper.GetRegister(); - var composition = new Composition(register, typeLoader, profilingLogger, runtimeState, configs, ioHelper, appCaches); + var composition = new Composition(register, typeLoader, profilingLogger, runtimeState, ioHelper, appCaches); composition.RegisterEssentials(loggerFactory.CreateLogger("Essentials"), profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState, typeFinder, ioHelper, umbracoVersion, TestHelper.DbProviderFactoryCreator, hostingEnvironment, backOfficeInfo); // create the core runtime and have it compose itself - var coreRuntime = new CoreRuntime(configs, umbracoVersion, ioHelper, loggerFactory.CreateLogger("CoreRunTime"), loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, typeFinder, AppCaches.NoCache); + var coreRuntime = new CoreRuntime(globalSettings, connectionStrings, umbracoVersion, ioHelper, loggerFactory.CreateLogger("CoreRunTime"), loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, typeFinder, AppCaches.NoCache); // determine actual runtime level runtimeState.DetermineRuntimeLevel(); @@ -120,14 +120,29 @@ namespace Umbraco.Tests.Runtimes composition.RegisterUnique(); composition.RegisterUnique(_ => new MediaUrlProviderCollection(Enumerable.Empty())); + // TODO: found these registration were necessary here as dependencies for ComponentCollection + // are not resolved. Need to check this if these explicit registrations are the best way to handle this. + var contentSettings = new ContentSettingsBuilder().Build(); + var coreDebugSettings = new CoreDebugSettingsBuilder().Build(); + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var userPasswordConfigurationSettings = new UserPasswordConfigurationSettingsBuilder().Build(); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + + composition.Register(x => Options.Create(globalSettings)); + composition.Register(x => Options.Create(contentSettings)); + composition.Register(x => Options.Create(coreDebugSettings)); + composition.Register(x => Options.Create(nuCacheSettings)); + composition.Register(x => Options.Create(requestHandlerSettings)); + composition.Register(x => Options.Create(userPasswordConfigurationSettings)); + composition.Register(x => Options.Create(webRoutingSettings)); + // initialize some components only/individually composition.WithCollectionBuilder() .Clear() .Append(); // configure - composition.Configs.Add(() => TestHelpers.SettingsForTests.DefaultGlobalSettings); - composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); // create and register the factory Current.Factory = factory = composition.CreateFactory(); @@ -165,7 +180,7 @@ namespace Umbraco.Tests.Runtimes var scopeProvider = factory.GetInstance(); using (var scope = scopeProvider.CreateScope()) { - var creator = new DatabaseSchemaCreator(scope.Database, loggerFactory.CreateLogger(), loggerFactory, umbracoVersion, TestHelpers.SettingsForTests.DefaultGlobalSettings); + var creator = new DatabaseSchemaCreator(scope.Database, loggerFactory.CreateLogger(), loggerFactory, umbracoVersion); creator.InitializeDatabaseSchema(); scope.Complete(); } @@ -272,16 +287,18 @@ namespace Umbraco.Tests.Runtimes Mock.Get(runtimeState).Setup(x => x.Level).Returns(RuntimeLevel.Run); var mainDom = Mock.Of(); Mock.Get(mainDom).Setup(x => x.IsMainDom).Returns(true); - var configs = TestHelper.GetConfigs(); // create the register and the composition var register = TestHelper.GetRegister(); - var composition = new Composition(register, typeLoader, profilingLogger, runtimeState, configs, ioHelper, appCaches); + var composition = new Composition(register, typeLoader, profilingLogger, runtimeState, ioHelper, appCaches); var umbracoVersion = TestHelper.GetUmbracoVersion(); composition.RegisterEssentials(loggerFactory.CreateLogger("RegisterEssentials"), profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState, typeFinder, ioHelper, umbracoVersion, TestHelper.DbProviderFactoryCreator, hostingEnvironment, backOfficeInfo); // create the core runtime and have it compose itself - var coreRuntime = new CoreRuntime(configs, umbracoVersion, ioHelper, loggerFactory.CreateLogger("CoreRuntime"), loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, typeFinder, AppCaches.NoCache); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); + + var coreRuntime = new CoreRuntime(globalSettings, connectionStrings, umbracoVersion, ioHelper, loggerFactory.CreateLogger("CoreRuntime"), loggerFactory, profiler, new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, TestHelper.DbProviderFactoryCreator, TestHelper.MainDom, typeFinder, AppCaches.NoCache); // get the components // all of them? diff --git a/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs b/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs index f31158b319..a60dc43a9d 100644 --- a/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopeEventDispatcherTests.cs @@ -18,6 +18,7 @@ using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Services; using Umbraco.Tests.Components; using Current = Umbraco.Web.Composing.Current; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Scoping { @@ -36,28 +37,22 @@ namespace Umbraco.Tests.Scoping var register = TestHelper.GetRegister(); - var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(register, TestHelper.GetMockedTypeLoader(), Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); _testObjects = new TestObjects(register); - composition.RegisterUnique(factory => new FileSystems(factory, factory.TryGetInstance>(), factory.TryGetInstance(), TestHelper.IOHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment())); + var globalSettings = new GlobalSettingsBuilder().Build(); + composition.RegisterUnique(factory => new FileSystems(factory, factory.TryGetInstance>(), factory.TryGetInstance(), TestHelper.IOHelper, Microsoft.Extensions.Options.Options.Create(globalSettings), TestHelper.GetHostingEnvironment())); composition.WithCollectionBuilder(); - composition.Configs.Add(() => SettingsForTests.DefaultGlobalSettings); - composition.Configs.Add(SettingsForTests.GenerateMockContentSettings); - Current.Reset(); Current.Factory = composition.CreateFactory(); - - SettingsForTests.Reset(); // ensure we have configuration } [TearDown] public void TearDown() { Current.Reset(); - - SettingsForTests.Reset(); } [TestCase(false, true, true)] diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index db3ec8c80b..9814f79950 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -8,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.Install; @@ -20,6 +21,7 @@ using Umbraco.Core.Services.Implement; using Umbraco.Core.Strings; using Umbraco.Core.Sync; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -73,7 +75,7 @@ namespace Umbraco.Tests.Scoping private Action _onPublishedAssertAction; - protected override IPublishedSnapshotService CreatePublishedSnapshotService() + protected override IPublishedSnapshotService CreatePublishedSnapshotService(GlobalSettings globalSettings = null) { var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; var publishedSnapshotAccessor = new UmbracoContextPublishedSnapshotAccessor(Umbraco.Web.Composing.Current.UmbracoContextAccessor); @@ -87,7 +89,8 @@ namespace Umbraco.Tests.Scoping var hostingEnvironment = TestHelper.GetHostingEnvironment(); var typeFinder = TestHelper.GetTypeFinder(); - var settings = Mock.Of(); + + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); return new PublishedSnapshotService( options, @@ -104,14 +107,14 @@ namespace Umbraco.Tests.Scoping documentRepository, mediaRepository, memberRepository, DefaultCultureAccessor, new DatabaseDataSource(Mock.Of()), - Factory.GetInstance(), + Microsoft.Extensions.Options.Options.Create(globalSettings ?? new GlobalSettingsBuilder().Build()), Factory.GetInstance(), new NoopPublishedModelFactory(), new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider(ShortStringHelper) }), hostingEnvironment, new MockShortStringHelper(), IOHelper, - settings); + Microsoft.Extensions.Options.Options.Create(nuCacheSettings)); } protected IUmbracoContext GetUmbracoContextNu(string url, RouteData routeData = null, bool setSingleton = false) diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 4c3bb288e4..da90d7fefa 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -1,21 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; +using Moq; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Web.Composing; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Events; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Scoping; +using Umbraco.Core.Sync; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; -using Umbraco.Web.Cache; -using Moq; -using Umbraco.Core; -using Umbraco.Core.Events; -using Umbraco.Core.Logging; -using Umbraco.Core.Sync; using Umbraco.Web; +using Umbraco.Web.Cache; +using Umbraco.Web.Composing; namespace Umbraco.Tests.Scoping { @@ -25,6 +27,15 @@ namespace Umbraco.Tests.Scoping { private DistributedCacheBinder _distributedCacheBinder; + private GlobalSettings _globalSettings; + + public override void SetUp() + { + base.SetUp(); + + _globalSettings = new GlobalSettingsBuilder().Build(); + } + protected override void Compose() { base.Compose(); @@ -63,7 +74,7 @@ namespace Umbraco.Tests.Scoping var service = ServiceContext.UserService; var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); - var user = (IUser)new User(TestObjects.GetGlobalSettings(), "name", "email", "username", "rawPassword"); + var user = (IUser)new User(_globalSettings, "name", "email", "username", "rawPassword"); service.Save(user); // global cache contains the entity @@ -140,7 +151,7 @@ namespace Umbraco.Tests.Scoping var service = ServiceContext.LocalizationService; var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof (ILanguage)); - var lang = (ILanguage) new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var lang = (ILanguage) new Language(_globalSettings, "fr-FR"); service.Save(lang); // global cache has been flushed, reload @@ -232,7 +243,7 @@ namespace Umbraco.Tests.Scoping var service = ServiceContext.LocalizationService; var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); - var lang = (ILanguage)new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var lang = (ILanguage)new Language(_globalSettings, "fr-FR"); service.Save(lang); var item = (IDictionaryItem) new DictionaryItem("item-key"); diff --git a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs index 852872fca0..59610e43bd 100644 --- a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs @@ -5,19 +5,19 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Web.Composing; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Core.Sync; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web; using Umbraco.Web.Cache; +using Umbraco.Web.Composing; using Umbraco.Web.PublishedCache; namespace Umbraco.Tests.Scoping @@ -44,8 +44,13 @@ namespace Umbraco.Tests.Scoping protected override void ComposeSettings() { - Composition.Configs.Add(SettingsForTests.GenerateMockContentSettings); - Composition.Configs.Add(SettingsForTests.GenerateMockGlobalSettings); + var contentSettings = new ContentSettingsBuilder().Build(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var userPasswordConfigurationSettings = new UserPasswordConfigurationSettingsBuilder().Build(); + + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(contentSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(globalSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(userPasswordConfigurationSettings)); } [TearDown] diff --git a/src/Umbraco.Tests/Security/BackOfficeOwinUserManagerTests.cs b/src/Umbraco.Tests/Security/BackOfficeOwinUserManagerTests.cs index 8958eabd42..32c85121d2 100644 --- a/src/Umbraco.Tests/Security/BackOfficeOwinUserManagerTests.cs +++ b/src/Umbraco.Tests/Security/BackOfficeOwinUserManagerTests.cs @@ -3,12 +3,14 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; using Microsoft.Owin.Security.DataProtection; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Net; using Umbraco.Web.Security; @@ -23,28 +25,32 @@ namespace Umbraco.Tests.Security const string v7Hash = "7Uob6fMTTxDIhWGebYiSxg==P+hgvWlXLbDd4cFLADn811KOaVI/9pg1PNvTuG5NklY="; const string plaintext = "4XxzH3s3&J"; - var mockPasswordConfiguration = new Mock(); + var userPasswordConfiguration = new UserPasswordConfigurationSettings() + { + HashAlgorithmType = Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName + }; var mockIpResolver = new Mock(); var mockUserStore = new Mock>(); var mockDataProtectionProvider = new Mock(); mockDataProtectionProvider.Setup(x => x.Create(It.IsAny())) .Returns(new Mock().Object); - mockPasswordConfiguration.Setup(x => x.HashAlgorithmType) - .Returns(Constants.Security.AspNetUmbraco8PasswordHashAlgorithmName); + var userManager = BackOfficeOwinUserManager.Create( - mockPasswordConfiguration.Object, + Options.Create(userPasswordConfiguration), mockIpResolver.Object, mockUserStore.Object, null, mockDataProtectionProvider.Object, new NullLogger>()); - var mockGlobalSettings = new Mock(); - mockGlobalSettings.Setup(x => x.DefaultUILanguage).Returns("test"); + var globalSettings = new GlobalSettings() + { + DefaultUILanguage = "test" + }; - var user = new BackOfficeIdentityUser(mockGlobalSettings.Object, 2, new List()) + var user = new BackOfficeIdentityUser(globalSettings, 2, new List()) { UserName = "alice", Name = "Alice", diff --git a/src/Umbraco.Tests/Security/OwinDataProtectorTokenProviderTests.cs b/src/Umbraco.Tests/Security/OwinDataProtectorTokenProviderTests.cs index 7b1ca53104..4874545571 100644 --- a/src/Umbraco.Tests/Security/OwinDataProtectorTokenProviderTests.cs +++ b/src/Umbraco.Tests/Security/OwinDataProtectorTokenProviderTests.cs @@ -8,7 +8,9 @@ using Moq; using NUnit.Framework; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; +using Umbraco.Tests.Common.Builders; using Umbraco.Web.Security; namespace Umbraco.Tests.Security @@ -81,7 +83,7 @@ namespace Umbraco.Tests.Security reader.ReadInt64(); // creation time reader.ReadString(); // user ID var purpose = reader.ReadString(); - + Assert.AreEqual(expectedPurpose, purpose); } } @@ -227,14 +229,13 @@ namespace Umbraco.Tests.Security _mockDataProtector.Setup(x => x.Protect(It.IsAny())).Returns((byte[] originalBytes) => originalBytes); _mockDataProtector.Setup(x => x.Unprotect(It.IsAny())).Returns((byte[] originalBytes) => originalBytes); - var mockGlobalSettings = new Mock(); - mockGlobalSettings.Setup(x => x.DefaultUILanguage).Returns("test"); + var globalSettings = new GlobalSettingsBuilder().Build(); _mockUserManager = new Mock>(new Mock>().Object, null, null, null, null, null, null, null, null); _mockUserManager.Setup(x => x.SupportsUserSecurityStamp).Returns(false); - _testUser = new BackOfficeIdentityUser(mockGlobalSettings.Object, 2, new List()) + _testUser = new BackOfficeIdentityUser(globalSettings, 2, new List()) { UserName = "alice", Name = "Alice", diff --git a/src/Umbraco.Tests/Services/ContentServiceEventTests.cs b/src/Umbraco.Tests/Services/ContentServiceEventTests.cs index 26f6d37456..208afe5b4b 100644 --- a/src/Umbraco.Tests/Services/ContentServiceEventTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceEventTests.cs @@ -1,11 +1,13 @@ using System.Linq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -18,10 +20,13 @@ namespace Umbraco.Tests.Services Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceEventTests : TestWithSomeContentBase { + private GlobalSettings _globalSettings; + public override void SetUp() { base.SetUp(); ContentRepositoryBase.ThrowOnWarning = true; + _globalSettings = new GlobalSettingsBuilder().Build(); } public override void TearDown() @@ -35,7 +40,7 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); + languageService.Save(new Language(_globalSettings, "fr-FR")); var contentTypeService = ServiceContext.ContentTypeService; @@ -146,7 +151,7 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); + languageService.Save(new Language(_globalSettings, "fr-FR")); var contentTypeService = ServiceContext.ContentTypeService; @@ -312,7 +317,7 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); + languageService.Save(new Language(_globalSettings, "fr-FR")); var contentTypeService = ServiceContext.ContentTypeService; diff --git a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs index 6e69c8b18e..fd2a4a664b 100644 --- a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs @@ -17,6 +17,7 @@ using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.TestHelpers.Stubs; @@ -44,10 +45,11 @@ namespace Umbraco.Tests.Services private DocumentRepository CreateDocumentRepository(IScopeProvider provider) { var accessor = (IScopeAccessor)provider; + var globalSettings = new GlobalSettingsBuilder().Build(); var tRepository = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepo = new TagRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, tRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(globalSettings)); var ctRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); diff --git a/src/Umbraco.Tests/Services/ContentServicePublishBranchTests.cs b/src/Umbraco.Tests/Services/ContentServicePublishBranchTests.cs index d856f3bd82..35bbaa5f68 100644 --- a/src/Umbraco.Tests/Services/ContentServicePublishBranchTests.cs +++ b/src/Umbraco.Tests/Services/ContentServicePublishBranchTests.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -425,11 +426,13 @@ namespace Umbraco.Tests.Services private void CreateTypes(out IContentType iContentType, out IContentType vContentType) { - var langDe = new Language(TestObjects.GetGlobalSettings(), "de") { IsDefault = true }; + var globalSettings = new GlobalSettingsBuilder().Build(); + + var langDe = new Language(globalSettings, "de") { IsDefault = true }; ServiceContext.LocalizationService.Save(langDe); - var langRu = new Language(TestObjects.GetGlobalSettings(), "ru"); + var langRu = new Language(globalSettings, "ru"); ServiceContext.LocalizationService.Save(langRu); - var langEs = new Language(TestObjects.GetGlobalSettings(), "es"); + var langEs = new Language(globalSettings, "es"); ServiceContext.LocalizationService.Save(langEs); iContentType = new ContentType(ShortStringHelper, -1) diff --git a/src/Umbraco.Tests/Services/ContentServiceTagsTests.cs b/src/Umbraco.Tests/Services/ContentServiceTagsTests.cs index 5e2c3823af..10bd82cbde 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTagsTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTagsTests.cs @@ -9,6 +9,8 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; +using Umbraco.Core.Configuration.Models; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Services { @@ -19,12 +21,15 @@ namespace Umbraco.Tests.Services Logger = UmbracoTestOptions.Logger.Console)] public class ContentServiceTagsTests : TestWithSomeContentBase { + private GlobalSettings _globalSettings; + public PropertyEditorCollection PropertyEditorCollection => Factory.GetInstance(); public override void SetUp() { base.SetUp(); ContentRepositoryBase.ThrowOnWarning = true; + _globalSettings = new GlobalSettingsBuilder().Build(); } public override void TearDown() @@ -81,7 +86,7 @@ namespace Umbraco.Tests.Services public void TagsCanBeVariant() { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); // en-US is already there + languageService.Save(new Language(_globalSettings, "fr-FR")); // en-US is already there var contentService = ServiceContext.ContentService; var contentTypeService = ServiceContext.ContentTypeService; @@ -205,7 +210,7 @@ namespace Umbraco.Tests.Services public void TagsCanBecomeInvariant() { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); // en-US is already there + languageService.Save(new Language(_globalSettings, "fr-FR")); // en-US is already there var enId = ServiceContext.LocalizationService.GetLanguageIdByIsoCode("en-US").Value; @@ -262,7 +267,7 @@ namespace Umbraco.Tests.Services public void TagsCanBecomeInvariant2() { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); // en-US is already there + languageService.Save(new Language(_globalSettings, "fr-FR")); // en-US is already there var enId = ServiceContext.LocalizationService.GetLanguageIdByIsoCode("en-US").Value; @@ -309,7 +314,7 @@ namespace Umbraco.Tests.Services public void TagsCanBecomeInvariantByPropertyType() { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); // en-US is already there + languageService.Save(new Language(_globalSettings, "fr-FR")); // en-US is already there var enId = ServiceContext.LocalizationService.GetLanguageIdByIsoCode("en-US").Value; @@ -366,7 +371,7 @@ namespace Umbraco.Tests.Services public void TagsCanBecomeInvariantByPropertyTypeAndBackToVariant() { var languageService = ServiceContext.LocalizationService; - languageService.Save(new Language(TestObjects.GetGlobalSettings(), "fr-FR")); // en-US is already there + languageService.Save(new Language(_globalSettings, "fr-FR")); // en-US is already there var enId = ServiceContext.LocalizationService.GetLanguageIdByIsoCode("en-US").Value; diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index b6427a2bc9..7efd1478f0 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -7,21 +7,21 @@ using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers.Entities; -using Umbraco.Core.Events; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.Scoping; -using Umbraco.Core.Services.Implement; -using Umbraco.Tests.Testing; -using Umbraco.Core.Persistence.DatabaseModelDefinitions; -using Umbraco.Core.Cache; using Umbraco.Core.PropertyEditors; -using Umbraco.Tests.Common.TestHelpers.Entities; +using Umbraco.Core.Scoping; +using Umbraco.Core.Services; +using Umbraco.Core.Services.Implement; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.LegacyXmlPublishedCache; +using Umbraco.Tests.TestHelpers.Entities; +using Umbraco.Tests.Testing; namespace Umbraco.Tests.Services { @@ -41,10 +41,13 @@ namespace Umbraco.Tests.Services // TODO: Add test to verify there is only ONE newest document/content in {Constants.DatabaseSchema.Tables.Document} table after updating. // TODO: Add test to delete specific version (with and without deleting prior versions) and versions by date. + private GlobalSettings _globalSettings; + public override void SetUp() { base.SetUp(); ContentRepositoryBase.ThrowOnWarning = true; + _globalSettings = new GlobalSettingsBuilder().Build(); } public override void TearDown() @@ -174,8 +177,8 @@ namespace Umbraco.Tests.Services [Test] public void Perform_Scheduled_Publishing() { - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langUk = new Language(_globalSettings, "en-GB") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langUk); @@ -509,7 +512,7 @@ namespace Umbraco.Tests.Services [Test] public void Can_Save_New_Content_With_Explicit_User() { - var user = new User(TestObjects.GetGlobalSettings()) + var user = new User(_globalSettings) { Name = "Test", Email = "test@test.com", @@ -878,8 +881,8 @@ namespace Umbraco.Tests.Services [Test] public void Unpublishing_Mandatory_Language_Unpublishes_Document() { - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true, IsMandatory = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langUk = new Language(_globalSettings, "en-GB") { IsDefault = true, IsMandatory = true }; + var langFr = new Language(_globalSettings, "fr-FR"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langUk); @@ -975,8 +978,8 @@ namespace Umbraco.Tests.Services { // Arrange - var langGB = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langGB = new Language(_globalSettings, "en-GB") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langGB); @@ -1043,8 +1046,8 @@ namespace Umbraco.Tests.Services { // Arrange - var langGB = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true, IsMandatory = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langGB = new Language(_globalSettings, "en-GB") { IsDefault = true, IsMandatory = true }; + var langFr = new Language(_globalSettings, "fr-FR"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langGB); @@ -1222,8 +1225,8 @@ namespace Umbraco.Tests.Services { //TODO: This is using an internal API - we aren't exposing this publicly (at least for now) but we'll keep the test around - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr"); - var langDa = new Language(TestObjects.GetGlobalSettings(), "da"); + var langFr = new Language(_globalSettings, "fr"); + var langDa = new Language(_globalSettings, "da"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langDa); @@ -2158,8 +2161,8 @@ namespace Umbraco.Tests.Services [Test] public void Can_Rollback_Version_On_Multilingual() { - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr"); - var langDa = new Language(TestObjects.GetGlobalSettings(), "da"); + var langFr = new Language(_globalSettings, "fr"); + var langDa = new Language(_globalSettings, "da"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langDa); @@ -2685,8 +2688,8 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langUk = new Language(_globalSettings, "en-GB") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); languageService.Save(langFr); languageService.Save(langUk); @@ -2720,8 +2723,8 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + var langUk = new Language(_globalSettings, "en-GB") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); languageService.Save(langFr); languageService.Save(langUk); @@ -2757,9 +2760,9 @@ namespace Umbraco.Tests.Services { var languageService = ServiceContext.LocalizationService; - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); - var langDa = new Language(TestObjects.GetGlobalSettings(), "da-DK"); + var langUk = new Language(_globalSettings, "en-GB") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); + var langDa = new Language(_globalSettings, "da-DK"); languageService.Save(langFr); languageService.Save(langUk); @@ -2859,10 +2862,10 @@ namespace Umbraco.Tests.Services var languageService = ServiceContext.LocalizationService; //var langFr = new Language("fr-FR") { IsDefaultVariantLanguage = true }; - var langXx = new Language(TestObjects.GetGlobalSettings(), "pt-PT") { IsDefault = true }; - var langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); - var langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB"); - var langDe = new Language(TestObjects.GetGlobalSettings(), "de-DE"); + var langXx = new Language(_globalSettings, "pt-PT") { IsDefault = true }; + var langFr = new Language(_globalSettings, "fr-FR"); + var langUk = new Language(_globalSettings, "en-GB"); + var langDe = new Language(_globalSettings, "de-DE"); languageService.Save(langFr); languageService.Save(langUk); @@ -3248,7 +3251,7 @@ namespace Umbraco.Tests.Services var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetFileSystemsMock(), IOHelper, ShortStringHelper); var tagRepository = new TagRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var commonRepository = new ContentTypeCommonRepository(accessor, templateRepository, AppCaches, ShortStringHelper); - var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), TestObjects.GetGlobalSettings()); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), Microsoft.Extensions.Options.Options.Create(_globalSettings)); contentTypeRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger(), commonRepository, languageRepository, ShortStringHelper); var relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, LoggerFactory_.CreateLogger()); var entityRepository = new EntityRepository(accessor); @@ -3261,8 +3264,8 @@ namespace Umbraco.Tests.Services private void CreateEnglishAndFrenchDocumentType(out Language langUk, out Language langFr, out ContentType contentType) { - langUk = new Language(TestObjects.GetGlobalSettings(), "en-GB") { IsDefault = true }; - langFr = new Language(TestObjects.GetGlobalSettings(), "fr-FR"); + langUk = new Language(_globalSettings, "en-GB") { IsDefault = true }; + langFr = new Language(_globalSettings, "fr-FR"); ServiceContext.LocalizationService.Save(langFr); ServiceContext.LocalizationService.Save(langUk); diff --git a/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs b/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs index f8d0116772..58d2e27f4d 100644 --- a/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs +++ b/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs @@ -8,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Install; using Umbraco.Core.Logging; @@ -19,6 +20,7 @@ using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Core.Sync; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; @@ -45,7 +47,7 @@ namespace Umbraco.Tests.Services .Add(() => Composition.TypeLoader.GetCacheRefreshers()); } - protected override IPublishedSnapshotService CreatePublishedSnapshotService() + protected override IPublishedSnapshotService CreatePublishedSnapshotService(GlobalSettings globalSettings = null) { var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; var publishedSnapshotAccessor = new UmbracoContextPublishedSnapshotAccessor(Umbraco.Web.Composing.Current.UmbracoContextAccessor); @@ -59,7 +61,8 @@ namespace Umbraco.Tests.Services var hostingEnvironment = Mock.Of(); var typeFinder = TestHelper.GetTypeFinder(); - var settings = Mock.Of(); + + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); return new PublishedSnapshotService( options, @@ -76,14 +79,14 @@ namespace Umbraco.Tests.Services documentRepository, mediaRepository, memberRepository, DefaultCultureAccessor, new DatabaseDataSource(Mock.Of()), - Factory.GetInstance(), + Microsoft.Extensions.Options.Options.Create(globalSettings ?? new GlobalSettingsBuilder().Build()), Factory.GetInstance(), Mock.Of(), new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider(ShortStringHelper) }), hostingEnvironment, new MockShortStringHelper(), IOHelper, - settings); + Microsoft.Extensions.Options.Options.Create(nuCacheSettings)); } public class LocalServerMessenger : ServerMessengerBase @@ -312,7 +315,9 @@ namespace Umbraco.Tests.Services var nlContentName = "Content nl-NL"; var nlCulture = "nl-NL"; - ServiceContext.LocalizationService.Save(new Language(TestObjects.GetGlobalSettings(), nlCulture)); + var globalSettings = new GlobalSettingsBuilder().Build(); + + ServiceContext.LocalizationService.Save(new Language(globalSettings, nlCulture)); var includeCultureNames = contentType.Variations.HasFlag(ContentVariation.Culture); @@ -668,9 +673,11 @@ namespace Umbraco.Tests.Services // can change it to variant and back // can then switch one property to variant - var languageEn = new Language(TestObjects.GetGlobalSettings(), "en") { IsDefault = true }; + var globalSettings = new GlobalSettingsBuilder().Build(); + + var languageEn = new Language(globalSettings, "en") { IsDefault = true }; ServiceContext.LocalizationService.Save(languageEn); - var languageFr = new Language(TestObjects.GetGlobalSettings(), "fr"); + var languageFr = new Language(globalSettings, "fr"); ServiceContext.LocalizationService.Save(languageFr); var contentType = CreateContentType(ContentVariation.Nothing); @@ -1261,9 +1268,10 @@ namespace Umbraco.Tests.Services private void CreateFrenchAndEnglishLangs() { - var languageEn = new Language(TestObjects.GetGlobalSettings(), "en") { IsDefault = true }; + var globalSettings = new GlobalSettingsBuilder().Build(); + var languageEn = new Language(globalSettings, "en") { IsDefault = true }; ServiceContext.LocalizationService.Save(languageEn); - var languageFr = new Language(TestObjects.GetGlobalSettings(), "fr"); + var languageFr = new Language(globalSettings, "fr"); ServiceContext.LocalizationService.Save(languageFr); } diff --git a/src/Umbraco.Tests/Services/EntityServiceTests.cs b/src/Umbraco.Tests/Services/EntityServiceTests.cs index fb802420d5..8be2dcc962 100644 --- a/src/Umbraco.Tests/Services/EntityServiceTests.cs +++ b/src/Umbraco.Tests/Services/EntityServiceTests.cs @@ -8,6 +8,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; @@ -31,8 +32,9 @@ namespace Umbraco.Tests.Services if (_langFr == null && _langEs == null) { - _langFr = new Language(SettingsForTests.GenerateMockGlobalSettings(), "fr-FR"); - _langEs = new Language(SettingsForTests.GenerateMockGlobalSettings(), "es-ES"); + var globalSettings = new GlobalSettingsBuilder().Build(); + _langFr = new Language(globalSettings, "fr-FR"); + _langEs = new Language(globalSettings, "es-ES"); ServiceContext.LocalizationService.Save(_langFr); ServiceContext.LocalizationService.Save(_langEs); } diff --git a/src/Umbraco.Tests/Services/EntityXmlSerializerTests.cs b/src/Umbraco.Tests/Services/EntityXmlSerializerTests.cs index e10dd99482..8497208d93 100644 --- a/src/Umbraco.Tests/Services/EntityXmlSerializerTests.cs +++ b/src/Umbraco.Tests/Services/EntityXmlSerializerTests.cs @@ -4,9 +4,10 @@ using System.Linq; using System.Xml.Linq; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Services; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Services.Importing; using Umbraco.Tests.Testing; @@ -17,6 +18,13 @@ namespace Umbraco.Tests.Services public class EntityXmlSerializerTests : TestWithSomeContentBase { private IEntityXmlSerializer Serializer => Factory.GetInstance(); + private GlobalSettings _globalSettings; + + public override void SetUp() + { + base.SetUp(); + _globalSettings = new GlobalSettingsBuilder().Build(); + } [Test] public void Can_Export_Macro() @@ -56,10 +64,10 @@ namespace Umbraco.Tests.Services public void Can_Export_Languages() { // Arrange - var languageNbNo = new Language(TestObjects.GetGlobalSettings(), "nb-NO") { CultureName = "Norwegian" }; + var languageNbNo = new Language(_globalSettings, "nb-NO") { CultureName = "Norwegian" }; ServiceContext.LocalizationService.Save(languageNbNo); - var languageEnGb = new Language(TestObjects.GetGlobalSettings(), "en-GB") { CultureName = "English (United Kingdom)" }; + var languageEnGb = new Language(_globalSettings, "en-GB") { CultureName = "English (United Kingdom)" }; ServiceContext.LocalizationService.Save(languageEnGb); var newPackageXml = XElement.Parse(ImportResources.Dictionary_Package); @@ -74,10 +82,10 @@ namespace Umbraco.Tests.Services private void CreateDictionaryData() { - var languageNbNo = new Language(TestObjects.GetGlobalSettings(), "nb-NO") { CultureName = "nb-NO" }; + var languageNbNo = new Language(_globalSettings, "nb-NO") { CultureName = "nb-NO" }; ServiceContext.LocalizationService.Save(languageNbNo); - var languageEnGb = new Language(TestObjects.GetGlobalSettings(), "en-GB") { CultureName = "en-GB" }; + var languageEnGb = new Language(_globalSettings, "en-GB") { CultureName = "en-GB" }; ServiceContext.LocalizationService.Save(languageEnGb); var parentItem = new DictionaryItem("Parent"); diff --git a/src/Umbraco.Tests/Services/LocalizationServiceTests.cs b/src/Umbraco.Tests/Services/LocalizationServiceTests.cs index c5ff549ee3..2785cdea27 100644 --- a/src/Umbraco.Tests/Services/LocalizationServiceTests.cs +++ b/src/Umbraco.Tests/Services/LocalizationServiceTests.cs @@ -9,6 +9,8 @@ using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Core.Persistence; +using Umbraco.Core.Configuration.Models; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Services { @@ -29,6 +31,14 @@ namespace Umbraco.Tests.Services private int _danishLangId; private int _englishLangId; + private GlobalSettings _globalSettings; + + public override void SetUp() + { + base.SetUp(); + _globalSettings = new GlobalSettingsBuilder().Build(); + } + [Test] public void Can_Get_Root_Dictionary_Items() { @@ -181,7 +191,7 @@ namespace Umbraco.Tests.Services [Test] public void Can_Delete_Language() { - var norwegian = new Language(TestObjects.GetGlobalSettings(), "nb-NO") { CultureName = "Norwegian" }; + var norwegian = new Language(_globalSettings, "nb-NO") { CultureName = "Norwegian" }; ServiceContext.LocalizationService.Save(norwegian, 0); Assert.That(norwegian.HasIdentity, Is.True); var languageId = norwegian.Id; @@ -196,7 +206,7 @@ namespace Umbraco.Tests.Services public void Can_Delete_Language_Used_As_Fallback() { var danish = ServiceContext.LocalizationService.GetLanguageByIsoCode("da-DK"); - var norwegian = new Language(TestObjects.GetGlobalSettings(), "nb-NO") { CultureName = "Norwegian", FallbackLanguageId = danish.Id }; + var norwegian = new Language(_globalSettings, "nb-NO") { CultureName = "Norwegian", FallbackLanguageId = danish.Id }; ServiceContext.LocalizationService.Save(norwegian, 0); var languageId = danish.Id; @@ -346,7 +356,7 @@ namespace Umbraco.Tests.Services // Arrange var localizationService = ServiceContext.LocalizationService; var isoCode = "en-AU"; - var language = new Core.Models.Language(TestObjects.GetGlobalSettings(), isoCode); + var language = new Core.Models.Language(_globalSettings, isoCode); // Act localizationService.Save(language); @@ -361,7 +371,7 @@ namespace Umbraco.Tests.Services { var localizationService = ServiceContext.LocalizationService; var isoCode = "en-AU"; - var language = new Core.Models.Language(TestObjects.GetGlobalSettings(), isoCode); + var language = new Core.Models.Language(_globalSettings, isoCode); // Act localizationService.Save(language); @@ -375,14 +385,14 @@ namespace Umbraco.Tests.Services public void Set_Default_Language() { var localizationService = ServiceContext.LocalizationService; - var language = new Core.Models.Language(TestObjects.GetGlobalSettings(), "en-AU"); + var language = new Core.Models.Language(_globalSettings, "en-AU"); language.IsDefault = true; localizationService.Save(language); var result = localizationService.GetLanguageById(language.Id); Assert.IsTrue(result.IsDefault); - var language2 = new Core.Models.Language(TestObjects.GetGlobalSettings(), "en-NZ"); + var language2 = new Core.Models.Language(_globalSettings, "en-NZ"); language2.IsDefault = true; localizationService.Save(language2); var result2 = localizationService.GetLanguageById(language2.Id); @@ -398,7 +408,7 @@ namespace Umbraco.Tests.Services { var localizationService = ServiceContext.LocalizationService; var isoCode = "en-AU"; - var language = new Core.Models.Language(TestObjects.GetGlobalSettings(), isoCode); + var language = new Core.Models.Language(_globalSettings, isoCode); localizationService.Save(language); // Act @@ -411,8 +421,8 @@ namespace Umbraco.Tests.Services public override void CreateTestData() { - var danish = new Language(TestObjects.GetGlobalSettings(), "da-DK") { CultureName = "Danish" }; - var english = new Language(TestObjects.GetGlobalSettings(), "en-GB") { CultureName = "English" }; + var danish = new Language(_globalSettings, "da-DK") { CultureName = "Danish" }; + var english = new Language(_globalSettings, "en-GB") { CultureName = "English" }; ServiceContext.LocalizationService.Save(danish, 0); ServiceContext.LocalizationService.Save(english, 0); _danishLangId = danish.Id; diff --git a/src/Umbraco.Tests/Services/SectionServiceTests.cs b/src/Umbraco.Tests/Services/SectionServiceTests.cs index 80a4de4bfe..82fda67003 100644 --- a/src/Umbraco.Tests/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests/Services/SectionServiceTests.cs @@ -4,6 +4,7 @@ using System.Threading; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Models.Membership; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Testing; using Umbraco.Web.Services; @@ -34,7 +35,8 @@ namespace Umbraco.Tests.Services private IUser CreateTestUser() { - var user = new User(TestObjects.GetGlobalSettings()) + var globalSettings = new GlobalSettingsBuilder().Build(); + var user = new User(globalSettings) { Name = "Test user", Username = "testUser", diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index cedb329f13..fef2fa30af 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -6,20 +6,17 @@ using System.Text; using System.Threading; using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Exceptions; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; -using Umbraco.Core.Persistence.DatabaseModelDefinitions; -using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; -using Umbraco.Tests.Common.TestHelpers.Entities; +using Umbraco.Tests.Common.Builders; +using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Actions; using MockedUser = Umbraco.Tests.TestHelpers.Entities.MockedUser; - namespace Umbraco.Tests.Services { /// @@ -724,7 +721,8 @@ namespace Umbraco.Tests.Services var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - var membershipUser = new User(TestObjects.GetGlobalSettings(), "JohnDoe", "john@umbraco.io", encodedPassword, encodedPassword); + var globalSettings = new GlobalSettingsBuilder().Build(); + var membershipUser = new User(globalSettings, "JohnDoe", "john@umbraco.io", encodedPassword, encodedPassword); userService.Save(membershipUser); // Assert diff --git a/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs b/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs index 84ffa3b696..71d789eddb 100644 --- a/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs +++ b/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -30,7 +31,8 @@ namespace Umbraco.Tests.Strings [TestCase("WhoIsNumber6InTheVillage", "Who Is Number6 In The Village")] // issue is fixed public void CompatibleDefaultReplacement(string input, string expected) { - var helper = new DefaultShortStringHelper(SettingsForTests.GenerateMockRequestHandlerSettings()); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings)); var output = input.Length < 2 ? input : helper.SplitPascalCasing(input, ' ').ToFirstUpperInvariant(); Assert.AreEqual(expected, output); } diff --git a/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs b/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs index 109142f51b..12f5022b55 100644 --- a/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs +++ b/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs @@ -3,13 +3,12 @@ using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; -using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Strings; -using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Testing; namespace Umbraco.Tests.Strings @@ -25,8 +24,8 @@ namespace Umbraco.Tests.Strings // NOTE pre-filters runs _before_ Recode takes place // so there still may be utf8 chars even though you want ascii - - _helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + _helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.FileName, new DefaultShortStringHelperConfig.Config { //PreFilter = ClearFileChars, // done in IsTerm @@ -94,18 +93,18 @@ namespace Umbraco.Tests.Strings [Test] public void U4_4056() { - var settings = SettingsForTests.GenerateMockRequestHandlerSettings(); - var contentMock = Mock.Get(settings); - contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); - contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder() + .WithConvertUrlsToAscii("false") + .WithCharCollection(Enumerable.Empty()) + .Build(); const string input = "ÆØÅ and æøå and 中文测试 and אודות האתר and größer БбДдЖж page"; - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(settings)); // unicode + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings)); // unicode var output = helper.CleanStringForUrlSegment(input); Assert.AreEqual("æøå-and-æøå-and-中文测试-and-אודות-האתר-and-größer-ббдджж-page", output); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(settings) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.UrlSegment, new DefaultShortStringHelperConfig.Config { IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', @@ -119,19 +118,19 @@ namespace Umbraco.Tests.Strings [Test] public void U4_4056_TryAscii() { - var settings = SettingsForTests.GenerateMockRequestHandlerSettings(); - var contentMock = Mock.Get(settings); - contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); - contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder() + .WithConvertUrlsToAscii("false") + .WithCharCollection(Enumerable.Empty()) + .Build(); const string input1 = "ÆØÅ and æøå and 中文测试 and אודות האתר and größer БбДдЖж page"; const string input2 = "ÆØÅ and æøå and größer БбДдЖж page"; - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(settings)); // unicode + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings)); // unicode Assert.AreEqual("æøå-and-æøå-and-中文测试-and-אודות-האתר-and-größer-ббдджж-page", helper.CleanStringForUrlSegment(input1)); Assert.AreEqual("æøå-and-æøå-and-größer-ббдджж-page", helper.CleanStringForUrlSegment(input2)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(settings) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.UrlSegment, new DefaultShortStringHelperConfig.Config { IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', @@ -145,7 +144,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringUnderscoreInTerm() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // underscore is accepted within terms @@ -155,7 +155,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo_bar*nil", helper.CleanString("foo_bar nil", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // underscore is not accepted within terms @@ -169,7 +169,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringLeadingChars() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // letters and digits are valid leading chars @@ -179,7 +180,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("0123foo*bar*543*nil*321", helper.CleanString("0123foo_bar 543 nil 321", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // only letters are valid leading chars @@ -190,14 +191,15 @@ namespace Umbraco.Tests.Strings Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123foo_bar 543 nil 321", CleanStringType.Alias)); Assert.AreEqual("foo*bar*543*nil*321", helper.CleanString("0123 foo_bar 543 nil 321", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings())); + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings)); Assert.AreEqual("child2", helper.CleanStringForSafeAlias("1child2")); } [Test] public void CleanStringTermOnUpper() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -207,7 +209,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo*Bar", helper.CleanString("fooBar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -221,7 +223,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringAcronymOnNonUpper() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -234,7 +237,7 @@ namespace Umbraco.Tests.Strings Assert.AreEqual("foo*BAnil", helper.CleanString("foo BAnil", CleanStringType.Alias)); Assert.AreEqual("foo*Bnil", helper.CleanString("foo Bnil", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -251,7 +254,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringGreedyAcronyms() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -264,7 +268,7 @@ namespace Umbraco.Tests.Strings Assert.AreEqual("foo*BA*nil", helper.CleanString("foo BAnil", CleanStringType.Alias)); Assert.AreEqual("foo*Bnil", helper.CleanString("foo Bnil", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -281,7 +285,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringWhiteSpace() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -294,7 +299,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringSeparator() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -302,7 +308,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo*bar", helper.CleanString("foo bar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -310,14 +316,14 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo bar", helper.CleanString("foo bar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged })); Assert.AreEqual("foobar", helper.CleanString("foo bar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -329,7 +335,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringSymbols() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -383,7 +390,9 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringEncoding() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -392,7 +401,7 @@ namespace Umbraco.Tests.Strings Assert.AreEqual("中文测试", helper.CleanString("中文测试", CleanStringType.Alias)); Assert.AreEqual("léger*中文测试*ZÔRG", helper.CleanString("léger 中文测试 ZÔRG", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Ascii | CleanStringType.Unchanged, @@ -405,12 +414,12 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringDefaultConfig() { - var settings = SettingsForTests.GenerateMockRequestHandlerSettings(); - var contentMock = Mock.Get(settings); - contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); - contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); + var requestHandlerSettings = new RequestHandlerSettingsBuilder() + .WithCharCollection(Enumerable.Empty()) + .WithConvertUrlsToAscii("false") + .Build(); - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(settings)); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings)); const string input = "0123 中文测试 中文测试 léger ZÔRG (2) a?? *x"; @@ -431,7 +440,8 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringCasing() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GenerateMockRequestHandlerSettings()) + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(requestHandlerSettings) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, diff --git a/src/Umbraco.Tests/Templates/HtmlImageSourceParserTests.cs b/src/Umbraco.Tests/Templates/HtmlImageSourceParserTests.cs index 14e45d976c..4dc7ad0278 100644 --- a/src/Umbraco.Tests/Templates/HtmlImageSourceParserTests.cs +++ b/src/Umbraco.Tests/Templates/HtmlImageSourceParserTests.cs @@ -14,6 +14,7 @@ using Umbraco.Core; using System.Diagnostics; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Templates { @@ -76,9 +77,9 @@ namespace Umbraco.Tests.Templates var umbracoContextFactory = TestUmbracoContextFactory.Create( umbracoContextAccessor: umbracoContextAccessor); - + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); var publishedUrlProvider = new UrlProvider(umbracoContextAccessor, - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(Enumerable.Empty()), new MediaUrlProviderCollection(new []{mediaUrlProvider.Object}), Mock.Of() diff --git a/src/Umbraco.Tests/Templates/HtmlLocalLinkParserTests.cs b/src/Umbraco.Tests/Templates/HtmlLocalLinkParserTests.cs index 20677468c6..375dc91d19 100644 --- a/src/Umbraco.Tests/Templates/HtmlLocalLinkParserTests.cs +++ b/src/Umbraco.Tests/Templates/HtmlLocalLinkParserTests.cs @@ -7,6 +7,7 @@ using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing.Objects; using Umbraco.Web; @@ -72,8 +73,9 @@ namespace Umbraco.Tests.Templates var umbracoContextFactory = TestUmbracoContextFactory.Create( umbracoContextAccessor: umbracoContextAccessor); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); var publishedUrlProvider = new UrlProvider(umbracoContextAccessor, - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(new []{contentUrlProvider.Object}), new MediaUrlProviderCollection(new []{mediaUrlProvider.Object}), Mock.Of() diff --git a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs index e8db0c934f..1065012e82 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs @@ -46,7 +46,7 @@ namespace Umbraco.Tests.TestHelpers logger, false); - var composition = new Composition(container, typeLoader, Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + var composition = new Composition(container, typeLoader, Mock.Of(), ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); composition.RegisterUnique(_ => Mock.Of()); composition.RegisterUnique(_ => Mock.Of()); diff --git a/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs b/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs index 568f617f7b..b366f1f07c 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs @@ -5,6 +5,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -13,6 +14,7 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web; @@ -91,13 +93,14 @@ namespace Umbraco.Tests.TestHelpers internal PublishedRouter CreatePublishedRouter(IFactory container = null, ContentFinderCollection contentFinders = null) { - return CreatePublishedRouter(SettingsForTests.GenerateMockWebRoutingSettings(), container ?? Factory, contentFinders); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + return CreatePublishedRouter(webRoutingSettings, container ?? Factory, contentFinders); } - internal static PublishedRouter CreatePublishedRouter(IWebRoutingSettings webRoutingSettings, IFactory container = null, ContentFinderCollection contentFinders = null) + internal static PublishedRouter CreatePublishedRouter(WebRoutingSettings webRoutingSettings, IFactory container = null, ContentFinderCollection contentFinders = null) { return new PublishedRouter( - webRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), contentFinders ?? new ContentFinderCollection(Enumerable.Empty()), new TestLastChanceFinder(), new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 641691e853..87d470f31e 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -1,31 +1,21 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Dispatcher; -using System.Web.Security; using Moq; using Umbraco.Core.BackOffice; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Dictionary; -using Umbraco.Core.IO; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Web; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; using Umbraco.Web.Security; using Umbraco.Web.WebApi; -using Umbraco.Core.Logging; -using Umbraco.Tests.Testing.Objects.Accessors; -using Umbraco.Web.Security.Providers; -using Umbraco.Tests.Strings; using Umbraco.Tests.Common; using Umbraco.Tests.TestHelpers.Entities; @@ -67,7 +57,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting contentTypeService: mockedContentTypeService, localizedTextService:Mock.Of()); - var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); + var globalSettings = new GlobalSettings(); // FIXME: v8? ////new app context diff --git a/src/Umbraco.Tests/TestHelpers/Entities/MockedUser.cs b/src/Umbraco.Tests/TestHelpers/Entities/MockedUser.cs index 531d87f76f..4977b5d81a 100644 --- a/src/Umbraco.Tests/TestHelpers/Entities/MockedUser.cs +++ b/src/Umbraco.Tests/TestHelpers/Entities/MockedUser.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Umbraco.Core.Models.Membership; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.TestHelpers.Entities { @@ -23,7 +24,8 @@ namespace Umbraco.Tests.TestHelpers.Entities internal static User CreateUser(string suffix = "") { - var user = new User(SettingsForTests.GenerateMockGlobalSettings()) + var globalSettings = new GlobalSettingsBuilder().Build(); + var user = new User(globalSettings) { Language = "en", IsApproved = true, @@ -41,10 +43,11 @@ namespace Umbraco.Tests.TestHelpers.Entities { var list = new List(); + var globalSettings = new GlobalSettingsBuilder().Build(); for (int i = 0; i < amount; i++) { var name = "Member No-" + i; - var user = new User(SettingsForTests.GenerateMockGlobalSettings(), name, "test" + i + "@test.com", "test" + i, "test" + i); + var user = new User(globalSettings, name, "test" + i + "@test.com", "test" + i, "test" + i); onCreating?.Invoke(i, user); diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs deleted file mode 100644 index b58301287b..0000000000 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; - -namespace Umbraco.Tests.TestHelpers -{ - public class SettingsForTests - { - private static Common.SettingsForTests _settingsForTests = new Common.SettingsForTests(); - - public static IGlobalSettings GenerateMockGlobalSettings() => _settingsForTests.GenerateMockGlobalSettings(TestHelper.GetUmbracoVersion()); - - /// - /// Returns generated settings which can be stubbed to return whatever values necessary - /// - /// - public static IContentSettings GenerateMockContentSettings() => _settingsForTests.GenerateMockContentSettings(); - - //// from appSettings - - //private static readonly IDictionary SavedAppSettings = new Dictionary(); - - //static void SaveSetting(string key) - //{ - // SavedAppSettings[key] = ConfigurationManager.AppSettings[key]; - //} - - //static void SaveSettings() - //{ - // SaveSetting("umbracoHideTopLevelNodeFromPath"); - // SaveSetting("umbracoUseDirectoryUrls"); - // SaveSetting("umbracoPath"); - // SaveSetting("umbracoReservedPaths"); - // SaveSetting("umbracoReservedUrls"); - // SaveSetting("umbracoConfigurationStatus"); - //} - - - - // reset & defaults - - //static SettingsForTests() - //{ - // //SaveSettings(); - //} - - public static void Reset() => _settingsForTests.Reset(); - - internal static IGlobalSettings DefaultGlobalSettings => _settingsForTests.GetDefaultGlobalSettings(TestHelper.GetUmbracoVersion()); - - internal static IHostingSettings DefaultHostingSettings => _settingsForTests.DefaultHostingSettings; - - public static IHostingSettings GenerateMockHostingSettings() => _settingsForTests.GenerateMockHostingSettings(); - - public static IWebRoutingSettings GenerateMockWebRoutingSettings() => _settingsForTests.GenerateMockWebRoutingSettings(); - - public static IRequestHandlerSettings GenerateMockRequestHandlerSettings() => _settingsForTests.GenerateMockRequestHandlerSettings(); - - public static ISecuritySettings GenerateMockSecuritySettings() => _settingsForTests.GenerateMockSecuritySettings(); - - public static IUserPasswordConfiguration GenerateMockUserPasswordConfiguration() => _settingsForTests.GenerateMockUserPasswordConfiguration(); - - public static IMemberPasswordConfiguration GenerateMockMemberPasswordConfiguration() => _settingsForTests.GenerateMockMemberPasswordConfiguration(); - } -} diff --git a/src/Umbraco.Tests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs index e48601c4e7..850ac07f3b 100644 --- a/src/Umbraco.Tests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -33,6 +33,9 @@ using Umbraco.Web; using Umbraco.Web.Hosting; using Umbraco.Web.Routing; using File = System.IO.File; +using Umbraco.Tests.Common.Builders; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Tests.TestHelpers { @@ -59,11 +62,11 @@ namespace Umbraco.Tests.TestHelpers public override IBackOfficeInfo GetBackOfficeInfo() => new AspNetBackOfficeInfo( - SettingsForTests.GenerateMockGlobalSettings(GetUmbracoVersion()), - TestHelper.IOHelper, Mock.Of>(), SettingsForTests.GenerateMockWebRoutingSettings()); + new GlobalSettings(), + TestHelper.IOHelper, Mock.Of>(), Options.Create(new WebRoutingSettings())); public override IHostingEnvironment GetHostingEnvironment() - => new AspNetHostingEnvironment(SettingsForTests.DefaultHostingSettings); + => new AspNetHostingEnvironment(Options.Create(new HostingSettings())); public override IApplicationShutdownRegistry GetHostingEnvironmentLifetime() => new AspNetApplicationShutdownRegistry(); @@ -76,11 +79,11 @@ namespace Umbraco.Tests.TestHelpers public static TypeLoader GetMockedTypeLoader() => _testHelperInternal.GetMockedTypeLoader(); - public static Configs GetConfigs() => _testHelperInternal.GetConfigs(); + //public static Configs GetConfigs() => _testHelperInternal.GetConfigs(); public static IBackOfficeInfo GetBackOfficeInfo() => _testHelperInternal.GetBackOfficeInfo(); - public static IConfigsFactory GetConfigsFactory() => _testHelperInternal.GetConfigsFactory(); + // public static IConfigsFactory GetConfigsFactory() => _testHelperInternal.GetConfigsFactory(); /// /// Gets the working directory of the test project. @@ -94,16 +97,14 @@ namespace Umbraco.Tests.TestHelpers public static IDbProviderFactoryCreator DbProviderFactoryCreator => _testHelperInternal.DbProviderFactoryCreator; public static IBulkSqlInsertProvider BulkSqlInsertProvider => _testHelperInternal.BulkSqlInsertProvider; public static IMarchal Marchal => _testHelperInternal.Marchal; - public static ICoreDebugSettings CoreDebugSettings => _testHelperInternal.CoreDebugSettings; + public static CoreDebugSettings CoreDebugSettings => _testHelperInternal.CoreDebugSettings; public static IIOHelper IOHelper => _testHelperInternal.IOHelper; public static IMainDom MainDom => _testHelperInternal.MainDom; public static UriUtility UriUtility => _testHelperInternal.UriUtility; - public static IWebRoutingSettings WebRoutingSettings => _testHelperInternal.WebRoutingSettings; - - public static IEmailSender EmailSender { get; } = new EmailSender(SettingsForTests.GenerateMockGlobalSettings()); + public static IEmailSender EmailSender { get; } = new EmailSender(Options.Create(new GlobalSettingsBuilder().Build())); /// @@ -115,12 +116,12 @@ namespace Umbraco.Tests.TestHelpers public static void InitializeContentDirectories() { - CreateDirectories(new[] { Constants.SystemDirectories.MvcViews, SettingsForTests.GenerateMockGlobalSettings().UmbracoMediaPath, Constants.SystemDirectories.AppPlugins }); + CreateDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath, Constants.SystemDirectories.AppPlugins }); } public static void CleanContentDirectories() { - CleanDirectories(new[] { Constants.SystemDirectories.MvcViews, SettingsForTests.GenerateMockGlobalSettings().UmbracoMediaPath }); + CleanDirectories(new[] { Constants.SystemDirectories.MvcViews, new GlobalSettings().UmbracoMediaPath }); } public static void CreateDirectories(string[] directories) diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 30c6296eff..b26a0e24d8 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -7,11 +7,10 @@ using System.Linq.Expressions; using Moq; using Umbraco.Core; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Services; using Umbraco.Persistance.SqlCe; using Umbraco.Tests.Common; @@ -135,9 +134,9 @@ namespace Umbraco.Tests.TestHelpers return umbracoContextFactory.EnsureUmbracoContext().UmbracoContext; } - public IGlobalSettings GetGlobalSettings() + public GlobalSettings GetGlobalSettings() { - return SettingsForTests.DefaultGlobalSettings; + return new GlobalSettings(); } public IFileSystems GetFileSystemsMock() { diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index ac2c59e2b8..a7023e1b44 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -1,4 +1,8 @@ using System; +using System.Configuration; +using System.IO; +using System.Linq; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Moq; using NPoco; @@ -6,12 +10,18 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Events; +using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Scoping; using Umbraco.Persistance.SqlCe; +using Umbraco.Tests.Common.Builders; +using Umbraco.Tests.TestHelpers.Stubs; using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Tests.TestHelpers @@ -72,27 +82,31 @@ namespace Umbraco.Tests.TestHelpers public IScopeProvider GetScopeProvider(ILoggerFactory loggerFactory, ITypeFinder typeFinder = null, FileSystems fileSystems = null, IUmbracoDatabaseFactory databaseFactory = null) { + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionString = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName].ConnectionString; + var connectionStrings = new ConnectionStringsBuilder().WithUmbracoConnectionString(connectionString).Build(); + var coreDebugSettings = new CoreDebugSettingsBuilder().Build(); + if (databaseFactory == null) { // var mappersBuilder = new MapperCollectionBuilder(Current.Container); // FIXME: // mappersBuilder.AddCore(); // var mappers = mappersBuilder.CreateCollection(); var mappers = Current.Factory.GetInstance(); - databaseFactory = new UmbracoDatabaseFactory(loggerFactory.CreateLogger(), + databaseFactory = new UmbracoDatabaseFactory( + loggerFactory.CreateLogger(), loggerFactory, - SettingsForTests.DefaultGlobalSettings, - new ConnectionStrings(), - Constants.System.UmbracoConnectionName, + globalSettings, + connectionStrings, new Lazy(() => mappers), TestHelper.DbProviderFactoryCreator); } typeFinder ??= new TypeFinder(loggerFactory.CreateLogger(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash()); - fileSystems ??= new FileSystems(Current.Factory, loggerFactory.CreateLogger(), loggerFactory, TestHelper.IOHelper, SettingsForTests.GenerateMockGlobalSettings(), TestHelper.GetHostingEnvironment()); + fileSystems ??= new FileSystems(Current.Factory, loggerFactory.CreateLogger(), loggerFactory, TestHelper.IOHelper, Options.Create(globalSettings), TestHelper.GetHostingEnvironment()); var coreDebug = TestHelper.CoreDebugSettings; var mediaFileSystem = Mock.Of(); - var scopeProvider = new ScopeProvider(databaseFactory, fileSystems, coreDebug, mediaFileSystem, loggerFactory.CreateLogger(), loggerFactory, typeFinder, NoAppCache.Instance); - return scopeProvider; + return new ScopeProvider(databaseFactory, fileSystems, Microsoft.Extensions.Options.Options.Create(coreDebugSettings), mediaFileSystem, loggerFactory.CreateLogger(), loggerFactory, typeFinder, NoAppCache.Instance); } } diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 738055426f..75f0b01d76 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -1,8 +1,6 @@ using System; -using System.Collections.Generic; using System.Configuration; using System.Data.SqlServerCe; -using System.Linq; using System.Threading; using System.Web.Routing; using System.Xml; @@ -11,8 +9,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.SqlSyntax; @@ -34,6 +31,7 @@ using Umbraco.Persistance.SqlCe; using Umbraco.Tests.LegacyXmlPublishedCache; using Umbraco.Web.WebApi; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.TestHelpers { @@ -238,11 +236,11 @@ namespace Umbraco.Tests.TestHelpers } } - protected virtual IPublishedSnapshotService CreatePublishedSnapshotService() + protected virtual IPublishedSnapshotService CreatePublishedSnapshotService(GlobalSettings globalSettings = null) { var cache = NoAppCache.Instance; - ContentTypesCache = new PublishedContentTypeCache( + ContentTypesCache ??= new PublishedContentTypeCache( Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), @@ -262,7 +260,7 @@ namespace Umbraco.Tests.TestHelpers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), DefaultCultureAccessor, Factory.GetInstance(), - Factory.GetInstance(), + globalSettings ?? TestObjects.GetGlobalSettings(), HostingEnvironment, HostingLifetime, ShortStringHelper, @@ -302,7 +300,7 @@ namespace Umbraco.Tests.TestHelpers { using (var scope = ScopeProvider.CreateScope()) { - var schemaHelper = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion, TestObjects.GetGlobalSettings()); + var schemaHelper = new DatabaseSchemaCreator(scope.Database, LoggerFactory_.CreateLogger(), LoggerFactory_, UmbracoVersion); //Create the umbraco database and its base data schemaHelper.InitializeDatabaseSchema(); @@ -352,7 +350,7 @@ namespace Umbraco.Tests.TestHelpers } } - protected IUmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IGlobalSettings globalSettings = null, IPublishedSnapshotService snapshotService = null) + protected IUmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, GlobalSettings globalSettings = null, IPublishedSnapshotService snapshotService = null) { // ensure we have a PublishedCachesService var service = snapshotService ?? PublishedSnapshotService as XmlPublishedSnapshotService; @@ -376,7 +374,7 @@ namespace Umbraco.Tests.TestHelpers httpContextAccessor, service, Mock.Of(), - globalSettings ?? Factory.GetInstance(), + globalSettings ?? new GlobalSettingsBuilder().Build(), HostingEnvironment, new TestVariationContextAccessor(), UriUtility, diff --git a/src/Umbraco.Tests/Testing/Objects/TestUmbracoContextFactory.cs b/src/Umbraco.Tests/Testing/Objects/TestUmbracoContextFactory.cs index cb20c56d6d..544e60d721 100644 --- a/src/Umbraco.Tests/Testing/Objects/TestUmbracoContextFactory.cs +++ b/src/Umbraco.Tests/Testing/Objects/TestUmbracoContextFactory.cs @@ -1,7 +1,5 @@ using Moq; -using NUnit.Framework.Internal; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Services; using Umbraco.Tests.Common; using Umbraco.Tests.TestHelpers; @@ -16,12 +14,12 @@ namespace Umbraco.Tests.Testing.Objects /// public class TestUmbracoContextFactory { - public static IUmbracoContextFactory Create(IGlobalSettings globalSettings = null, + public static IUmbracoContextFactory Create(GlobalSettings globalSettings = null, IUmbracoContextAccessor umbracoContextAccessor = null, IHttpContextAccessor httpContextAccessor = null, IPublishedUrlProvider publishedUrlProvider = null) { - if (globalSettings == null) globalSettings = TestHelpers.SettingsForTests.GenerateMockGlobalSettings(); + if (globalSettings == null) globalSettings = new GlobalSettings(); if (umbracoContextAccessor == null) umbracoContextAccessor = new TestUmbracoContextAccessor(); if (httpContextAccessor == null) httpContextAccessor = TestHelper.GetHttpContextAccessor(); if (publishedUrlProvider == null) publishedUrlProvider = TestHelper.GetPublishedUrlProvider(); diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index bed7db4e35..96907654c4 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -9,6 +9,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Dictionary; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; @@ -27,6 +28,7 @@ using Umbraco.Web.Security; using Umbraco.Web.Security.Providers; using Umbraco.Web.WebApi; using Current = Umbraco.Web.Composing.Current; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Testing.TestingTests { @@ -84,9 +86,10 @@ namespace Umbraco.Tests.Testing.TestingTests .Returns(UrlInfo.Url("/hello/world/1234")); var urlProvider = urlProviderMock.Object; + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); var theUrlProvider = new UrlProvider( new TestUmbracoContextAccessor(umbracoContext), - TestHelper.WebRoutingSettings, + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(new [] { urlProvider }), new MediaUrlProviderCollection( Enumerable.Empty()) , umbracoContext.VariationContextAccessor); @@ -109,7 +112,7 @@ namespace Umbraco.Tests.Testing.TestingTests var membershipHelper = new MembershipHelper(Mock.Of(), Mock.Of(), membershipProvider, Mock.Of(), memberService, memberTypeService, Mock.Of(), AppCaches.Disabled, logger, ShortStringHelper, Mock.Of()); var umbracoMapper = new UmbracoMapper(new MapDefinitionCollection(new[] { Mock.Of() })); - var umbracoApiController = new FakeUmbracoApiController(Mock.Of(), Mock.Of(), Mock.Of(), ServiceContext.CreatePartial(), AppCaches.NoCache, pLogger, Mock.Of(), umbracoMapper, Mock.Of()); + var umbracoApiController = new FakeUmbracoApiController(new GlobalSettings(), Mock.Of(), Mock.Of(), ServiceContext.CreatePartial(), AppCaches.NoCache, pLogger, Mock.Of(), umbracoMapper, Mock.Of()); Assert.Pass(); } @@ -117,7 +120,7 @@ namespace Umbraco.Tests.Testing.TestingTests internal class FakeUmbracoApiController : UmbracoApiController { - public FakeUmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + public FakeUmbracoApiController(GlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { } } } diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 936262046e..bfde408c63 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -17,13 +17,19 @@ using Serilog; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; +using Umbraco.Core.Composing.CompositionExtensions; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Dictionary; using Umbraco.Core.Events; +using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.IO.MediaPathSchemes; using Umbraco.Core.Logging; using Umbraco.Core.Logging.Serilog; using Umbraco.Core.Manifest; +using Umbraco.Core.Mapping; +using Umbraco.Core.Media; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; @@ -31,39 +37,34 @@ using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; +using Umbraco.Core.Security; +using Umbraco.Core.Serialization; +using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Core.Strings; +using Umbraco.Net; +using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Components; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web; -using Umbraco.Web.Services; using Umbraco.Web.Actions; +using Umbraco.Web.AspNet; using Umbraco.Web.ContentApps; +using Umbraco.Web.Hosting; +using Umbraco.Web.Install; +using Umbraco.Web.PropertyEditors; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; -using Umbraco.Core.Composing.CompositionExtensions; -using Umbraco.Core.Hosting; -using Umbraco.Core.Mapping; -using Umbraco.Core.Serialization; -using Umbraco.Web.Composing.CompositionExtensions; -using Umbraco.Web.Hosting; using Umbraco.Web.Sections; -using FileSystems = Umbraco.Core.IO.FileSystems; -using Umbraco.Web.Templates; -using Umbraco.Web.PropertyEditors; -using Umbraco.Core.Dictionary; -using Umbraco.Net; -using Umbraco.Core.Security; -using Umbraco.Core.Services; -using Umbraco.Web.AspNet; -using Umbraco.Web.Install; using Umbraco.Web.Security; using Umbraco.Web.Security.Providers; +using Umbraco.Web.Services; +using Umbraco.Web.Templates; using Umbraco.Web.Trees; using Current = Umbraco.Web.Composing.Current; -using Umbraco.Tests.Common; -using Umbraco.Core.Media; +using FileSystems = Umbraco.Core.IO.FileSystems; using ILogger = Umbraco.Core.Logging.ILogger; namespace Umbraco.Tests.Testing @@ -143,7 +144,7 @@ namespace Umbraco.Tests.Testing protected virtual IProfilingLogger ProfilingLogger => Factory.GetInstance(); - protected IHostingEnvironment HostingEnvironment { get; } = new AspNetHostingEnvironment(TestHelpers.SettingsForTests.DefaultHostingSettings); + protected IHostingEnvironment HostingEnvironment { get; } = new AspNetHostingEnvironment(Microsoft.Extensions.Options.Options.Create(new HostingSettings())); protected IApplicationShutdownRegistry HostingLifetime { get; } = new AspNetApplicationShutdownRegistry(); protected IIpResolver IpResolver => Factory.GetInstance(); protected IBackOfficeInfo BackOfficeInfo => Factory.GetInstance(); @@ -181,12 +182,12 @@ namespace Umbraco.Tests.Testing TypeFinder = new TypeFinder(loggerFactoy.CreateLogger(), new DefaultUmbracoAssemblyProvider(GetType().Assembly), new VaryingRuntimeHash()); var appCaches = GetAppCaches(); - var globalSettings = TestHelpers.SettingsForTests.DefaultGlobalSettings; - var settings = TestHelpers.SettingsForTests.GenerateMockWebRoutingSettings(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var settings = new WebRoutingSettings(); - IBackOfficeInfo backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, IOHelper, loggerFactoy.CreateLogger(), settings); + IBackOfficeInfo backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, IOHelper, loggerFactoy.CreateLogger(), Microsoft.Extensions.Options.Options.Create(settings)); IIpResolver ipResolver = new AspNetIpResolver(); - UmbracoVersion = new UmbracoVersion(globalSettings); + UmbracoVersion = new UmbracoVersion(); LocalizedTextService = new LocalizedTextService(new Dictionary>(), logger); @@ -196,11 +197,12 @@ namespace Umbraco.Tests.Testing - Composition = new Composition(register, typeLoader, proflogger, ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.GetConfigs(), TestHelper.IOHelper, AppCaches.NoCache); + Composition = new Composition(register, typeLoader, proflogger, ComponentTests.MockRuntimeState(RuntimeLevel.Run), TestHelper.IOHelper, AppCaches.NoCache); + + //TestHelper.GetConfigs().RegisterWith(register); Composition.Register(new NullLoggerFactory()); Composition.Register(typeof(Microsoft.Extensions.Logging.ILogger<>), typeof(Logger<>)); - Composition.RegisterUnique(IOHelper); Composition.RegisterUnique(UriUtility); Composition.RegisterUnique(UmbracoVersion); @@ -352,15 +354,15 @@ namespace Umbraco.Tests.Testing Composition.RegisterUnique(); Composition.RegisterUnique(); Composition.RegisterUnique(); + + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); Composition.RegisterUnique(factory => new UrlProvider( factory.GetInstance(), - TestHelpers.SettingsForTests.GenerateMockWebRoutingSettings(), + Microsoft.Extensions.Options.Options.Create(webRoutingSettings), new UrlProviderCollection(Enumerable.Empty()), new MediaUrlProviderCollection(Enumerable.Empty()), - factory.GetInstance() - - )); + factory.GetInstance())); @@ -444,16 +446,21 @@ namespace Umbraco.Tests.Testing protected virtual void ComposeSettings() { - Composition.Configs.Add(() => TestHelpers.SettingsForTests.DefaultGlobalSettings); - Composition.Configs.Add(() => TestHelpers.SettingsForTests.DefaultHostingSettings); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockRequestHandlerSettings); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockWebRoutingSettings); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockSecuritySettings); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockUserPasswordConfiguration); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockMemberPasswordConfiguration); - Composition.Configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); + var contentSettings = new ContentSettingsBuilder().Build(); + var coreDebugSettings = new CoreDebugSettingsBuilder().Build(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var nuCacheSettings = new NuCacheSettingsBuilder().Build(); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + var userPasswordConfigurationSettings = new UserPasswordConfigurationSettingsBuilder().Build(); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); - //Composition.Configs.Add(() => new DefaultUserPasswordConfig()); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(contentSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(coreDebugSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(globalSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(nuCacheSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(requestHandlerSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(userPasswordConfigurationSettings)); + Composition.Register(x => Microsoft.Extensions.Options.Options.Create(webRoutingSettings)); } protected virtual void ComposeApplication(bool withApplication) @@ -490,14 +497,13 @@ namespace Umbraco.Tests.Testing Composition.RegisterUnique(_ => new TransientEventMessagesFactory()); - var globalSettings = TestHelper.GetConfigs().Global(); - var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); + var globalSettings = new GlobalSettingsBuilder().Build(); + var connectionStrings = new ConnectionStringsBuilder().Build(); Composition.RegisterUnique(f => new UmbracoDatabaseFactory(LoggerFactory_.CreateLogger(), LoggerFactory_, globalSettings, connectionStrings, - Constants.System.UmbracoConnectionName, new Lazy(f.GetInstance), TestHelper.DbProviderFactoryCreator)); @@ -587,7 +593,6 @@ namespace Umbraco.Tests.Testing // reset all other static things that should not be static ;( UriUtility.ResetAppDomainAppVirtualPath(HostingEnvironment); - TestHelpers.SettingsForTests.Reset(); // FIXME: should it be optional? // clear static events DocumentRepository.ClearScopeEvents(); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 35e5160c57..400b345cc9 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -145,6 +145,8 @@ + + @@ -195,7 +197,7 @@ - + @@ -399,7 +401,6 @@ - @@ -465,10 +466,6 @@ - - {fbe7c065-dac0-4025-a78b-63b24d3ab00b} - Umbraco.Configuration - {29aa69d9-b597-4395-8d42-43b1263c240a} Umbraco.Core diff --git a/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs b/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs index c97e2ce84b..15a158196c 100644 --- a/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs +++ b/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs @@ -6,6 +6,7 @@ using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Logging.Serilog; using Umbraco.Core.Strings; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.Components; using Umbraco.Tests.TestHelpers; using NullLogger = Microsoft.Extensions.Logging.Abstractions.NullLogger; @@ -34,8 +35,8 @@ namespace Umbraco.Tests.UmbracoExamine protected override void Compose() { base.Compose(); - - Composition.RegisterUnique(_ => new DefaultShortStringHelper(SettingsForTests.GenerateMockRequestHandlerSettings())); + var requestHandlerSettings = new RequestHandlerSettingsBuilder().Build(); + Composition.RegisterUnique(_ => new DefaultShortStringHelper(Microsoft.Extensions.Options.Options.Create(requestHandlerSettings))); } } } diff --git a/src/Umbraco.Tests/Web/Mvc/RenderNoContentControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/RenderNoContentControllerTests.cs index d33ce3bfcc..3f66dcb86c 100644 --- a/src/Umbraco.Tests/Web/Mvc/RenderNoContentControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/RenderNoContentControllerTests.cs @@ -2,6 +2,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Tests.Common; using Umbraco.Web; @@ -20,8 +21,7 @@ namespace Umbraco.Tests.Web.Mvc var mockUmbracoContext = new Mock(); mockUmbracoContext.Setup(x => x.Content.HasContent()).Returns(true); var mockIOHelper = new Mock(); - var mockGlobalSettings = new Mock(); - var controller = new RenderNoContentController(new TestUmbracoContextAccessor(mockUmbracoContext.Object), mockIOHelper.Object, mockGlobalSettings.Object); + var controller = new RenderNoContentController(new TestUmbracoContextAccessor(mockUmbracoContext.Object), mockIOHelper.Object, new GlobalSettings()); var result = controller.Index() as RedirectResult; @@ -39,10 +39,12 @@ namespace Umbraco.Tests.Web.Mvc mockUmbracoContext.Setup(x => x.Content.HasContent()).Returns(false); var mockIOHelper = new Mock(); mockIOHelper.Setup(x => x.ResolveUrl(It.Is(y => y == UmbracoPathSetting))).Returns(UmbracoPath); - var mockGlobalSettings = new Mock(); - mockGlobalSettings.SetupGet(x => x.UmbracoPath).Returns(UmbracoPathSetting); - mockGlobalSettings.SetupGet(x => x.NoNodesViewPath).Returns(ViewPath); - var controller = new RenderNoContentController(new TestUmbracoContextAccessor(mockUmbracoContext.Object), mockIOHelper.Object, mockGlobalSettings.Object); + var globalSettings = new GlobalSettings() + { + UmbracoPath = UmbracoPathSetting, + NoNodesViewPath = ViewPath, + }; + var controller = new RenderNoContentController(new TestUmbracoContextAccessor(mockUmbracoContext.Object), mockIOHelper.Object, globalSettings); var result = controller.Index() as ViewResult; Assert.IsNotNull(result); diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index 4c222b9116..8e0c534550 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Tests.Common; +using Umbraco.Tests.Common.Builders; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; using Umbraco.Web; @@ -155,8 +156,8 @@ namespace Umbraco.Tests.Web.Mvc var content = Mock.Of(publishedContent => publishedContent.Id == 12345); - - var publishedRouter = BaseWebTest.CreatePublishedRouter(TestHelpers.SettingsForTests.GenerateMockWebRoutingSettings()); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + var publishedRouter = BaseWebTest.CreatePublishedRouter(webRoutingSettings); var frequest = publishedRouter.CreateRequest(umbracoContext, new Uri("http://localhost/test")); frequest.PublishedContent = content; diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index c13c9abc2d..5542e34547 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -23,6 +23,7 @@ using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Umbraco.Web.Routing; using Umbraco.Web.Security; +using Umbraco.Tests.Common.Builders; namespace Umbraco.Tests.Web.Mvc { @@ -388,7 +389,8 @@ namespace Umbraco.Tests.Web.Mvc { var umbracoContext = GetUmbracoContext("/dang", 0); - var publishedRouter = BaseWebTest.CreatePublishedRouter(TestHelpers.SettingsForTests.GenerateMockWebRoutingSettings()); + var webRoutingSettings = new WebRoutingSettingsBuilder().Build(); + var publishedRouter = BaseWebTest.CreatePublishedRouter(webRoutingSettings); var frequest = publishedRouter.CreateRequest(umbracoContext, new Uri("http://localhost/dang")); frequest.Culture = CultureInfo.InvariantCulture; diff --git a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs index 25cae69900..524ad55650 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs @@ -1,17 +1,17 @@ -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Routing; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Models; @@ -45,11 +45,11 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IUserService _userService; private readonly ILocalizedTextService _textService; private readonly UmbracoMapper _umbracoMapper; - private readonly IGlobalSettings _globalSettings; - private readonly ISecuritySettings _securitySettings; + private readonly GlobalSettings _globalSettings; + private readonly SecuritySettings _securitySettings; private readonly ILogger _logger; private readonly IIpResolver _ipResolver; - private readonly IUserPasswordConfiguration _passwordConfiguration; + private readonly UserPasswordConfigurationSettings _passwordConfiguration; private readonly IEmailSender _emailSender; private readonly Core.Hosting.IHostingEnvironment _hostingEnvironment; private readonly IRequestAccessor _requestAccessor; @@ -64,11 +64,11 @@ namespace Umbraco.Web.BackOffice.Controllers IUserService userService, ILocalizedTextService textService, UmbracoMapper umbracoMapper, - IGlobalSettings globalSettings, - ISecuritySettings securitySettings, + IOptions globalSettings, + IOptions securitySettings, ILogger logger, IIpResolver ipResolver, - IUserPasswordConfiguration passwordConfiguration, + IOptions passwordConfiguration, IEmailSender emailSender, Core.Hosting.IHostingEnvironment hostingEnvironment, IRequestAccessor requestAccessor) @@ -79,11 +79,11 @@ namespace Umbraco.Web.BackOffice.Controllers _userService = userService; _textService = textService; _umbracoMapper = umbracoMapper; - _globalSettings = globalSettings; - _securitySettings = securitySettings; + _globalSettings = globalSettings.Value; + _securitySettings = securitySettings.Value; _logger = logger; _ipResolver = ipResolver; - _passwordConfiguration = passwordConfiguration; + _passwordConfiguration = passwordConfiguration.Value; _emailSender = emailSender; _hostingEnvironment = hostingEnvironment; _requestAccessor = requestAccessor; diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeAssetsController.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeAssetsController.cs index 7d336f29d7..bbb8195aa0 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeAssetsController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeAssetsController.cs @@ -4,8 +4,10 @@ using System.IO; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Web.Common.Attributes; @@ -17,9 +19,9 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly IFileSystem _jsLibFileSystem; - public BackOfficeAssetsController(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory, IGlobalSettings globalSettings) + public BackOfficeAssetsController(IIOHelper ioHelper, IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory, IOptions globalSettings) { - _jsLibFileSystem = new PhysicalFileSystem(ioHelper, hostingEnvironment, loggerFactory.CreateLogger(), globalSettings.UmbracoPath + Path.DirectorySeparatorChar + "lib"); + _jsLibFileSystem = new PhysicalFileSystem(ioHelper, hostingEnvironment, loggerFactory.CreateLogger(), globalSettings.Value.UmbracoPath + Path.DirectorySeparatorChar + "lib"); } [HttpGet] diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs index c550e44a56..24d46e894f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs @@ -5,13 +5,14 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Grid; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; using Umbraco.Core.Services; @@ -29,13 +30,14 @@ using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { - + //[UmbracoRequireHttps] //TODO Reintroduce + [DisableBrowserCache] [PluginController(Constants.Web.Mvc.BackOfficeArea)] public class BackOfficeController : Controller { private readonly BackOfficeUserManager _userManager; private readonly IRuntimeMinifier _runtimeMinifier; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly ILocalizedTextService _textService; @@ -49,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers public BackOfficeController( BackOfficeUserManager userManager, IRuntimeMinifier runtimeMinifier, - IGlobalSettings globalSettings, + IOptions globalSettings, IHostingEnvironment hostingEnvironment, IUmbracoContextAccessor umbracoContextAccessor, ILocalizedTextService textService, @@ -59,11 +61,10 @@ namespace Umbraco.Web.BackOffice.Controllers BackOfficeSignInManager signInManager, IWebSecurity webSecurity, ILogger logger) - { _userManager = userManager; _runtimeMinifier = runtimeMinifier; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _umbracoContextAccessor = umbracoContextAccessor; _textService = textService; diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs index 34494e1492..755c0b3a3f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs @@ -1,16 +1,15 @@ -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Routing; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; -using System.Text; using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.WebAssets; using Umbraco.Extensions; @@ -19,10 +18,8 @@ using Umbraco.Web.BackOffice.PropertyEditors; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Editors; using Umbraco.Web.Features; -using Umbraco.Web.HealthCheck; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; -using Umbraco.Web.WebApi; namespace Umbraco.Web.BackOffice.Controllers { @@ -34,14 +31,14 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly LinkGenerator _linkGenerator; private readonly IRuntimeState _runtimeState; private readonly UmbracoFeatures _features; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IUmbracoVersion _umbracoVersion; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly TreeCollection _treeCollection; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IRuntimeSettings _settings; - private readonly ISecuritySettings _securitySettings; + private readonly RuntimeSettings _runtimeSettings; + private readonly SecuritySettings _securitySettings; private readonly IRuntimeMinifier _runtimeMinifier; private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; @@ -49,28 +46,28 @@ namespace Umbraco.Web.BackOffice.Controllers LinkGenerator linkGenerator, IRuntimeState runtimeState, UmbracoFeatures features, - IGlobalSettings globalSettings, + IOptions globalSettings, IUmbracoVersion umbracoVersion, - IContentSettings contentSettings, + IOptions contentSettings, IHttpContextAccessor httpContextAccessor, TreeCollection treeCollection, IHostingEnvironment hostingEnvironment, - IRuntimeSettings settings, - ISecuritySettings securitySettings, + IOptions runtimeSettings, + IOptions securitySettings, IRuntimeMinifier runtimeMinifier, IAuthenticationSchemeProvider authenticationSchemeProvider) { _linkGenerator = linkGenerator; _runtimeState = runtimeState; _features = features; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _umbracoVersion = umbracoVersion; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _httpContextAccessor = httpContextAccessor; _treeCollection = treeCollection ?? throw new ArgumentNullException(nameof(treeCollection)); _hostingEnvironment = hostingEnvironment; - _settings = settings; - _securitySettings = securitySettings; + _runtimeSettings = runtimeSettings.Value; + _securitySettings = securitySettings.Value; _runtimeMinifier = runtimeMinifier; _authenticationSchemeProvider = authenticationSchemeProvider; } @@ -366,7 +363,7 @@ namespace Umbraco.Web.BackOffice.Controllers {"appPluginsPath", _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.AppPlugins).TrimEnd('/')}, { "imageFileTypes", - string.Join(",", _contentSettings.ImageFileTypes) + string.Join(",", _contentSettings.Imaging.ImageFileTypes) }, { "disallowedUploadFiles", @@ -513,7 +510,7 @@ namespace Umbraco.Web.BackOffice.Controllers private string GetMaxRequestLength() { - return _settings.MaxRequestLength.HasValue ? _settings.MaxRequestLength.Value.ToString() : string.Empty; + return _runtimeSettings.MaxRequestLength.HasValue ? _runtimeSettings.MaxRequestLength.Value.ToString() : string.Empty; } } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs index 621f3a0e78..4bf76a108a 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs @@ -3,11 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; -using System.Net.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Legacy; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Mapping; using Umbraco.Core.Models; @@ -15,15 +14,13 @@ using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Core.Strings.Css; using Umbraco.Extensions; -using Umbraco.Web.Models.ContentEditing; -using Stylesheet = Umbraco.Core.Models.Stylesheet; -using StylesheetRule = Umbraco.Web.Models.ContentEditing.StylesheetRule; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.ActionsResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; -using Umbraco.Web.Editors; -using Umbraco.Web.BackOffice.Trees; +using Umbraco.Web.Models.ContentEditing; +using Stylesheet = Umbraco.Core.Models.Stylesheet; +using StylesheetRule = Umbraco.Web.Models.ContentEditing.StylesheetRule; namespace Umbraco.Web.BackOffice.Controllers { @@ -41,7 +38,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ILocalizedTextService _localizedTextService; private readonly UmbracoMapper _umbracoMapper; private readonly IShortStringHelper _shortStringHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; public CodeFileController( IIOHelper ioHelper, @@ -51,9 +48,8 @@ namespace Umbraco.Web.BackOffice.Controllers ILocalizedTextService localizedTextService, UmbracoMapper umbracoMapper, IShortStringHelper shortStringHelper, - IGlobalSettings globalSettings) + IOptions globalSettings) { - _ioHelper = ioHelper; _fileSystems = fileSystems; _fileService = fileService; @@ -61,7 +57,7 @@ namespace Umbraco.Web.BackOffice.Controllers _localizedTextService = localizedTextService; _umbracoMapper = umbracoMapper; _shortStringHelper = shortStringHelper; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } /// diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs index 1b317b8427..a96a49ff39 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs @@ -32,6 +32,8 @@ using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; using Umbraco.Web.Security; using ContentType = Umbraco.Core.Models.ContentType; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.BackOffice.Controllers { @@ -48,7 +50,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class ContentTypeController : ContentTypeControllerBase { private readonly IEntityXmlSerializer _serializer; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly PropertyEditorCollection _propertyEditors; private readonly IScopeProvider _scopeProvider; private readonly IIOHelper _ioHelper; @@ -67,17 +69,15 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IEntityService _entityService; private readonly IHostingEnvironment _hostingEnvironment; - public ContentTypeController( ICultureDictionary cultureDictionary, - EditorValidatorCollection editorValidatorCollection, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, UmbracoMapper umbracoMapper, ILocalizedTextService localizedTextService, IEntityXmlSerializer serializer, - IGlobalSettings globalSettings, + IOptions globalSettings, PropertyEditorCollection propertyEditors, IScopeProvider scopeProvider, IIOHelper ioHelper, @@ -91,7 +91,8 @@ namespace Umbraco.Web.BackOffice.Controllers ILocalizationService localizationService, IMacroService macroService, IEntityService entityService, - IHostingEnvironment hostingEnvironment) + IHostingEnvironment hostingEnvironment, + EditorValidatorCollection editorValidatorCollection) : base(cultureDictionary, editorValidatorCollection, contentTypeService, @@ -101,7 +102,7 @@ namespace Umbraco.Web.BackOffice.Controllers localizedTextService) { _serializer = serializer; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _propertyEditors = propertyEditors; _scopeProvider = scopeProvider; _ioHelper = ioHelper; @@ -616,7 +617,7 @@ namespace Umbraco.Web.BackOffice.Controllers } var dataInstaller = new PackageDataInstallation(_logger, _fileService, _macroService, _LocalizationService, - _dataTypeService, _entityService, _contentTypeService, _contentService, _propertyEditors, _scopeProvider, _shortStringHelper, _globalSettings, _localizedTextService); + _dataTypeService, _entityService, _contentTypeService, _contentService, _propertyEditors, _scopeProvider, _shortStringHelper, Options.Create(_globalSettings), _localizedTextService); var xd = new XmlDocument {XmlResolver = null}; xd.Load(filePath); diff --git a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs index 3bf44f4e9c..433c26169f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs @@ -1,31 +1,30 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Net.Http; -using System.Threading.Tasks; -using Umbraco.Core.Services; -using Umbraco.Web.Models; -using Umbraco.Web.Models.ContentEditing; using System.Linq; +using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Cache; -using Umbraco.Core.IO; -using Umbraco.Web.WebApi.Filters; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Media; +using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.Security; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; +using Umbraco.Web.Models; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Security; namespace Umbraco.Web.BackOffice.Controllers @@ -37,7 +36,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class CurrentUserController : UmbracoAuthorizedJsonController { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IImageUrlGenerator _imageUrlGenerator; private readonly IWebSecurity _webSecurity; @@ -51,7 +50,7 @@ namespace Umbraco.Web.BackOffice.Controllers public CurrentUserController( IMediaFileSystem mediaFileSystem, - IContentSettings contentSettings, + IOptions contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, IWebSecurity webSecurity, @@ -64,7 +63,7 @@ namespace Umbraco.Web.BackOffice.Controllers IShortStringHelper shortStringHelper) { _mediaFileSystem = mediaFileSystem; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _hostingEnvironment = hostingEnvironment; _imageUrlGenerator = imageUrlGenerator; _webSecurity = webSecurity; diff --git a/src/Umbraco.Web.BackOffice/Controllers/DashboardController.cs b/src/Umbraco.Web.BackOffice/Controllers/DashboardController.cs index fca0a4da1a..5414b17b87 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DashboardController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DashboardController.cs @@ -43,7 +43,6 @@ namespace Umbraco.Web.BackOffice.Controllers /// Initializes a new instance of the with all its dependencies. /// public DashboardController( - IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, diff --git a/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs index 194029db4b..3ffcd5cec3 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DataTypeController.cs @@ -4,20 +4,21 @@ using System.Data; using System.Linq; using System.Net; using System.Net.Mime; +using System.Text; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; -using System.Text; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Mapping; -using Microsoft.AspNetCore.Mvc; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; +using Umbraco.Web.Models.ContentEditing; +using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { @@ -34,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly PropertyEditorCollection _propertyEditors; private readonly IDataTypeService _dataTypeService; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly UmbracoMapper _umbracoMapper; private readonly PropertyEditorCollection _propertyEditorCollection; private readonly IContentTypeService _contentTypeService; @@ -46,7 +47,7 @@ namespace Umbraco.Web.BackOffice.Controllers public DataTypeController( PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, - IContentSettings contentSettings, + IOptions contentSettings, UmbracoMapper umbracoMapper, PropertyEditorCollection propertyEditorCollection, IContentTypeService contentTypeService, @@ -57,7 +58,7 @@ namespace Umbraco.Web.BackOffice.Controllers { _propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors)); _dataTypeService = dataTypeService ?? throw new ArgumentNullException(nameof(dataTypeService)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper)); _propertyEditorCollection = propertyEditorCollection ?? throw new ArgumentNullException(nameof(propertyEditorCollection)); _contentTypeService = contentTypeService ?? throw new ArgumentNullException(nameof(contentTypeService)); diff --git a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs index f763deae0a..c61f727a5d 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs @@ -15,6 +15,8 @@ using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Security; using Constants = Umbraco.Core.Constants; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.BackOffice.Controllers { @@ -33,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ILogger _logger; private readonly ILocalizationService _localizationService; private readonly IWebSecurity _webSecurity; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly ILocalizedTextService _localizedTextService; private readonly UmbracoMapper _umbracoMapper; @@ -41,7 +43,7 @@ namespace Umbraco.Web.BackOffice.Controllers ILogger logger, ILocalizationService localizationService, IWebSecurity webSecurity, - IGlobalSettings globalSettings, + IOptions globalSettings, ILocalizedTextService localizedTextService, UmbracoMapper umbracoMapper ) @@ -49,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _webSecurity = webSecurity ?? throw new ArgumentNullException(nameof(webSecurity)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); + _globalSettings = globalSettings.Value ?? throw new ArgumentNullException(nameof(globalSettings)); _localizedTextService = localizedTextService ?? throw new ArgumentNullException(nameof(localizedTextService)); _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper)); } diff --git a/src/Umbraco.Web.BackOffice/Controllers/IconController.cs b/src/Umbraco.Web.BackOffice/Controllers/IconController.cs index bbefa82bd9..83d6ba299d 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/IconController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/IconController.cs @@ -4,7 +4,9 @@ using Umbraco.Web.Models; using System.IO; using Umbraco.Core; using Ganss.XSS; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.Common.Attributes; @@ -16,11 +18,11 @@ namespace Umbraco.Web.Editors public class IconController : UmbracoAuthorizedApiController { private readonly IHostingEnvironment _hostingEnvironment; - private readonly IGlobalSettings _globalSettings; + private readonly IOptions _globalSettings; public IconController( IHostingEnvironment hostingEnvironment, - IGlobalSettings globalSettings) + IOptions globalSettings) { _hostingEnvironment = hostingEnvironment; _globalSettings = globalSettings; @@ -37,7 +39,7 @@ namespace Umbraco.Web.Editors return string.IsNullOrWhiteSpace(iconName) ? null : CreateIconModel(iconName.StripFileExtension(), - _hostingEnvironment.MapPathWebRoot($"{_globalSettings.IconsPath}/{iconName}.svg")); + _hostingEnvironment.MapPathWebRoot($"{_globalSettings.Value.IconsPath}/{iconName}.svg")); } /// @@ -60,7 +62,7 @@ namespace Umbraco.Web.Editors public List GetAllIcons() { var icons = new List(); - var directory = new DirectoryInfo(_hostingEnvironment.MapPathWebRoot($"{_globalSettings.IconsPath}/")); + var directory = new DirectoryInfo(_hostingEnvironment.MapPathWebRoot($"{_globalSettings.Value.IconsPath}/")); var iconNames = directory.GetFiles("*.svg"); iconNames.OrderBy(f => f.Name).ToList().ForEach(iconInfo => diff --git a/src/Umbraco.Web.BackOffice/Controllers/ImagesController.cs b/src/Umbraco.Web.BackOffice/Controllers/ImagesController.cs index 70e0c71e55..6f1b7fb037 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ImagesController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ImagesController.cs @@ -1,8 +1,10 @@ using System; using System.IO; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Media; using Umbraco.Core.Models; @@ -18,14 +20,16 @@ namespace Umbraco.Web.BackOffice.Controllers public class ImagesController : UmbracoAuthorizedApiController { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IImageUrlGenerator _imageUrlGenerator; - public ImagesController(IMediaFileSystem mediaFileSystem, IContentSettings contentSettings, + public ImagesController( + IMediaFileSystem mediaFileSystem, + IOptions contentSettings, IImageUrlGenerator imageUrlGenerator) { _mediaFileSystem = mediaFileSystem; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _imageUrlGenerator = imageUrlGenerator; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs b/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs index 14667c1fe5..66f8b6d7e0 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/LanguageController.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -25,15 +27,15 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly ILocalizationService _localizationService; private readonly UmbracoMapper _umbracoMapper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; public LanguageController(ILocalizationService localizationService, UmbracoMapper umbracoMapper, - IGlobalSettings globalSettings) + IOptions globalSettings) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); + _globalSettings = globalSettings.Value ?? throw new ArgumentNullException(nameof(globalSettings)); } /// diff --git a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs index 94e5b58095..c24ac382bd 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs @@ -3,35 +3,30 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Mime; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Newtonsoft.Json; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; using Umbraco.Core.Hosting; +using Umbraco.Core.IO; +using Umbraco.Core.Logging; +using Umbraco.Core.Mapping; +using Umbraco.Core.Models; using Umbraco.Core.Models.ContentEditing; -using Umbraco.Core.Models.Editors; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Validation; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.PropertyEditors; -using Umbraco.Web.ContentApps; -using Umbraco.Web.WebApi.Filters; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Mapping; +using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; @@ -39,7 +34,11 @@ using Umbraco.Web.BackOffice.ModelBinders; using Umbraco.Web.Common.ActionResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; +using Umbraco.Web.ContentApps; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Security; +using Umbraco.Web.WebApi.Filters; +using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { @@ -52,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class MediaController : ContentControllerBase { private readonly IShortStringHelper _shortStringHelper; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IMediaTypeService _mediaTypeService; private readonly IMediaService _mediaService; private readonly IEntityService _entityService; @@ -69,7 +68,7 @@ namespace Umbraco.Web.BackOffice.Controllers IShortStringHelper shortStringHelper, IEventMessagesFactory eventMessages, ILocalizedTextService localizedTextService, - IContentSettings contentSettings, + IOptions contentSettings, IMediaTypeService mediaTypeService, IMediaService mediaService, IEntityService entityService, @@ -85,7 +84,7 @@ namespace Umbraco.Web.BackOffice.Controllers : base(cultureDictionary, logger, shortStringHelper, eventMessages, localizedTextService) { _shortStringHelper = shortStringHelper; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _mediaTypeService = mediaTypeService; _mediaService = mediaService; _entityService = entityService; @@ -742,7 +741,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (contentTypeAlias == Constants.Conventions.MediaTypes.AutoSelect) { - if (_contentSettings.ImageFileTypes.Contains(ext)) + if (_contentSettings.Imaging.ImageFileTypes.Contains(ext)) { mediaType = Constants.Conventions.MediaTypes.Image; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs index 9627c96e24..6a93bf6437 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs @@ -8,23 +8,20 @@ using System.Net.Mime; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; using Umbraco.Core.Logging; +using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Security; +using Umbraco.Core.Serialization; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; -using Umbraco.Web.ContentApps; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.WebApi.Filters; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Mapping; -using Umbraco.Core.Serialization; using Umbraco.Core.Strings; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; @@ -32,7 +29,11 @@ using Umbraco.Web.BackOffice.ModelBinders; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Common.Filters; +using Umbraco.Web.ContentApps; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Security; +using Umbraco.Web.WebApi.Filters; +using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.BackOffice.Controllers { @@ -45,8 +46,7 @@ namespace Umbraco.Web.BackOffice.Controllers [OutgoingNoHyphenGuidFormat] public class MemberController : ContentControllerBase { - - private readonly IMemberPasswordConfiguration _passwordConfig; + private readonly MemberPasswordConfigurationSettings _passwordConfig; private readonly PropertyEditorCollection _propertyEditors; private readonly LegacyPasswordSecurity _passwordSecurity; private readonly UmbracoMapper _umbracoMapper; @@ -63,7 +63,7 @@ namespace Umbraco.Web.BackOffice.Controllers IShortStringHelper shortStringHelper, IEventMessagesFactory eventMessages, ILocalizedTextService localizedTextService, - IMemberPasswordConfiguration passwordConfig, + IOptions passwordConfig, PropertyEditorCollection propertyEditors, LegacyPasswordSecurity passwordSecurity, UmbracoMapper umbracoMapper, @@ -74,7 +74,7 @@ namespace Umbraco.Web.BackOffice.Controllers IJsonSerializer jsonSerializer) : base(cultureDictionary, logger, shortStringHelper, eventMessages, localizedTextService) { - _passwordConfig = passwordConfig; + _passwordConfig = passwordConfig.Value; _propertyEditors = propertyEditors; _passwordSecurity = passwordSecurity; _umbracoMapper = umbracoMapper; diff --git a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs index fec9d23f19..3878eb9b14 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs @@ -1,11 +1,13 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.Extensions.Options; using System; using System.IO; using System.Threading.Tasks; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; using Umbraco.Core.Services; @@ -28,7 +30,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class PreviewController : Controller { private readonly UmbracoFeatures _features; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IPublishedSnapshotService _publishedSnapshotService; private readonly IWebSecurity _webSecurity; private readonly ILocalizationService _localizationService; @@ -39,7 +41,7 @@ namespace Umbraco.Web.BackOffice.Controllers public PreviewController( UmbracoFeatures features, - IGlobalSettings globalSettings, + IOptions globalSettings, IPublishedSnapshotService publishedSnapshotService, IWebSecurity webSecurity, ILocalizationService localizationService, @@ -49,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers ICompositeViewEngine viewEngines) { _features = features; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _publishedSnapshotService = publishedSnapshotService; _webSecurity = webSecurity; _localizationService = localizationService; diff --git a/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs b/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs index 5e9943c913..c503de68f5 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs @@ -13,6 +13,8 @@ using Umbraco.Core.Services; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Security; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.BackOffice.Controllers { @@ -20,7 +22,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class RedirectUrlManagementController : UmbracoAuthorizedApiController { private readonly ILogger _logger; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly IWebSecurity _webSecurity; private readonly IRedirectUrlService _redirectUrlService; private readonly UmbracoMapper _umbracoMapper; @@ -29,7 +31,7 @@ namespace Umbraco.Web.BackOffice.Controllers public RedirectUrlManagementController( ILogger logger, - IWebRoutingSettings webRoutingSettings, + IOptions webRoutingSettings, IWebSecurity webSecurity, IRedirectUrlService redirectUrlService, UmbracoMapper umbracoMapper, @@ -37,7 +39,7 @@ namespace Umbraco.Web.BackOffice.Controllers IConfigManipulator configManipulator) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _webRoutingSettings = webRoutingSettings ?? throw new ArgumentNullException(nameof(webRoutingSettings)); + _webRoutingSettings = webRoutingSettings.Value ?? throw new ArgumentNullException(nameof(webRoutingSettings)); _webSecurity = webSecurity ?? throw new ArgumentNullException(nameof(webSecurity)); _redirectUrlService = redirectUrlService ?? throw new ArgumentNullException(nameof(redirectUrlService)); _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper)); diff --git a/src/Umbraco.Web.BackOffice/Controllers/TinyMceController.cs b/src/Umbraco.Web.BackOffice/Controllers/TinyMceController.cs index dd7c539922..b62d6b6080 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/TinyMceController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/TinyMceController.cs @@ -6,8 +6,10 @@ using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Strings; @@ -28,19 +30,19 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly IHostingEnvironment _hostingEnvironment; private readonly IShortStringHelper _shortStringHelper; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IIOHelper _ioHelper; public TinyMceController( IHostingEnvironment hostingEnvironment, IShortStringHelper shortStringHelper, - IContentSettings contentSettings, + IOptions contentSettings, IIOHelper ioHelper ) { _hostingEnvironment = hostingEnvironment; _shortStringHelper = shortStringHelper; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _ioHelper = ioHelper; } @@ -76,7 +78,7 @@ namespace Umbraco.Web.BackOffice.Controllers var safeFileName = fileName.ToSafeFileName(_shortStringHelper); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); - if (_contentSettings.IsFileAllowedForUpload(ext) == false || _contentSettings.ImageFileTypes.Contains(ext) == false) + if (_contentSettings.IsFileAllowedForUpload(ext) == false || _contentSettings.Imaging.ImageFileTypes.Contains(ext) == false) { // Throw some error - to say can't upload this IMG type return new UmbracoProblemResult("This is not an image filetype extension that is approved", HttpStatusCode.BadRequest); diff --git a/src/Umbraco.Web.BackOffice/Controllers/TourController.cs b/src/Umbraco.Web.BackOffice/Controllers/TourController.cs index f85bdb1bd5..6e7af87a11 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/TourController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/TourController.cs @@ -2,9 +2,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Umbraco.Core; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Services; using Umbraco.Web.Common.Attributes; @@ -19,21 +20,21 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly TourFilterCollection _filters; private readonly IHostingEnvironment _hostingEnvironment; - private readonly ITourSettings _tourSettings; + private readonly TourSettings _tourSettings; private readonly IWebSecurity _webSecurity; private readonly IContentTypeService _contentTypeService; public TourController( TourFilterCollection filters, IHostingEnvironment hostingEnvironment, - ITourSettings tourSettings, + IOptions tourSettings, IWebSecurity webSecurity, IContentTypeService contentTypeService) { _filters = filters; _hostingEnvironment = hostingEnvironment; - _tourSettings = tourSettings; + _tourSettings = tourSettings.Value; _webSecurity = webSecurity; _contentTypeService = contentTypeService; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/UmbracoAuthorizedApiController.cs b/src/Umbraco.Web.BackOffice/Controllers/UmbracoAuthorizedApiController.cs index c3e1a71b86..85c92d1139 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UmbracoAuthorizedApiController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UmbracoAuthorizedApiController.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.BackOffice.Controllers [UmbracoAuthorize] [DisableBrowserCache] [UmbracoWebApiRequireHttps] - //[CheckIfUserTicketDataIsStale] //TODO reintroduce + [CheckIfUserTicketDataIsStale] //[UnhandedExceptionLoggerConfiguration] //TODO reintroduce //[EnableDetailedErrors] //TODO reintroduce public abstract class UmbracoAuthorizedApiController : UmbracoApiController diff --git a/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs b/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs index 4212bace72..16fcb5b38c 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs @@ -3,10 +3,12 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; using Semver; using Umbraco.Composing; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Web.Common.Attributes; @@ -22,20 +24,20 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IUmbracoVersion _umbracoVersion; private readonly ICookieManager _cookieManager; private readonly IWebSecurity _webSecurity; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; public UpdateCheckController( IUpgradeService upgradeService, IUmbracoVersion umbracoVersion, ICookieManager cookieManager, IWebSecurity webSecurity, - IGlobalSettings globalSettings) + IOptions globalSettings) { _upgradeService = upgradeService ?? throw new ArgumentNullException(nameof(upgradeService)); _umbracoVersion = umbracoVersion ?? throw new ArgumentNullException(nameof(umbracoVersion)); _cookieManager = cookieManager ?? throw new ArgumentNullException(nameof(cookieManager)); _webSecurity = webSecurity ?? throw new ArgumentNullException(nameof(webSecurity)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); + _globalSettings = globalSettings.Value ?? throw new ArgumentNullException(nameof(globalSettings)); } [UpdateCheckResponseFilter] @@ -77,11 +79,11 @@ namespace Umbraco.Web.BackOffice.Controllers private class UpdateCheckResponseFilter : IActionFilter { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public UpdateCheckResponseFilter(IGlobalSettings globalSettings) + public UpdateCheckResponseFilter(IOptions globalSettings) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public void OnActionExecuted(ActionExecutedContext context) diff --git a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs index 1359244055..3cffa307eb 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Mail; using System.Runtime.Serialization; using System.Security.Cryptography; @@ -11,27 +10,22 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; +using Umbraco.Core.Mapping; +using Umbraco.Core.Media; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence; using Umbraco.Core.Services; using Umbraco.Core.Strings; -using Umbraco.Web.Models; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.WebApi.Filters; -using Constants = Umbraco.Core.Constants; -using IUser = Umbraco.Core.Models.Membership.IUser; -using Task = System.Threading.Tasks.Task; -using Umbraco.Core.Mapping; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.Hosting; -using Umbraco.Core.Media; using Umbraco.Extensions; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.BackOffice.ModelBinders; @@ -40,7 +34,13 @@ using Umbraco.Web.Common.ActionResults; using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Editors; +using Umbraco.Web.Models; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Security; +using Umbraco.Web.WebApi.Filters; +using Constants = Umbraco.Core.Constants; +using IUser = Umbraco.Core.Models.Membership.IUser; +using Task = System.Threading.Tasks.Task; namespace Umbraco.Web.BackOffice.Controllers { @@ -51,11 +51,11 @@ namespace Umbraco.Web.BackOffice.Controllers public class UsersController : UmbracoAuthorizedJsonController { private readonly IMediaFileSystem _mediaFileSystem; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly ISqlContext _sqlContext; private readonly IImageUrlGenerator _imageUrlGenerator; - private readonly ISecuritySettings _securitySettings; + private readonly SecuritySettings _securitySettings; private readonly IRequestAccessor _requestAccessor; private readonly IEmailSender _emailSender; private readonly IWebSecurity _webSecurity; @@ -67,18 +67,18 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IEntityService _entityService; private readonly IMediaService _mediaService; private readonly IContentService _contentService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly BackOfficeUserManager _backOfficeUserManager; private readonly ILogger _logger; private readonly LinkGenerator _linkGenerator; public UsersController( IMediaFileSystem mediaFileSystem, - IContentSettings contentSettings, + IOptions contentSettings, IHostingEnvironment hostingEnvironment, ISqlContext sqlContext, IImageUrlGenerator imageUrlGenerator, - ISecuritySettings securitySettings, + IOptions securitySettings, IRequestAccessor requestAccessor, IEmailSender emailSender, IWebSecurity webSecurity, @@ -90,17 +90,17 @@ namespace Umbraco.Web.BackOffice.Controllers IEntityService entityService, IMediaService mediaService, IContentService contentService, - IGlobalSettings globalSettings, + IOptions globalSettings, BackOfficeUserManager backOfficeUserManager, ILogger logger, LinkGenerator linkGenerator) { _mediaFileSystem = mediaFileSystem; - _contentSettings = contentSettings; + _contentSettings = contentSettings.Value; _hostingEnvironment = hostingEnvironment; _sqlContext = sqlContext; _imageUrlGenerator = imageUrlGenerator; - _securitySettings = securitySettings; + _securitySettings = securitySettings.Value; _requestAccessor = requestAccessor; _emailSender = emailSender; _webSecurity = webSecurity; @@ -112,7 +112,7 @@ namespace Umbraco.Web.BackOffice.Controllers _entityService = entityService; _mediaService = mediaService; _contentService = contentService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _backOfficeUserManager = backOfficeUserManager; _logger = logger; _linkGenerator = linkGenerator; @@ -138,7 +138,7 @@ namespace Umbraco.Web.BackOffice.Controllers return await PostSetAvatarInternal(files, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, id); } - internal static async Task PostSetAvatarInternal(IList files, IUserService userService, IAppCache cache, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, IContentSettings contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, int id) + internal static async Task PostSetAvatarInternal(IList files, IUserService userService, IAppCache cache, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, ContentSettings contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, int id) { if (files is null) { diff --git a/src/Umbraco.Web.BackOffice/Extensions/BackOfficeServiceCollectionExtensions.cs b/src/Umbraco.Web.BackOffice/Extensions/BackOfficeServiceCollectionExtensions.cs index f135a72293..d9eb0987d0 100644 --- a/src/Umbraco.Web.BackOffice/Extensions/BackOfficeServiceCollectionExtensions.cs +++ b/src/Umbraco.Web.BackOffice/Extensions/BackOfficeServiceCollectionExtensions.cs @@ -7,9 +7,10 @@ using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Security; using Umbraco.Core.Serialization; using Umbraco.Net; @@ -79,7 +80,7 @@ namespace Umbraco.Extensions services.TryAddScoped, PasswordValidator>(); services.TryAddScoped>( services => new BackOfficePasswordHasher( - new LegacyPasswordSecurity(services.GetRequiredService()), + new LegacyPasswordSecurity(services.GetRequiredService>().Value), services.GetRequiredService())); services.TryAddScoped, DefaultUserConfirmation>(); services.TryAddScoped, UserClaimsPrincipalFactory>(); diff --git a/src/Umbraco.Web.BackOffice/Filters/CheckIfUserTicketDataIsStaleAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/CheckIfUserTicketDataIsStaleAttribute.cs new file mode 100644 index 0000000000..cde2f77bf7 --- /dev/null +++ b/src/Umbraco.Web.BackOffice/Filters/CheckIfUserTicketDataIsStaleAttribute.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; +using Umbraco.Core; +using Umbraco.Core.BackOffice; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Mapping; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Membership; +using Umbraco.Core.Services; +using Umbraco.Extensions; +using Umbraco.Web.BackOffice.Security; +using Umbraco.Web.Common.Security; + +namespace Umbraco.Web.BackOffice.Filters +{ + internal sealed class CheckIfUserTicketDataIsStaleAttribute : TypeFilterAttribute + { + public CheckIfUserTicketDataIsStaleAttribute() : base(typeof(CheckIfUserTicketDataIsStaleFilter)) + { + } + + private class CheckIfUserTicketDataIsStaleFilter : IAsyncActionFilter + { + private readonly IRequestCache _requestCache; + private readonly UmbracoMapper _umbracoMapper; + private readonly IUserService _userService; + private readonly IEntityService _entityService; + private readonly ILocalizedTextService _localizedTextService; + private readonly IOptions _globalSettings; + private readonly BackOfficeSignInManager _backOfficeSignInManager; + private readonly IBackOfficeAntiforgery _backOfficeAntiforgery; + + public CheckIfUserTicketDataIsStaleFilter( + IRequestCache requestCache, + UmbracoMapper umbracoMapper, + IUserService userService, + IEntityService entityService, + ILocalizedTextService localizedTextService, + IOptions globalSettings, + BackOfficeSignInManager backOfficeSignInManager, + IBackOfficeAntiforgery backOfficeAntiforgery) + { + _requestCache = requestCache; + _umbracoMapper = umbracoMapper; + _userService = userService; + _entityService = entityService; + _localizedTextService = localizedTextService; + _globalSettings = globalSettings; + _backOfficeSignInManager = backOfficeSignInManager; + _backOfficeAntiforgery = backOfficeAntiforgery; + } + + + public async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next) + { + await CheckStaleData(actionContext); + + await next(); + + await CheckStaleData(actionContext); + + //return if nothing is updated + if (_requestCache.Get(nameof(CheckIfUserTicketDataIsStaleFilter)) is null) + return; + + await UpdateTokensAndAppendCustomHeaders(actionContext); + } + + private async Task UpdateTokensAndAppendCustomHeaders(ActionExecutingContext actionContext) + { + var tokenFilter = + new SetAngularAntiForgeryTokensAttribute.SetAngularAntiForgeryTokensFilter(_backOfficeAntiforgery, + _globalSettings); + await tokenFilter.OnActionExecutionAsync(actionContext, + () => Task.FromResult(new ActionExecutedContext(actionContext, new List(), null))); + + //add the header + AppendUserModifiedHeaderAttribute.AppendHeader(actionContext); + } + + + private async Task CheckStaleData(ActionExecutingContext actionContext) + { + if (actionContext?.HttpContext.Request == null || actionContext.HttpContext.User?.Identity == null) + { + return; + } + + //don't execute if it's already been done + if (!(_requestCache.Get(nameof(CheckIfUserTicketDataIsStaleFilter)) is null)) + return; + + var identity = actionContext.HttpContext.User.Identity as UmbracoBackOfficeIdentity; + if (identity == null) return; + + var userId = identity.Id.TryConvertTo(); + if (userId == false) return; + + var user = _userService.GetUserById(userId.Result); + if (user == null) return; + + //a list of checks to execute, if any of them pass then we resync + var checks = new Func[] + { + () => user.Username != identity.Username, + () => + { + var culture = user.GetUserCulture(_localizedTextService, _globalSettings.Value); + return culture != null && culture.ToString() != identity.Culture; + }, + () => user.AllowedSections.UnsortedSequenceEqual(identity.AllowedApplications) == false, + () => user.Groups.Select(x => x.Alias).UnsortedSequenceEqual(identity.Roles) == false, + () => + { + var startContentIds = user.CalculateContentStartNodeIds(_entityService); + return startContentIds.UnsortedSequenceEqual(identity.StartContentNodes) == false; + }, + () => + { + var startMediaIds = user.CalculateMediaStartNodeIds(_entityService); + return startMediaIds.UnsortedSequenceEqual(identity.StartMediaNodes) == false; + } + }; + + if (checks.Any(check => check())) + { + await ReSync(user, actionContext); + } + } + + /// + /// This will update the current request IPrincipal to be correct and re-create the auth ticket + /// + /// + /// + /// + private async Task ReSync(IUser user, ActionExecutingContext actionContext) + { + var backOfficeIdentityUser = _umbracoMapper.Map(user); + await _backOfficeSignInManager.SignInAsync(backOfficeIdentityUser, isPersistent: true); + + //ensure the remainder of the request has the correct principal set + actionContext.HttpContext.SetPrincipalForRequest(ClaimsPrincipal.Current); + + //flag that we've made changes + _requestCache.Set(nameof(CheckIfUserTicketDataIsStaleFilter), true); + } + } + } +} diff --git a/src/Umbraco.Web.BackOffice/Filters/SetAngularAntiForgeryTokensAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/SetAngularAntiForgeryTokensAttribute.cs index e52287b57e..aaf23d1799 100644 --- a/src/Umbraco.Web.BackOffice/Filters/SetAngularAntiForgeryTokensAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/SetAngularAntiForgeryTokensAttribute.cs @@ -2,8 +2,9 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.BackOffice.Security; namespace Umbraco.Extensions @@ -17,15 +18,15 @@ namespace Umbraco.Extensions { } - private class SetAngularAntiForgeryTokensFilter : IAsyncActionFilter + internal class SetAngularAntiForgeryTokensFilter : IAsyncActionFilter { private readonly IBackOfficeAntiforgery _antiforgery; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public SetAngularAntiForgeryTokensFilter(IBackOfficeAntiforgery antiforgery, IGlobalSettings globalSettings) + public SetAngularAntiForgeryTokensFilter(IBackOfficeAntiforgery antiforgery, IOptions globalSettings) { _antiforgery = antiforgery; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) @@ -54,24 +55,31 @@ namespace Umbraco.Extensions //We need to set 2 cookies: one is the cookie value that angular will use to set a header value on each request, // the 2nd is the validation value generated by the anti-forgery helper that we use to validate the header token against. - context.HttpContext.Response.Cookies.Append( - Constants.Web.AngularCookieName, headerToken, - new Microsoft.AspNetCore.Http.CookieOptions - { - Path = "/", - //must be js readable - HttpOnly = false, - Secure = _globalSettings.UseHttps - }); + if (!(headerToken is null)) + { + context.HttpContext.Response.Cookies.Append( + Constants.Web.AngularCookieName, headerToken, + new Microsoft.AspNetCore.Http.CookieOptions + { + Path = "/", + //must be js readable + HttpOnly = false, + Secure = _globalSettings.UseHttps + }); + } + + if (!(cookieToken is null)) + { + context.HttpContext.Response.Cookies.Append( + Constants.Web.CsrfValidationCookieName, cookieToken, + new Microsoft.AspNetCore.Http.CookieOptions + { + Path = "/", + HttpOnly = true, + Secure = _globalSettings.UseHttps + }); + } - context.HttpContext.Response.Cookies.Append( - Constants.Web.CsrfValidationCookieName, cookieToken, - new Microsoft.AspNetCore.Http.CookieOptions - { - Path = "/", - HttpOnly = true, - Secure = _globalSettings.UseHttps - }); } } diff --git a/src/Umbraco.Web.BackOffice/Filters/UmbracoWebApiRequireHttpsAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/UmbracoWebApiRequireHttpsAttribute.cs index 7c7652c532..e2a1d942d9 100644 --- a/src/Umbraco.Web.BackOffice/Filters/UmbracoWebApiRequireHttpsAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/UmbracoWebApiRequireHttpsAttribute.cs @@ -3,7 +3,8 @@ using System.Net; using System.Net.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using Umbraco.Core.Configuration; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.BackOffice.Filters { @@ -27,11 +28,11 @@ namespace Umbraco.Web.BackOffice.Filters public class UmbracoWebApiRequireHttpsFilter: IAuthorizationFilter { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public UmbracoWebApiRequireHttpsFilter(IGlobalSettings globalSettings) + public UmbracoWebApiRequireHttpsFilter(IOptions globalSettings) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; } public void OnAuthorization(AuthorizationFilterContext context) diff --git a/src/Umbraco.Web.BackOffice/HealthCheck/HealthCheckController.cs b/src/Umbraco.Web.BackOffice/HealthCheck/HealthCheckController.cs index 586768b899..add187c0d2 100644 --- a/src/Umbraco.Web.BackOffice/HealthCheck/HealthCheckController.cs +++ b/src/Umbraco.Web.BackOffice/HealthCheck/HealthCheckController.cs @@ -8,6 +8,8 @@ using Umbraco.Core.Configuration.HealthChecks; using Umbraco.Web.BackOffice.Filters; using Umbraco.Web.HealthCheck; using Umbraco.Web.Common.Attributes; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.BackOffice.Controllers { @@ -22,12 +24,12 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IList _disabledCheckIds; private readonly ILogger _logger; - public HealthCheckController(HealthCheckCollection checks, ILogger logger, IHealthChecksSettings healthChecksSettings) + public HealthCheckController(HealthCheckCollection checks, ILogger logger, IOptions healthChecksSettings) { _checks = checks ?? throw new ArgumentNullException(nameof(checks)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - var healthCheckConfig = healthChecksSettings ?? throw new ArgumentNullException(nameof(healthChecksSettings)); + var healthCheckConfig = healthChecksSettings.Value ?? throw new ArgumentNullException(nameof(healthChecksSettings)); _disabledCheckIds = healthCheckConfig.DisabledChecks .Select(x => x.Id) .ToList(); diff --git a/src/Umbraco.Web.BackOffice/Mapping/MediaMapDefinition.cs b/src/Umbraco.Web.BackOffice/Mapping/MediaMapDefinition.cs index 0a7bdb0026..4076f01aab 100644 --- a/src/Umbraco.Web.BackOffice/Mapping/MediaMapDefinition.cs +++ b/src/Umbraco.Web.BackOffice/Mapping/MediaMapDefinition.cs @@ -1,14 +1,14 @@ -using Umbraco.Core; +using System; +using Microsoft.Extensions.Options; +using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Dictionary; -using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; -using Umbraco.Core.Configuration.UmbracoSettings; -using System; namespace Umbraco.Web.Models.Mapping { @@ -23,17 +23,17 @@ namespace Umbraco.Web.Models.Mapping private readonly IMediaTypeService _mediaTypeService; private readonly MediaUrlGeneratorCollection _mediaUrlGenerators; private readonly TabsAndPropertiesMapper _tabsAndPropertiesMapper; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; public MediaMapDefinition(ICultureDictionary cultureDictionary, CommonMapper commonMapper, CommonTreeNodeMapper commonTreeNodeMapper, IMediaService mediaService, IMediaTypeService mediaTypeService, - ILocalizedTextService localizedTextService, MediaUrlGeneratorCollection mediaUrlGenerators, IContentSettings contentSettings, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider) + ILocalizedTextService localizedTextService, MediaUrlGeneratorCollection mediaUrlGenerators, IOptions contentSettings, IContentTypeBaseServiceProvider contentTypeBaseServiceProvider) { _commonMapper = commonMapper; _commonTreeNodeMapper = commonTreeNodeMapper; _mediaService = mediaService; _mediaTypeService = mediaTypeService; _mediaUrlGenerators = mediaUrlGenerators; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _tabsAndPropertiesMapper = new TabsAndPropertiesMapper(cultureDictionary, localizedTextService, contentTypeBaseServiceProvider); } diff --git a/src/Umbraco.Web.BackOffice/Routing/BackOfficeAreaRoutes.cs b/src/Umbraco.Web.BackOffice/Routing/BackOfficeAreaRoutes.cs index ec0a75fe11..dd3b3988c9 100644 --- a/src/Umbraco.Web.BackOffice/Routing/BackOfficeAreaRoutes.cs +++ b/src/Umbraco.Web.BackOffice/Routing/BackOfficeAreaRoutes.cs @@ -1,6 +1,8 @@ using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Web.BackOffice.Controllers; using Umbraco.Web.Common.Controllers; @@ -14,19 +16,19 @@ namespace Umbraco.Web.BackOffice.Routing /// public class BackOfficeAreaRoutes : IAreaRoutes { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IRuntimeState _runtimeState; private readonly UmbracoApiControllerTypeCollection _apiControllers; private readonly string _umbracoPathSegment; public BackOfficeAreaRoutes( - IGlobalSettings globalSettings, + IOptions globalSettings, IHostingEnvironment hostingEnvironment, IRuntimeState runtimeState, UmbracoApiControllerTypeCollection apiControllers) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _runtimeState = runtimeState; _apiControllers = apiControllers; diff --git a/src/Umbraco.Web.BackOffice/Security/BackOfficeCookieManager.cs b/src/Umbraco.Web.BackOffice/Security/BackOfficeCookieManager.cs index 75112e9a22..60bdc9c8ff 100644 --- a/src/Umbraco.Web.BackOffice/Security/BackOfficeCookieManager.cs +++ b/src/Umbraco.Web.BackOffice/Security/BackOfficeCookieManager.cs @@ -1,16 +1,15 @@ -using Microsoft.AspNetCore.Authentication.Cookies; +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Routing; -using System; -using System.Collections.Generic; -using System.Linq; using Umbraco.Core; -using Umbraco.Extensions; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Web.BackOffice.Controllers; +using Umbraco.Extensions; namespace Umbraco.Web.BackOffice.Security { @@ -28,7 +27,7 @@ namespace Umbraco.Web.BackOffice.Security private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly IRuntimeState _runtime; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IRequestCache _requestCache; private readonly string[] _explicitPaths; @@ -36,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Security IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IHostingEnvironment hostingEnvironment, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IRequestCache requestCache, LinkGenerator linkGenerator) : this(umbracoContextAccessor, runtime, hostingEnvironment, globalSettings, requestCache, linkGenerator, null) @@ -46,7 +45,7 @@ namespace Umbraco.Web.BackOffice.Security IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IHostingEnvironment hostingEnvironment, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IRequestCache requestCache, LinkGenerator linkGenerator, IEnumerable explicitPaths) diff --git a/src/Umbraco.Web.BackOffice/Security/BackOfficeSessionIdValidator.cs b/src/Umbraco.Web.BackOffice/Security/BackOfficeSessionIdValidator.cs index fdf630e01c..e91a517496 100644 --- a/src/Umbraco.Web.BackOffice/Security/BackOfficeSessionIdValidator.cs +++ b/src/Umbraco.Web.BackOffice/Security/BackOfficeSessionIdValidator.cs @@ -1,16 +1,14 @@  +using System; +using System.Security.Claims; +using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Extensions; @@ -37,14 +35,14 @@ namespace Umbraco.Web.BackOffice.Security { public const string CookieName = "UMB_UCONTEXT_C"; private readonly ISystemClock _systemClock; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly BackOfficeUserManager _userManager; - public BackOfficeSessionIdValidator(ISystemClock systemClock, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, BackOfficeUserManager userManager) + public BackOfficeSessionIdValidator(ISystemClock systemClock, IOptions globalSettings, IHostingEnvironment hostingEnvironment, BackOfficeUserManager userManager) { _systemClock = systemClock; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _userManager = userManager; } diff --git a/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeCookieOptions.cs b/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeCookieOptions.cs index d51db33a55..3b8421ce6a 100644 --- a/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeCookieOptions.cs +++ b/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeCookieOptions.cs @@ -5,20 +5,20 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.Services; -using Umbraco.Net; using Umbraco.Core.Security; +using Umbraco.Core.Services; using Umbraco.Extensions; -using Microsoft.Extensions.DependencyInjection; +using Umbraco.Net; using Umbraco.Web.Common.Security; -using Microsoft.AspNetCore.Routing; namespace Umbraco.Web.BackOffice.Security { @@ -28,8 +28,8 @@ namespace Umbraco.Web.BackOffice.Security public class ConfigureBackOfficeCookieOptions : IConfigureNamedOptions { private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private readonly ISecuritySettings _securitySettings; - private readonly IGlobalSettings _globalSettings; + private readonly SecuritySettings _securitySettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IRuntimeState _runtimeState; private readonly IDataProtectionProvider _dataProtection; @@ -42,8 +42,8 @@ namespace Umbraco.Web.BackOffice.Security public ConfigureBackOfficeCookieOptions( IUmbracoContextAccessor umbracoContextAccessor, - ISecuritySettings securitySettings, - IGlobalSettings globalSettings, + IOptions securitySettings, + IOptions globalSettings, IHostingEnvironment hostingEnvironment, IRuntimeState runtimeState, IDataProtectionProvider dataProtection, @@ -55,8 +55,8 @@ namespace Umbraco.Web.BackOffice.Security LinkGenerator linkGenerator) { _umbracoContextAccessor = umbracoContextAccessor; - _securitySettings = securitySettings; - _globalSettings = globalSettings; + _securitySettings = securitySettings.Value; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _runtimeState = runtimeState; _dataProtection = dataProtection; @@ -230,7 +230,7 @@ namespace Umbraco.Web.BackOffice.Security } /// - /// Ensures the ticket is renewed if the is set to true + /// Ensures the ticket is renewed if the is set to true /// and the current request is for the get user seconds endpoint /// /// diff --git a/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeIdentityOptions.cs b/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeIdentityOptions.cs index 13d608bd9b..31b5de2e43 100644 --- a/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeIdentityOptions.cs +++ b/src/Umbraco.Web.BackOffice/Security/ConfigureBackOfficeIdentityOptions.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.BackOffice.Security { @@ -13,11 +14,11 @@ namespace Umbraco.Web.BackOffice.Security /// public class ConfigureBackOfficeIdentityOptions : IConfigureOptions { - private readonly IUserPasswordConfiguration _userPasswordConfiguration; + private readonly UserPasswordConfigurationSettings _userPasswordConfiguration; - public ConfigureBackOfficeIdentityOptions(IUserPasswordConfiguration userPasswordConfiguration) + public ConfigureBackOfficeIdentityOptions(IOptions userPasswordConfiguration) { - _userPasswordConfiguration = userPasswordConfiguration; + _userPasswordConfiguration = userPasswordConfiguration.Value; } public void Configure(BackOfficeIdentityOptions options) diff --git a/src/Umbraco.Web.BackOffice/Security/PreviewAuthenticationMiddleware.cs b/src/Umbraco.Web.BackOffice/Security/PreviewAuthenticationMiddleware.cs index ff182b9f7b..1854187a2a 100644 --- a/src/Umbraco.Web.BackOffice/Security/PreviewAuthenticationMiddleware.cs +++ b/src/Umbraco.Web.BackOffice/Security/PreviewAuthenticationMiddleware.cs @@ -6,6 +6,7 @@ using System; using System.Threading.Tasks; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Extensions; @@ -16,14 +17,14 @@ namespace Umbraco.Web.BackOffice.Security /// public class PreviewAuthenticationMiddleware : IMiddleware { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; public PreviewAuthenticationMiddleware( - IGlobalSettings globalSettings, + IOptions globalSettings, IHostingEnvironment hostingEnvironment) { - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs index 0cc73af315..44c83e3009 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs @@ -20,6 +20,8 @@ using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Exceptions; using Umbraco.Web.Security; using Umbraco.Web.WebApi; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Trees { @@ -40,7 +42,7 @@ namespace Umbraco.Web.Trees { private readonly UmbracoTreeSearcher _treeSearcher; private readonly ActionCollection _actions; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IMenuItemCollectionFactory _menuItemCollectionFactory; private readonly IWebSecurity _webSecurity; private readonly IContentService _contentService; @@ -49,7 +51,6 @@ namespace Umbraco.Web.Trees private readonly IUserService _userService; private readonly ILocalizationService _localizationService; - public ContentTreeController( ILocalizedTextService localizedTextService, UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, @@ -62,7 +63,7 @@ namespace Umbraco.Web.Trees IDataTypeService dataTypeService, UmbracoTreeSearcher treeSearcher, ActionCollection actions, - IGlobalSettings globalSettings, + IOptions globalSettings, IContentService contentService, IPublicAccessService publicAccessService, ILocalizationService localizationService) @@ -70,7 +71,7 @@ namespace Umbraco.Web.Trees { _treeSearcher = treeSearcher; _actions = actions; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _menuItemCollectionFactory = menuItemCollectionFactory; _webSecurity = webSecurity; _contentService = contentService; diff --git a/src/Umbraco.Web.BackOffice/Umbraco.Web.BackOffice.csproj b/src/Umbraco.Web.BackOffice/Umbraco.Web.BackOffice.csproj index b5ead8896a..a5a32d43b1 100644 --- a/src/Umbraco.Web.BackOffice/Umbraco.Web.BackOffice.csproj +++ b/src/Umbraco.Web.BackOffice/Umbraco.Web.BackOffice.csproj @@ -31,7 +31,6 @@ - diff --git a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs index 39b1d7ff4e..fe991275de 100644 --- a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs +++ b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs @@ -1,13 +1,14 @@ +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.Common.AspNetCore { public class AspNetCoreBackOfficeInfo : IBackOfficeInfo { - public AspNetCoreBackOfficeInfo(IGlobalSettings globalSettings) + public AspNetCoreBackOfficeInfo(IOptionsMonitor globalSettings) { - GetAbsoluteUrl = globalSettings.UmbracoPath; + GetAbsoluteUrl = globalSettings.CurrentValue.UmbracoPath; } public string GetAbsoluteUrl { get; } // TODO make absolute diff --git a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreHostingEnvironment.cs b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreHostingEnvironment.cs index efa1a52ad4..ede121a9f7 100644 --- a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreHostingEnvironment.cs +++ b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreHostingEnvironment.cs @@ -1,19 +1,21 @@ using System; using System.IO; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.Common.AspNetCore { - public class AspNetCoreHostingEnvironment : Umbraco.Core.Hosting.IHostingEnvironment + public class AspNetCoreHostingEnvironment : Core.Hosting.IHostingEnvironment { - private readonly IHostingSettings _hostingSettings; + private IOptionsMonitor _hostingSettings; private readonly IWebHostEnvironment _webHostEnvironment; private string _localTempPath; - public AspNetCoreHostingEnvironment(IHostingSettings hostingSettings, IWebHostEnvironment webHostEnvironment) + public AspNetCoreHostingEnvironment(IOptionsMonitor hostingSettings, IWebHostEnvironment webHostEnvironment) { _hostingSettings = hostingSettings ?? throw new ArgumentNullException(nameof(hostingSettings)); _webHostEnvironment = webHostEnvironment ?? throw new ArgumentNullException(nameof(webHostEnvironment)); @@ -22,12 +24,7 @@ namespace Umbraco.Web.Common.AspNetCore ApplicationId = AppDomain.CurrentDomain.Id.ToString(); ApplicationPhysicalPath = webHostEnvironment.ContentRootPath; - //TODO how to find this, This is a server thing, not application thing. - ApplicationVirtualPath = hostingSettings.ApplicationVirtualPath?.EnsureStartsWith('/') - ?? "/"; - IISVersion = new Version(0, 0); // TODO not necessary IIS - } public bool IsHosted { get; } = true; @@ -36,8 +33,9 @@ namespace Umbraco.Web.Common.AspNetCore public string ApplicationPhysicalPath { get; } public string ApplicationServerAddress { get; } - public string ApplicationVirtualPath { get; } - public bool IsDebugMode => _hostingSettings.DebugMode; + //TODO how to find this, This is a server thing, not application thing. + public string ApplicationVirtualPath => _hostingSettings.CurrentValue.ApplicationVirtualPath?.EnsureStartsWith('/') ?? "/"; + public bool IsDebugMode => _hostingSettings.CurrentValue.Debug; public Version IISVersion { get; } public string LocalTempPath @@ -47,7 +45,7 @@ namespace Umbraco.Web.Common.AspNetCore if (_localTempPath != null) return _localTempPath; - switch (_hostingSettings.LocalTempStorageLocation) + switch (_hostingSettings.CurrentValue.LocalTempStorageLocation) { case LocalTempStorage.AspNetTemp: diff --git a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreRequestAccessor.cs b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreRequestAccessor.cs index d29e58a2bf..985c568a08 100644 --- a/src/Umbraco.Web.Common/AspNetCore/AspNetCoreRequestAccessor.cs +++ b/src/Umbraco.Web.Common/AspNetCore/AspNetCoreRequestAccessor.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Extensions; using Umbraco.Web.Common.Lifetime; @@ -13,18 +15,18 @@ namespace Umbraco.Web.Common.AspNetCore { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly ISet _applicationUrls = new HashSet(); private Uri _currentApplicationUrl; public AspNetCoreRequestAccessor(IHttpContextAccessor httpContextAccessor, IUmbracoRequestLifetime umbracoRequestLifetime, IUmbracoContextAccessor umbracoContextAccessor, - IWebRoutingSettings webRoutingSettings) + IOptions webRoutingSettings) { _httpContextAccessor = httpContextAccessor; _umbracoContextAccessor = umbracoContextAccessor; - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; umbracoRequestLifetime.RequestStart += RequestStart; umbracoRequestLifetime.RequestEnd += RequestEnd; diff --git a/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs b/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs index e72b62b006..fde3d095fe 100644 --- a/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs +++ b/src/Umbraco.Web.Common/AspNetCore/UmbracoViewPage.cs @@ -3,9 +3,10 @@ using System.Text; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; @@ -24,8 +25,8 @@ namespace Umbraco.Web.Common.AspNetCore private IUmbracoContext _umbracoContext; private IUmbracoContextAccessor UmbracoContextAccessor => Context.RequestServices.GetRequiredService(); - private IGlobalSettings GlobalSettings => Context.RequestServices.GetRequiredService(); - private IContentSettings ContentSettings => Context.RequestServices.GetRequiredService(); + private GlobalSettings GlobalSettings => Context.RequestServices.GetRequiredService>().Value; + private ContentSettings ContentSettings => Context.RequestServices.GetRequiredService>().Value; private IProfilerHtml ProfilerHtml => Context.RequestServices.GetRequiredService(); private IIOHelper IOHelper => Context.RequestServices.GetRequiredService(); diff --git a/src/Umbraco.Web.Common/Builder/UmbracoBuilderExtensions.cs b/src/Umbraco.Web.Common/Builder/UmbracoBuilderExtensions.cs index dd91a2cca9..08b7670522 100644 --- a/src/Umbraco.Web.Common/Builder/UmbracoBuilderExtensions.cs +++ b/src/Umbraco.Web.Common/Builder/UmbracoBuilderExtensions.cs @@ -34,7 +34,7 @@ namespace Umbraco.Web.Common.Builder { options.ShouldProfile = request => false; // WebProfiler determine and start profiling. We should not use the MiniProfilerMiddleware to also profile })); - + public static IUmbracoBuilder WithMvcAndRazor(this IUmbracoBuilder builder, Action mvcOptions = null, Action mvcBuilding = null) => builder.AddWith(nameof(WithMvcAndRazor), () => { diff --git a/src/Umbraco.Web.Common/Extensions/HttpRequestExtensions.cs b/src/Umbraco.Web.Common/Extensions/HttpRequestExtensions.cs index 5baedf3ded..0369717b9b 100644 --- a/src/Umbraco.Web.Common/Extensions/HttpRequestExtensions.cs +++ b/src/Umbraco.Web.Common/Extensions/HttpRequestExtensions.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; namespace Umbraco.Extensions @@ -24,7 +25,7 @@ namespace Umbraco.Extensions return request.Cookies.TryGetValue(Constants.Web.PreviewCookieName, out var cookieVal) && !cookieVal.IsNullOrWhiteSpace(); } - public static bool IsBackOfficeRequest(this HttpRequest request, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static bool IsBackOfficeRequest(this HttpRequest request, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { return new Uri(request.GetEncodedUrl(), UriKind.RelativeOrAbsolute).IsBackOfficeRequest(globalSettings, hostingEnvironment); } diff --git a/src/Umbraco.Web.Common/Extensions/UmbracoCoreServiceCollectionExtensions.cs b/src/Umbraco.Web.Common/Extensions/UmbracoCoreServiceCollectionExtensions.cs index d0f47a0da9..815a413cb0 100644 --- a/src/Umbraco.Web.Common/Extensions/UmbracoCoreServiceCollectionExtensions.cs +++ b/src/Umbraco.Web.Common/Extensions/UmbracoCoreServiceCollectionExtensions.cs @@ -1,26 +1,24 @@ using System; using System.Data.Common; using System.Data.SqlClient; -using System.Globalization; using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.InteropServices; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Serilog; using Serilog.Extensions.Hosting; using Serilog.Extensions.Logging; using Umbraco.Composing; -using Umbraco.Configuration; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Logging.Serilog; @@ -28,14 +26,14 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Runtime; using Umbraco.Web.Common.AspNetCore; -using Umbraco.Web.Common.Extensions; using Umbraco.Web.Common.Profiler; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; +using CoreDebugSettings = Umbraco.Core.Configuration.Models.CoreDebugSettings; +using IHostingEnvironment = Umbraco.Core.Hosting.IHostingEnvironment; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Umbraco.Extensions { - - public static class UmbracoCoreServiceCollectionExtensions { /// @@ -97,6 +95,28 @@ namespace Umbraco.Extensions return services; } + /// + /// Adds the Umbraco Back Core requirements + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static IServiceCollection AddUmbracoCore( + this IServiceCollection services, + IWebHostEnvironment webHostEnvironment, + IRegister umbContainer, + Assembly entryAssembly, + AppCaches appCaches, + ILoggingConfiguration loggingConfiguration, + out IFactory factory) + => services.AddUmbracoCore(webHostEnvironment, umbContainer, entryAssembly, appCaches, loggingConfiguration, GetCoreRuntime, out factory); + /// /// Adds the Umbraco Configuration requirements /// @@ -107,11 +127,29 @@ namespace Umbraco.Extensions { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); - var configsFactory = new AspNetCoreConfigsFactory(configuration); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "ActiveDirectory")); + services.Configure(configuration.GetSection("ConnectionStrings"), o => o.BindNonPublicProperties = true); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Content")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Core:Debug")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "ExceptionFilter")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Global")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "HealthChecks")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Hosting")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Imaging")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Examine")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "KeepAlive")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Logging")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigSecurityPrefix + "MemberPassword")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigGlobalPrefix + "ModelsBuilder")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "NuCache")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "RequestHandler")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Runtime")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Security")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "Tours")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "TypeFinder")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigSecurityPrefix + "UserPassword")); + services.Configure(configuration.GetSection(Constants.Configuration.ConfigPrefix + "WebRouting")); - var configs = configsFactory.Create(); - - services.AddSingleton(configs); return services; } @@ -160,6 +198,7 @@ namespace Umbraco.Extensions Assembly.GetEntryAssembly(), appCaches, loggingConfig, + GetCoreRuntime, out factory); return services; @@ -172,30 +211,7 @@ namespace Umbraco.Extensions /// /// /// - /// - /// - /// - /// - /// - public static IServiceCollection AddUmbracoCore( - this IServiceCollection services, - IWebHostEnvironment webHostEnvironment, - IRegister umbContainer, - Assembly entryAssembly, - AppCaches appCaches, - ILoggingConfiguration loggingConfiguration, - out IFactory factory) - => services.AddUmbracoCore(webHostEnvironment, umbContainer, entryAssembly, appCaches, loggingConfiguration, GetCoreRuntime, out factory); - - - /// - /// Adds the Umbraco Back Core requirements - /// - /// - /// - /// - /// - /// + /// /// /// /// Delegate to create an @@ -206,10 +222,10 @@ namespace Umbraco.Extensions IWebHostEnvironment webHostEnvironment, IRegister umbContainer, Assembly entryAssembly, - AppCaches appCaches, + AppCaches appCaches, ILoggingConfiguration loggingConfiguration, - // TODO: Yep that's extremely ugly - Func getRuntime, + //TODO: Yep that's extremely ugly + Func getRuntime, out IFactory factory) { if (services is null) throw new ArgumentNullException(nameof(services)); @@ -237,22 +253,28 @@ namespace Umbraco.Extensions // `RegisterEssentials`. var serviceProvider = services.BuildServiceProvider(); - var configs = serviceProvider.GetService(); + var globalSettings = serviceProvider.GetService>(); + var connectionStrings = serviceProvider.GetService>(); + var hostingSettings = serviceProvider.GetService>(); + var typeFinderSettings = serviceProvider.GetService>(); + var loggerFactory = serviceProvider.GetService(); + var dbProviderFactoryCreator = serviceProvider.GetRequiredService(); CreateCompositionRoot(services, - configs, + globalSettings, + hostingSettings, webHostEnvironment, loggingConfiguration, out var logger, out var ioHelper, out var hostingEnvironment, out var backOfficeInfo, out var profiler); - var globalSettings = configs.Global(); - var umbracoVersion = new UmbracoVersion(globalSettings); - var typeFinder = CreateTypeFinder(Current.LoggerFactory, profiler, webHostEnvironment, entryAssembly, configs.TypeFinder()); + var umbracoVersion = new UmbracoVersion(); + var typeFinder = CreateTypeFinder(Current.LoggerFactory, profiler, webHostEnvironment, entryAssembly, typeFinderSettings); - var runtime = getRuntime( - configs, + var coreRuntime = getRuntime( + globalSettings.CurrentValue, + connectionStrings.Value, umbracoVersion, ioHelper, logger, @@ -264,12 +286,12 @@ namespace Umbraco.Extensions appCaches, dbProviderFactoryCreator); - factory = runtime.Configure(container); + factory = coreRuntime.Configure(container); return services; } - private static ITypeFinder CreateTypeFinder(ILoggerFactory loggerFactory, IProfiler profiler, IWebHostEnvironment webHostEnvironment, Assembly entryAssembly, ITypeFinderSettings typeFinderSettings) + private static ITypeFinder CreateTypeFinder(ILoggerFactory loggerFactory, IProfiler profiler, IWebHostEnvironment webHostEnvironment, Assembly entryAssembly, IOptionsMonitor typeFinderSettings) { var runtimeHashPaths = new RuntimeHashPaths(); runtimeHashPaths.AddFolder(new DirectoryInfo(Path.Combine(webHostEnvironment.ContentRootPath, "bin"))); @@ -278,25 +300,23 @@ namespace Umbraco.Extensions } private static IRuntime GetCoreRuntime( - Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, - IProfiler profiler, Core.Hosting.IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo, + GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, + IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo, ITypeFinder typeFinder, AppCaches appCaches, IDbProviderFactoryCreator dbProviderFactoryCreator) { - // Determine if we should use the sql main dom or the default - var globalSettings = configs.Global(); - var connStrings = configs.ConnectionStrings(); var appSettingMainDomLock = globalSettings.MainDomLock; var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var mainDomLock = appSettingMainDomLock == "SqlMainDomLock" || isWindows == false - ? (IMainDomLock)new SqlMainDomLock(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connStrings, dbProviderFactoryCreator, hostingEnvironment) + ? (IMainDomLock)new SqlMainDomLock(loggerFactory.CreateLogger(), loggerFactory, globalSettings, connectionStrings, dbProviderFactoryCreator, hostingEnvironment) : new MainDomSemaphoreLock(loggerFactory.CreateLogger(), hostingEnvironment); var mainDom = new MainDom(loggerFactory.CreateLogger(), mainDomLock); var coreRuntime = new CoreRuntime( - configs, + globalSettings, + connectionStrings, umbracoVersion, ioHelper, logger, @@ -315,7 +335,8 @@ namespace Umbraco.Extensions private static IServiceCollection CreateCompositionRoot( IServiceCollection services, - Configs configs, + IOptionsMonitor globalSettings, + IOptionsMonitor hostingSettings, IWebHostEnvironment webHostEnvironment, ILoggingConfiguration loggingConfiguration, out ILogger logger, @@ -324,11 +345,8 @@ namespace Umbraco.Extensions out IBackOfficeInfo backOfficeInfo, out IProfiler profiler) { - if (configs == null) - throw new InvalidOperationException($"Could not resolve type {typeof(Configs)} from the container, ensure {nameof(AddUmbracoConfiguration)} is called before calling {nameof(AddUmbracoCore)}"); - - var hostingSettings = configs.Hosting(); - var globalSettings = configs.Global(); + if (globalSettings == null) + throw new InvalidOperationException($"Could not resolve type {typeof(GlobalSettings)} from the container, ensure {nameof(AddUmbracoConfiguration)} is called before calling {nameof(AddUmbracoCore)}"); hostingEnvironment = new AspNetCoreHostingEnvironment(hostingSettings, webHostEnvironment); ioHelper = new IOHelper(hostingEnvironment); diff --git a/src/Umbraco.Web.Common/Extensions/UmbracoWebServiceCollectionExtensions.cs b/src/Umbraco.Web.Common/Extensions/UmbracoWebServiceCollectionExtensions.cs index a795edf6cf..394a15e1d4 100644 --- a/src/Umbraco.Web.Common/Extensions/UmbracoWebServiceCollectionExtensions.cs +++ b/src/Umbraco.Web.Common/Extensions/UmbracoWebServiceCollectionExtensions.cs @@ -19,6 +19,7 @@ using Smidge; using Smidge.Nuglify; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Common.ApplicationModels; using Umbraco.Web.Common.Middleware; using Umbraco.Web.Common.ModelBinding; @@ -40,8 +41,7 @@ namespace Umbraco.Extensions // TODO: We need to avoid this, surely there's a way? See ContainerTests.BuildServiceProvider_Before_Host_Is_Configured var serviceProvider = services.BuildServiceProvider(); - var configs = serviceProvider.GetService(); - var imagingSettings = configs.Imaging(); + var imagingSettings = serviceProvider.GetService>().Value; services.AddUmbracoImageSharp(imagingSettings); return services; @@ -53,19 +53,19 @@ namespace Umbraco.Extensions /// /// /// - public static IServiceCollection AddUmbracoImageSharp(this IServiceCollection services, IImagingSettings imagingSettings) + public static IServiceCollection AddUmbracoImageSharp(this IServiceCollection services, ImagingSettings imagingSettings) { services.AddImageSharpCore( options => { options.Configuration = SixLabors.ImageSharp.Configuration.Default; - options.MaxBrowserCacheDays = imagingSettings.MaxBrowserCacheDays; - options.MaxCacheDays = imagingSettings.MaxCacheDays; - options.CachedNameLength = imagingSettings.CachedNameLength; + options.MaxBrowserCacheDays = imagingSettings.Cache.MaxBrowserCacheDays; + options.MaxCacheDays = imagingSettings.Cache.MaxCacheDays; + options.CachedNameLength = imagingSettings.Cache.CachedNameLength; options.OnParseCommands = context => { - RemoveIntParamenterIfValueGreatherThen(context.Commands, ResizeWebProcessor.Width, imagingSettings.MaxResizeWidth); - RemoveIntParamenterIfValueGreatherThen(context.Commands, ResizeWebProcessor.Height, imagingSettings.MaxResizeHeight); + RemoveIntParamenterIfValueGreatherThen(context.Commands, ResizeWebProcessor.Width, imagingSettings.Resize.MaxWidth); + RemoveIntParamenterIfValueGreatherThen(context.Commands, ResizeWebProcessor.Height, imagingSettings.Resize.MaxHeight); }; options.OnBeforeSave = _ => { }; options.OnProcessed = _ => { }; @@ -75,7 +75,7 @@ namespace Umbraco.Extensions .SetMemoryAllocator(provider => ArrayPoolMemoryAllocator.CreateWithMinimalPooling()) .Configure(options => { - options.CacheFolder = imagingSettings.CacheFolder; + options.CacheFolder = imagingSettings.Cache.CacheFolder; }) .SetCache() .SetCacheHash() diff --git a/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs b/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs index 46bfd6cdfa..6a5f6eaa47 100644 --- a/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs +++ b/src/Umbraco.Web.Common/Filters/HttpResponseExceptionFilter.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using Umbraco.Core.Exceptions; using Umbraco.Web.Common.Exceptions; namespace Umbraco.Web.Common.Filters diff --git a/src/Umbraco.Web.Common/Filters/JsonExceptionFilterAttribute.cs b/src/Umbraco.Web.Common/Filters/JsonExceptionFilterAttribute.cs index 1ff8ede0ab..3d25016c15 100644 --- a/src/Umbraco.Web.Common/Filters/JsonExceptionFilterAttribute.cs +++ b/src/Umbraco.Web.Common/Filters/JsonExceptionFilterAttribute.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Common.Filters public void OnException(ExceptionContext filterContext) { - if (filterContext.Exception != null) + if (filterContext.Exception != null && !filterContext.ExceptionHandled) { filterContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError; diff --git a/src/Umbraco.Web.Common/Filters/ModelBindingExceptionFilter.cs b/src/Umbraco.Web.Common/Filters/ModelBindingExceptionFilter.cs index 559a02e149..3c1de1e138 100644 --- a/src/Umbraco.Web.Common/Filters/ModelBindingExceptionFilter.cs +++ b/src/Umbraco.Web.Common/Filters/ModelBindingExceptionFilter.cs @@ -4,8 +4,9 @@ using System.Text.RegularExpressions; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Common.ModelBinders; @@ -22,12 +23,12 @@ namespace Umbraco.Web.Common.Filters { private static readonly Regex _getPublishedModelsTypesRegex = new Regex("Umbraco.Web.PublishedModels.(\\w+)", RegexOptions.Compiled); - private readonly IExceptionFilterSettings _exceptionFilterSettings; + private readonly ExceptionFilterSettings _exceptionFilterSettings; private readonly IPublishedModelFactory _publishedModelFactory; - public ModelBindingExceptionFilter(IExceptionFilterSettings exceptionFilterSettings, IPublishedModelFactory publishedModelFactory) + public ModelBindingExceptionFilter(IOptions exceptionFilterSettings, IPublishedModelFactory publishedModelFactory) { - _exceptionFilterSettings = exceptionFilterSettings; + _exceptionFilterSettings = exceptionFilterSettings.Value; _publishedModelFactory = publishedModelFactory ?? throw new ArgumentNullException(nameof(publishedModelFactory)); } diff --git a/src/Umbraco.Web.Common/Filters/StatusCodeResultAttribute.cs b/src/Umbraco.Web.Common/Filters/StatusCodeResultAttribute.cs index 8f3fcf3a95..fe941e89d5 100644 --- a/src/Umbraco.Web.Common/Filters/StatusCodeResultAttribute.cs +++ b/src/Umbraco.Web.Common/Filters/StatusCodeResultAttribute.cs @@ -2,6 +2,8 @@ using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; namespace Umbraco.Web.Common.Filters @@ -26,7 +28,7 @@ namespace Umbraco.Web.Common.Filters httpContext.Response.StatusCode = (int)_statusCode; - var disableIisCustomErrors = httpContext.RequestServices.GetService().TrySkipIisCustomErrors; + var disableIisCustomErrors = httpContext.RequestServices.GetService>().Value.TrySkipIisCustomErrors; var statusCodePagesFeature = httpContext.Features.Get(); if (statusCodePagesFeature != null) diff --git a/src/Umbraco.Web.Common/Install/InstallController.cs b/src/Umbraco.Web.Common/Install/InstallController.cs index 7840a1097b..a8f1801795 100644 --- a/src/Umbraco.Web.Common/Install/InstallController.cs +++ b/src/Umbraco.Web.Common/Install/InstallController.cs @@ -12,6 +12,8 @@ using Umbraco.Extensions; using Umbraco.Web.Common.Filters; using Umbraco.Web.Install; using Umbraco.Web.Security; +using Umbraco.Core.Configuration.Models; +using Microsoft.Extensions.Options; namespace Umbraco.Web.Common.Install { @@ -26,7 +28,7 @@ namespace Umbraco.Web.Common.Install private readonly IWebSecurity _webSecurity; private readonly InstallHelper _installHelper; private readonly IRuntimeState _runtime; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IUmbracoVersion _umbracoVersion; private readonly ILogger _logger; @@ -37,7 +39,7 @@ namespace Umbraco.Web.Common.Install IWebSecurity webSecurity, InstallHelper installHelper, IRuntimeState runtime, - IGlobalSettings globalSettings, + IOptions globalSettings, IRuntimeMinifier runtimeMinifier, IHostingEnvironment hostingEnvironment, IUmbracoVersion umbracoVersion, @@ -47,7 +49,7 @@ namespace Umbraco.Web.Common.Install _webSecurity = webSecurity; _installHelper = installHelper; _runtime = runtime; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _runtimeMinifier = runtimeMinifier; _hostingEnvironment = hostingEnvironment; _umbracoVersion = umbracoVersion; diff --git a/src/Umbraco.Web.Common/Macros/MacroRenderer.cs b/src/Umbraco.Web.Common/Macros/MacroRenderer.cs index 74d8e7726d..d0474e0d29 100644 --- a/src/Umbraco.Web.Common/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web.Common/Macros/MacroRenderer.cs @@ -4,9 +4,10 @@ using System.IO; using System.Linq; using System.Text; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -23,7 +24,7 @@ namespace Umbraco.Web.Macros private readonly IProfilingLogger _plogger; private readonly ILogger _logger; private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly ILocalizedTextService _textService; private readonly AppCaches _appCaches; private readonly IMacroService _macroService; @@ -34,12 +35,11 @@ namespace Umbraco.Web.Macros private readonly IRequestAccessor _requestAccessor; private readonly IHttpContextAccessor _httpContextAccessor; - public MacroRenderer( IProfilingLogger plogger, ILogger logger, IUmbracoContextAccessor umbracoContextAccessor, - IContentSettings contentSettings, + IOptions contentSettings, ILocalizedTextService textService, AppCaches appCaches, IMacroService macroService, @@ -53,7 +53,7 @@ namespace Umbraco.Web.Macros _plogger = plogger ?? throw new ArgumentNullException(nameof(plogger)); _logger = logger; _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _textService = textService; _appCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches)); _macroService = macroService ?? throw new ArgumentNullException(nameof(macroService)); @@ -293,7 +293,7 @@ namespace Umbraco.Web.Macros Alias = macro.Alias, MacroSource = macro.MacroSource, Exception = e, - Behaviour = _contentSettings.MacroErrorBehaviour + Behaviour = _contentSettings.MacroErrors }; switch (macroErrorEventArgs.Behaviour) diff --git a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs b/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs index 959c4c27a2..67755da5ea 100644 --- a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs +++ b/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs @@ -1,29 +1,30 @@ +using System.Linq; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; +using Umbraco.Core.Diagnostics; using Umbraco.Core.Hosting; -using Umbraco.Net; +using Umbraco.Core.Logging; using Umbraco.Core.Runtime; using Umbraco.Core.Security; +using Umbraco.Extensions; +using Umbraco.Net; using Umbraco.Web.Common.AspNetCore; +using Umbraco.Web.Common.Controllers; using Umbraco.Web.Common.Formatters; +using Umbraco.Web.Common.Install; using Umbraco.Web.Common.Lifetime; using Umbraco.Web.Common.Macros; -using Umbraco.Web.Composing.CompositionExtensions; -using Umbraco.Web.Macros; -using Umbraco.Core.Diagnostics; -using Umbraco.Core.Logging; -using Umbraco.Web.Common.Profiler; -using Umbraco.Web.Common.Install; -using Umbraco.Extensions; -using System.Linq; -using Umbraco.Core.Configuration; -using Umbraco.Web.Common.Controllers; using Umbraco.Web.Common.Middleware; using Umbraco.Web.Common.ModelBinding; +using Umbraco.Web.Common.Profiler; using Umbraco.Web.Common.Routing; -using Umbraco.Web.Common.Templates; using Umbraco.Web.Common.Security; +using Umbraco.Web.Common.Templates; +using Umbraco.Web.Composing.CompositionExtensions; +using Umbraco.Web.Macros; using Umbraco.Web.Security; using Umbraco.Web.Templates; @@ -96,7 +97,7 @@ namespace Umbraco.Web.Common.Runtime composition.RegisterUnique(); composition.RegisterUnique(); - composition.RegisterUnique(factory => new LegacyPasswordSecurity(factory.GetInstance())); + composition.RegisterUnique(factory => new LegacyPasswordSecurity(factory.GetInstance>().Value)); } diff --git a/src/Umbraco.Web.Common/Security/WebSecurity.cs b/src/Umbraco.Web.Common/Security/WebSecurity.cs index c67d5a9b4f..b822adf656 100644 --- a/src/Umbraco.Web.Common/Security/WebSecurity.cs +++ b/src/Umbraco.Web.Common/Security/WebSecurity.cs @@ -1,33 +1,33 @@ using System; using System.Security; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; +using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Extensions; using Umbraco.Web.Security; -using Umbraco.Core.Models; namespace Umbraco.Web.Common.Security { - public class WebSecurity : IWebSecurity { private readonly IUserService _userService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; public WebSecurity( IUserService userService, - IGlobalSettings globalSettings, + IOptions globalSettings, IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor) { _userService = userService; - _globalSettings = globalSettings; + _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _httpContextAccessor = httpContextAccessor; } @@ -113,7 +113,7 @@ namespace Umbraco.Web.Common.Security return ValidateRequestAttempt.Success; } - private static bool RequestIsInUmbracoApplication(IHttpContextAccessor httpContextAccessor, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + private static bool RequestIsInUmbracoApplication(IHttpContextAccessor httpContextAccessor, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { return httpContextAccessor.GetRequiredHttpContext().Request.Path.ToString().IndexOf(hostingEnvironment.ToAbsolute(globalSettings.UmbracoPath), StringComparison.InvariantCultureIgnoreCase) > -1; } diff --git a/src/Umbraco.Web.Common/Templates/TemplateRenderer.cs b/src/Umbraco.Web.Common/Templates/TemplateRenderer.cs index d692303df5..1bec3cf41c 100644 --- a/src/Umbraco.Web.Common/Templates/TemplateRenderer.cs +++ b/src/Umbraco.Web.Common/Templates/TemplateRenderer.cs @@ -11,7 +11,9 @@ using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Services; using Umbraco.Core.Strings; @@ -34,7 +36,7 @@ namespace Umbraco.Web.Common.Templates private readonly IPublishedRouter _publishedRouter; private readonly IFileService _fileService; private readonly ILocalizationService _languageService; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly IShortStringHelper _shortStringHelper; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ICompositeViewEngine _viewEngine; @@ -43,7 +45,7 @@ namespace Umbraco.Web.Common.Templates IPublishedRouter publishedRouter, IFileService fileService, ILocalizationService textService, - IWebRoutingSettings webRoutingSettings, + IOptions webRoutingSettings, IShortStringHelper shortStringHelper, IHttpContextAccessor httpContextAccessor, ICompositeViewEngine viewEngine) @@ -52,7 +54,7 @@ namespace Umbraco.Web.Common.Templates _publishedRouter = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter)); _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService)); _languageService = textService ?? throw new ArgumentNullException(nameof(textService)); - _webRoutingSettings = webRoutingSettings ?? throw new ArgumentNullException(nameof(webRoutingSettings)); + _webRoutingSettings = webRoutingSettings.Value ?? throw new ArgumentNullException(nameof(webRoutingSettings)); _shortStringHelper = shortStringHelper ?? throw new ArgumentNullException(nameof(shortStringHelper)); _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); _viewEngine = viewEngine ?? throw new ArgumentNullException(nameof(viewEngine)); diff --git a/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj b/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj index 7b8cda5e10..57181f908c 100644 --- a/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj +++ b/src/Umbraco.Web.Common/Umbraco.Web.Common.csproj @@ -15,7 +15,6 @@ - @@ -36,5 +35,5 @@ <_Parameter1>Umbraco.Tests.UnitTests - + diff --git a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs index 4419015105..b255013b7f 100644 --- a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs +++ b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs @@ -1,7 +1,9 @@ using System; +using Microsoft.Extensions.Options; using Umbraco.Composing; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.PublishedCache; @@ -15,7 +17,7 @@ namespace Umbraco.Web /// public class UmbracoContext : DisposableObjectSlim, IDisposeOnRequestEnd, IUmbracoContext { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly ICookieManager _cookieManager; private readonly IRequestAccessor _requestAccessor; @@ -30,7 +32,7 @@ namespace Umbraco.Web internal UmbracoContext( IPublishedSnapshotService publishedSnapshotService, IWebSecurity webSecurity, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IVariationContextAccessor variationContextAccessor, UriUtility uriUtility, diff --git a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs index 3c771a1668..d9df11e4a9 100644 --- a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs +++ b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs @@ -2,7 +2,9 @@ using System.IO; using System.Text; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -22,7 +24,7 @@ namespace Umbraco.Web private readonly IVariationContextAccessor _variationContextAccessor; private readonly IDefaultCultureAccessor _defaultCultureAccessor; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IUserService _userService; private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; @@ -39,7 +41,7 @@ namespace Umbraco.Web IPublishedSnapshotService publishedSnapshotService, IVariationContextAccessor variationContextAccessor, IDefaultCultureAccessor defaultCultureAccessor, - IGlobalSettings globalSettings, + IOptions globalSettings, IUserService userService, IHostingEnvironment hostingEnvironment, UriUtility uriUtility, @@ -52,7 +54,7 @@ namespace Umbraco.Web _publishedSnapshotService = publishedSnapshotService ?? throw new ArgumentNullException(nameof(publishedSnapshotService)); _variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor)); _defaultCultureAccessor = defaultCultureAccessor ?? throw new ArgumentNullException(nameof(defaultCultureAccessor)); - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); + _globalSettings = globalSettings.Value ?? throw new ArgumentNullException(nameof(globalSettings)); _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); _uriUtility = uriUtility ?? throw new ArgumentNullException(nameof(uriUtility)); diff --git a/src/Umbraco.Web.UI.NetCore/Startup.cs b/src/Umbraco.Web.UI.NetCore/Startup.cs index 72e0d792f3..aa141b2624 100644 --- a/src/Umbraco.Web.UI.NetCore/Startup.cs +++ b/src/Umbraco.Web.UI.NetCore/Startup.cs @@ -34,6 +34,7 @@ namespace Umbraco.Web.UI.NetCore { var umbracoBuilder = services.AddUmbraco(_env, _config); umbracoBuilder.BuildWithAllBackOfficeComponents(); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/src/Umbraco.Web.UI.NetCore/Umbraco.Web.UI.NetCore.csproj b/src/Umbraco.Web.UI.NetCore/Umbraco.Web.UI.NetCore.csproj index 2479880d16..39937d1f3a 100644 --- a/src/Umbraco.Web.UI.NetCore/Umbraco.Web.UI.NetCore.csproj +++ b/src/Umbraco.Web.UI.NetCore/Umbraco.Web.UI.NetCore.csproj @@ -18,7 +18,7 @@ - + diff --git a/src/Umbraco.Web.UI.NetCore/appsettings.json b/src/Umbraco.Web.UI.NetCore/appsettings.json index 3bbb4e7da4..1eb761e1ad 100644 --- a/src/Umbraco.Web.UI.NetCore/appsettings.json +++ b/src/Umbraco.Web.UI.NetCore/appsettings.json @@ -13,7 +13,7 @@ "Global": { "DefaultUILanguage": "en-us", "HideTopLevelNodeFromPath": true, - "Path": "~/umbraco", + "UmbracoPath": "~/umbraco", "TimeOutInMinutes": 20, "UseHttps": false }, diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/AuthorizeUpgrade.cshtml b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/AuthorizeUpgrade.cshtml index d9f39b544c..dc47195a18 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/AuthorizeUpgrade.cshtml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/AuthorizeUpgrade.cshtml @@ -1,21 +1,22 @@ -@using Umbraco.Core +@using Microsoft.Extensions.Options; +@using Umbraco.Core @using Umbraco.Web.WebAssets @using Umbraco.Web.Common.Security @using Umbraco.Core.WebAssets @using Umbraco.Core.Configuration +@using Umbraco.Core.Configuration.Models @using Umbraco.Core.Hosting @using Umbraco.Extensions -@using Umbraco.Core.Logging @using Umbraco.Web.BackOffice.Controllers @inject BackOfficeSignInManager signInManager @inject BackOfficeServerVariables backOfficeServerVariables @inject IUmbracoVersion umbracoVersion @inject IHostingEnvironment hostingEnvironment -@inject IGlobalSettings globalSettings +@inject IOptions globalSettings @inject IRuntimeMinifier runtimeMinifier @{ - var backOfficePath = globalSettings.GetBackOfficePath(hostingEnvironment); + var backOfficePath = globalSettings.Value.GetBackOfficePath(hostingEnvironment); } diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Default.cshtml b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Default.cshtml index c71957e77d..41cd42b037 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Default.cshtml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Default.cshtml @@ -1,8 +1,10 @@ -@using Umbraco.Core +@using Microsoft.Extensions.Options; +@using Umbraco.Core @using Umbraco.Web.WebAssets @using Umbraco.Web.Common.Security @using Umbraco.Core.WebAssets @using Umbraco.Core.Configuration +@using Umbraco.Core.Configuration.Models @using Umbraco.Core.Hosting @using Umbraco.Extensions @using Umbraco.Core.Logging @@ -11,13 +13,13 @@ @inject BackOfficeServerVariables backOfficeServerVariables @inject IUmbracoVersion umbracoVersion @inject IHostingEnvironment hostingEnvironment -@inject IGlobalSettings globalSettings +@inject IOptions globalSettings @inject IRuntimeMinifier runtimeMinifier @inject IProfilerHtml profilerHtml @{ bool.TryParse(Context.Request.Query["umbDebug"], out bool isDebug); - var backOfficePath = globalSettings.GetBackOfficePath(hostingEnvironment); + var backOfficePath = globalSettings.Value.GetBackOfficePath(hostingEnvironment); } diff --git a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Preview.cshtml b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Preview.cshtml index 3bab021741..212d6bddee 100644 --- a/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Preview.cshtml +++ b/src/Umbraco.Web.UI.NetCore/umbraco/UmbracoBackOffice/Preview.cshtml @@ -1,8 +1,9 @@ -@using Umbraco.Core +@using Microsoft.Extensions.Options; @using Umbraco.Web.WebAssets @using Umbraco.Web.Common.Security @using Umbraco.Core.WebAssets @using Umbraco.Core.Configuration +@using Umbraco.Core.Configuration.Models @using Umbraco.Core.Hosting @using Umbraco.Extensions @using Umbraco.Core.Logging @@ -11,7 +12,7 @@ @inject BackOfficeServerVariables backOfficeServerVariables @inject IUmbracoVersion umbracoVersion @inject IHostingEnvironment hostingEnvironment -@inject IGlobalSettings globalSettings +@inject IOptions globalSettings @inject IRuntimeMinifier runtimeMinifier @inject IProfilerHtml profilerHtml diff --git a/src/Umbraco.Web/AppBuilderExtensions.cs b/src/Umbraco.Web/AppBuilderExtensions.cs index c8c6cbdf5c..f4766bc414 100644 --- a/src/Umbraco.Web/AppBuilderExtensions.cs +++ b/src/Umbraco.Web/AppBuilderExtensions.cs @@ -3,9 +3,8 @@ using Microsoft.AspNet.SignalR; using Microsoft.Owin.Logging; using Owin; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; -using Umbraco.Web.Composing; using Umbraco.Web.Logging; namespace Umbraco.Web @@ -46,7 +45,7 @@ namespace Umbraco.Web /// The app builder. /// /// - public static IAppBuilder UseSignalR(this IAppBuilder app, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public static IAppBuilder UseSignalR(this IAppBuilder app, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { var umbracoPath = globalSettings.GetUmbracoMvcArea(hostingEnvironment); var signalrPath = HttpRuntime.AppDomainAppVirtualPath + umbracoPath + "/BackOffice/signalr"; diff --git a/src/Umbraco.Web/AspNet/AspNetBackOfficeInfo.cs b/src/Umbraco.Web/AspNet/AspNetBackOfficeInfo.cs index 66578f1517..88fc07c5fa 100644 --- a/src/Umbraco.Web/AspNet/AspNetBackOfficeInfo.cs +++ b/src/Umbraco.Web/AspNet/AspNetBackOfficeInfo.cs @@ -1,6 +1,8 @@ using System.Web; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Microsoft.Extensions.Logging; @@ -9,17 +11,17 @@ namespace Umbraco.Web { public class AspNetBackOfficeInfo : IBackOfficeInfo { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; private readonly ILogger _logger; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; - public AspNetBackOfficeInfo(IGlobalSettings globalSettings, IIOHelper ioHelper, ILogger logger, IWebRoutingSettings webRoutingSettings) + public AspNetBackOfficeInfo(GlobalSettings globalSettings, IIOHelper ioHelper, ILogger logger, IOptions webRoutingSettings) { _globalSettings = globalSettings; _ioHelper = ioHelper; _logger = logger; - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; } /// diff --git a/src/Umbraco.Web/AspNet/AspNetHostingEnvironment.cs b/src/Umbraco.Web/AspNet/AspNetHostingEnvironment.cs index 5e7324236a..2ec6599939 100644 --- a/src/Umbraco.Web/AspNet/AspNetHostingEnvironment.cs +++ b/src/Umbraco.Web/AspNet/AspNetHostingEnvironment.cs @@ -2,8 +2,10 @@ using System; using System.Reflection; using System.Web; using System.Web.Hosting; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; namespace Umbraco.Web.Hosting @@ -11,18 +13,18 @@ namespace Umbraco.Web.Hosting public class AspNetHostingEnvironment : IHostingEnvironment { - private readonly IHostingSettings _hostingSettings; + private readonly HostingSettings _hostingSettings; private string _localTempPath; - public AspNetHostingEnvironment(IHostingSettings hostingSettings) + public AspNetHostingEnvironment(IOptions hostingSettings) { - _hostingSettings = hostingSettings ?? throw new ArgumentNullException(nameof(hostingSettings)); + _hostingSettings = hostingSettings.Value ?? throw new ArgumentNullException(nameof(hostingSettings)); SiteName = HostingEnvironment.SiteName; ApplicationId = HostingEnvironment.ApplicationID; // when we are not hosted (i.e. unit test or otherwise) we'll need to get the root path from the executing assembly ApplicationPhysicalPath = HostingEnvironment.ApplicationPhysicalPath ?? Assembly.GetExecutingAssembly().GetRootDirectorySafe(); - ApplicationVirtualPath = hostingSettings.ApplicationVirtualPath?.EnsureStartsWith('/') + ApplicationVirtualPath = _hostingSettings.ApplicationVirtualPath?.EnsureStartsWith('/') ?? HostingEnvironment.ApplicationVirtualPath?.EnsureStartsWith("/") ?? "/"; IISVersion = HttpRuntime.IISVersion; @@ -34,7 +36,7 @@ namespace Umbraco.Web.Hosting public string ApplicationVirtualPath { get; } - public bool IsDebugMode => HttpContext.Current?.IsDebuggingEnabled ?? _hostingSettings.DebugMode; + public bool IsDebugMode => HttpContext.Current?.IsDebuggingEnabled ?? _hostingSettings.Debug; /// public bool IsHosted => (HttpContext.Current != null || HostingEnvironment.IsHosted); diff --git a/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs index aa2cba6949..ae38dc2c05 100644 --- a/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs +++ b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using Microsoft.Extensions.Options; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Web.Routing; @@ -8,13 +10,13 @@ namespace Umbraco.Web.AspNet public class AspNetRequestAccessor : IRequestAccessor { private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IWebRoutingSettings _webRoutingSettings; + private readonly WebRoutingSettings _webRoutingSettings; private readonly ISet _applicationUrls = new HashSet(); private Uri _currentApplicationUrl; - public AspNetRequestAccessor(IHttpContextAccessor httpContextAccessor, IWebRoutingSettings webRoutingSettings) + public AspNetRequestAccessor(IHttpContextAccessor httpContextAccessor, IOptions webRoutingSettings) { _httpContextAccessor = httpContextAccessor; - _webRoutingSettings = webRoutingSettings; + _webRoutingSettings = webRoutingSettings.Value; UmbracoModule.EndRequest += OnEndRequest; UmbracoModule.RouteAttempt += OnRouteAttempt; diff --git a/src/Umbraco.Web/Compose/AuditEventsComponent.cs b/src/Umbraco.Web/Compose/AuditEventsComponent.cs index 9842ec21a3..4b5669a33f 100644 --- a/src/Umbraco.Web/Compose/AuditEventsComponent.cs +++ b/src/Umbraco.Web/Compose/AuditEventsComponent.cs @@ -3,15 +3,16 @@ using System.Linq; using System.Text; using System.Threading; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; -using Umbraco.Net; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Extensions; +using Umbraco.Net; + namespace Umbraco.Core.Compose { public sealed class AuditEventsComponent : IComponent @@ -20,9 +21,9 @@ namespace Umbraco.Core.Compose private readonly IUserService _userService; private readonly IEntityService _entityService; private readonly IIpResolver _ipResolver; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public AuditEventsComponent(IAuditService auditService, IUserService userService, IEntityService entityService, IIpResolver ipResolver, IGlobalSettings globalSettings) + public AuditEventsComponent(IAuditService auditService, IUserService userService, IEntityService entityService, IIpResolver ipResolver, GlobalSettings globalSettings) { _auditService = auditService; _userService = userService; @@ -61,7 +62,7 @@ namespace Umbraco.Core.Compose MemberService.Exported -= OnMemberExported; } - public static IUser UnknownUser(IGlobalSettings globalSettings) => new User(globalSettings) { Id = Constants.Security.UnknownUserId, Name = Constants.Security.UnknownUserName, Email = "" }; + public static IUser UnknownUser(GlobalSettings globalSettings) => new User(globalSettings) { Id = Constants.Security.UnknownUserId, Name = Constants.Security.UnknownUserName, Email = "" }; private IUser CurrentPerformingUser { diff --git a/src/Umbraco.Web/Compose/BackOfficeUserAuditEventsComponent.cs b/src/Umbraco.Web/Compose/BackOfficeUserAuditEventsComponent.cs index e4f9679f4c..bfb80924d1 100644 --- a/src/Umbraco.Web/Compose/BackOfficeUserAuditEventsComponent.cs +++ b/src/Umbraco.Web/Compose/BackOfficeUserAuditEventsComponent.cs @@ -3,6 +3,7 @@ using Umbraco.Core; using Umbraco.Core.Compose; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Web.Security; @@ -13,9 +14,9 @@ namespace Umbraco.Web.Compose { private readonly IAuditService _auditService; private readonly IUserService _userService; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public BackOfficeUserAuditEventsComponent(IAuditService auditService, IUserService userService, IGlobalSettings globalSettings) + public BackOfficeUserAuditEventsComponent(IAuditService auditService, IUserService userService, GlobalSettings globalSettings) { _auditService = auditService; _userService = userService; diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 94a76ef850..8b7868cf4a 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -215,8 +215,6 @@ namespace Umbraco.Web.Composing public static TypeLoader TypeLoader => Factory.GetInstance(); - public static Configs Configs => Factory.GetInstance(); - public static UrlSegmentProviderCollection UrlSegmentProviders => Factory.GetInstance(); public static CacheRefresherCollection CacheRefreshers => Factory.GetInstance(); diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index bacd533560..e4d3c043c5 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -10,6 +10,7 @@ using System.Web; using System.Web.Http; using System.Web.Mvc; using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; @@ -21,6 +22,7 @@ using Umbraco.Web.Security; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using IUser = Umbraco.Core.Models.Membership.IUser; @@ -48,13 +50,13 @@ namespace Umbraco.Web.Editors private readonly IHostingEnvironment _hostingEnvironment; private readonly ILogger _logger; private readonly IRuntimeState _runtimeState; - private readonly ISecuritySettings _securitySettings; + private readonly SecuritySettings _securitySettings; private readonly IRequestAccessor _requestAccessor; private readonly IEmailSender _emailSender; public AuthenticationController( IUserPasswordConfiguration passwordConfiguration, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, @@ -64,7 +66,7 @@ namespace Umbraco.Web.Editors ILogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, - ISecuritySettings securitySettings, + IOptions securitySettings, IPublishedUrlProvider publishedUrlProvider, IRequestAccessor requestAccessor, IEmailSender emailSender) @@ -74,7 +76,7 @@ namespace Umbraco.Web.Editors _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); _logger = logger; _runtimeState = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState)); - _securitySettings = securitySettings ?? throw new ArgumentNullException(nameof(securitySettings)); + _securitySettings = securitySettings.Value ?? throw new ArgumentNullException(nameof(securitySettings)); _requestAccessor = requestAccessor ?? throw new ArgumentNullException(nameof(securitySettings)); _emailSender = emailSender; } @@ -114,7 +116,7 @@ namespace Umbraco.Web.Editors /// Used to retrieve the 2FA providers for code submission /// /// - [SetAngularAntiForgeryTokens] + // [SetAngularAntiForgeryTokens] //TODO reintroduce when migrated to netcore public async Task> Get2FAProviders() { var userId = await SignInManager.GetVerifiedUserIdAsync(); @@ -130,7 +132,7 @@ namespace Umbraco.Web.Editors return userFactors; } - [SetAngularAntiForgeryTokens] + // [SetAngularAntiForgeryTokens] //TODO reintroduce when migrated to netcore public async Task PostSend2FACode([FromBody]string provider) { if (provider.IsNullOrWhiteSpace()) @@ -151,7 +153,7 @@ namespace Umbraco.Web.Editors return Ok(); } - [SetAngularAntiForgeryTokens] + // [SetAngularAntiForgeryTokens] //TODO reintroduce when migrated to netcore public async Task PostVerify2FACode(Verify2FACodeModel model) { if (ModelState.IsValid == false) diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 1055a54130..9c27f538c3 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -4,17 +4,18 @@ using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; using Microsoft.Owin.Security; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Web.Mvc; using Umbraco.Core.Services; using Umbraco.Web.Features; using Umbraco.Web.Security; using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; using BackOfficeIdentityUser = Umbraco.Core.BackOffice.BackOfficeIdentityUser; @@ -32,33 +33,33 @@ namespace Umbraco.Web.Editors private BackOfficeOwinUserManager _userManager; private BackOfficeSignInManager _signInManager; private readonly IUmbracoVersion _umbracoVersion; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IRuntimeSettings _runtimeSettings; - private readonly ISecuritySettings _securitySettings; + private readonly RuntimeSettings _runtimeSettings; + private readonly SecuritySettings _securitySettings; public BackOfficeController( UmbracoFeatures features, - IGlobalSettings globalSettings, + IOptions globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger, IUmbracoVersion umbracoVersion, - IContentSettings contentSettings, + IOptions contentSettings, IHostingEnvironment hostingEnvironment, - IRuntimeSettings settings, - ISecuritySettings securitySettings) + IOptions settings, + IOptions securitySettings) : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, logger) { _features = features; _umbracoVersion = umbracoVersion; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value; _hostingEnvironment = hostingEnvironment; - _runtimeSettings = settings; - _securitySettings = securitySettings; + _runtimeSettings = settings.Value; + _securitySettings = securitySettings.Value; } protected BackOfficeSignInManager SignInManager => _signInManager ?? (_signInManager = OwinContext.GetBackOfficeSignInManager()); @@ -140,7 +141,7 @@ namespace Umbraco.Web.Editors if (defaultResponse == null) throw new ArgumentNullException("defaultResponse"); if (externalSignInResponse == null) throw new ArgumentNullException("externalSignInResponse"); - ViewData.SetUmbracoPath(GlobalSettings.GetUmbracoMvcArea(_hostingEnvironment)); + ViewData.SetUmbracoPath(GlobalSettings.Value.GetUmbracoMvcArea(_hostingEnvironment)); //check if there is the TempData with the any token name specified, if so, assign to view bag and render the view if (ViewData.FromTempData(TempData, ViewDataExtensions.TokenExternalSignInError) || @@ -254,8 +255,7 @@ namespace Umbraco.Web.Editors var groups = Services.UserService.GetUserGroupsByAlias(autoLinkOptions.GetDefaultUserGroups(UmbracoContext, loginInfo)); - var autoLinkUser = BackOfficeIdentityUser.CreateNew( - GlobalSettings, + var autoLinkUser = BackOfficeIdentityUser.CreateNew(GlobalSettings.Value, loginInfo.Email, loginInfo.Email, autoLinkOptions.GetDefaultCulture(UmbracoContext, loginInfo)); diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index bdcb93099b..7b2cc04652 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -5,18 +5,17 @@ using System.Linq; using System.Runtime.Serialization; using System.Web; using System.Web.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Web.Features; -using Umbraco.Web.HealthCheck; -using Umbraco.Web.Models.ContentEditing; -using Umbraco.Web.Mvc; -using Umbraco.Web.Trees; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.WebAssets; +using Umbraco.Web.Features; +using Umbraco.Web.Mvc; using Umbraco.Web.Security; +using Umbraco.Web.Trees; +using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Editors { @@ -28,27 +27,27 @@ namespace Umbraco.Web.Editors private readonly UrlHelper _urlHelper; private readonly IRuntimeState _runtimeState; private readonly UmbracoFeatures _features; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IUmbracoVersion _umbracoVersion; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly TreeCollection _treeCollection; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IRuntimeSettings _settings; - private readonly ISecuritySettings _securitySettings; + private readonly RuntimeSettings _settings; + private readonly SecuritySettings _securitySettings; private readonly IRuntimeMinifier _runtimeMinifier; internal BackOfficeServerVariables( UrlHelper urlHelper, IRuntimeState runtimeState, UmbracoFeatures features, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IUmbracoVersion umbracoVersion, - IContentSettings contentSettings, + IOptions contentSettings, TreeCollection treeCollection, IHostingEnvironment hostingEnvironment, - IRuntimeSettings settings, - ISecuritySettings securitySettings, + IOptions settings, + IOptions securitySettings, IRuntimeMinifier runtimeMinifier) { _urlHelper = urlHelper; @@ -56,11 +55,11 @@ namespace Umbraco.Web.Editors _features = features; _globalSettings = globalSettings; _umbracoVersion = umbracoVersion; - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _treeCollection = treeCollection ?? throw new ArgumentNullException(nameof(treeCollection)); _hostingEnvironment = hostingEnvironment; - _settings = settings; - _securitySettings = securitySettings; + _settings = settings.Value; + _securitySettings = securitySettings.Value; _runtimeMinifier = runtimeMinifier; } @@ -148,7 +147,7 @@ namespace Umbraco.Web.Editors {"appPluginsPath", _hostingEnvironment.ToAbsolute(Constants.SystemDirectories.AppPlugins).TrimEnd('/')}, { "imageFileTypes", - string.Join(",", _contentSettings.ImageFileTypes) + string.Join(",", _contentSettings.Imaging.ImageFileTypes) }, { "disallowedUploadFiles", diff --git a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs index 64aba378f4..4cd5a76fa4 100644 --- a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs +++ b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs @@ -1,7 +1,9 @@ using System; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Persistence; @@ -31,7 +33,7 @@ namespace Umbraco.Web.Editors } protected UmbracoAuthorizedJsonController( - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index 5ddd34fbed..eccbe073cb 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -10,6 +10,7 @@ using System.Web.Mvc.Html; using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Web.Mvc; @@ -60,7 +61,7 @@ namespace Umbraco.Web /// /// See: http://issues.umbraco.org/issue/U4-1614 /// - public static MvcHtmlString PreviewBadge(this HtmlHelper helper, IHttpContextAccessor httpContextAccessor, IGlobalSettings globalSettings, IIOHelper ioHelper, IContentSettings contentSettings) + public static MvcHtmlString PreviewBadge(this HtmlHelper helper, IHttpContextAccessor httpContextAccessor, GlobalSettings globalSettings, IIOHelper ioHelper, ContentSettings contentSettings) { if (Current.UmbracoContext.InPreviewMode) { diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index dd705cef57..e185f62bc5 100644 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.IO; @@ -21,7 +23,7 @@ namespace Umbraco.Web.Macros private readonly IProfilingLogger _plogger; private readonly ILogger _logger; private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private readonly IContentSettings _contentSettings; + private readonly ContentSettings _contentSettings; private readonly ILocalizedTextService _textService; private readonly AppCaches _appCaches; private readonly IMacroService _macroService; @@ -37,7 +39,7 @@ namespace Umbraco.Web.Macros IProfilingLogger plogger, ILogger logger, IUmbracoContextAccessor umbracoContextAccessor, - IContentSettings contentSettings, + IOptions contentSettings, ILocalizedTextService textService, AppCaches appCaches, IMacroService macroService, @@ -51,7 +53,7 @@ namespace Umbraco.Web.Macros _plogger = plogger ?? throw new ArgumentNullException(nameof(plogger)); _logger = logger; _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _textService = textService; _appCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches)); _macroService = macroService ?? throw new ArgumentNullException(nameof(macroService)); @@ -291,7 +293,7 @@ namespace Umbraco.Web.Macros Alias = macro.Alias, MacroSource = macro.MacroSource, Exception = e, - Behaviour = _contentSettings.MacroErrorBehaviour + Behaviour = _contentSettings.MacroErrors }; switch (macroErrorEventArgs.Behaviour) diff --git a/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs b/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs index 118c53a7f0..e25ab4a69e 100644 --- a/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs +++ b/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs @@ -6,10 +6,8 @@ using System.Web.Routing; using System.Web.SessionState; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Exceptions; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; -using Umbraco.Web.Composing; using Umbraco.Web.WebApi; namespace Umbraco.Web.Mvc @@ -44,7 +42,7 @@ namespace Umbraco.Web.Mvc /// /// internal static Route RouteControllerPlugin(this AreaRegistration area, - IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, string controllerName, Type controllerType, RouteCollection routes, string controllerSuffixName, string defaultAction, object defaultId, string umbracoTokenValue = "backoffice", diff --git a/src/Umbraco.Web/Mvc/BackOfficeArea.cs b/src/Umbraco.Web/Mvc/BackOfficeArea.cs index 156a896bb5..eeb48c3b38 100644 --- a/src/Umbraco.Web/Mvc/BackOfficeArea.cs +++ b/src/Umbraco.Web/Mvc/BackOfficeArea.cs @@ -1,8 +1,7 @@ using System.Web.Mvc; -using Umbraco.Web.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; using Umbraco.Web.Editors; namespace Umbraco.Web.Mvc @@ -10,10 +9,10 @@ namespace Umbraco.Web.Mvc // TODO: This has been ported to netcore, can be removed internal class BackOfficeArea : AreaRegistration { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; - public BackOfficeArea(IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) + public BackOfficeArea(GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { _globalSettings = globalSettings; _hostingEnvironment = hostingEnvironment; diff --git a/src/Umbraco.Web/Mvc/ModelBindingExceptionFilter.cs b/src/Umbraco.Web/Mvc/ModelBindingExceptionFilter.cs index 60ca151ce6..b189867a89 100644 --- a/src/Umbraco.Web/Mvc/ModelBindingExceptionFilter.cs +++ b/src/Umbraco.Web/Mvc/ModelBindingExceptionFilter.cs @@ -3,8 +3,10 @@ using System.Configuration; using System.Net; using System.Text.RegularExpressions; using System.Web.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core.Configuration; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Web.Composing; namespace Umbraco.Web.Mvc @@ -23,7 +25,7 @@ namespace Umbraco.Web.Mvc public void OnException(ExceptionContext filterContext) { - var settings = Current.Factory.GetInstance(); + var settings = Current.Factory.GetInstance>().Value; var disabled = settings?.Disabled ?? false; if (Current.PublishedModelFactory.IsLiveFactory() && !disabled diff --git a/src/Umbraco.Web/Mvc/PluginControllerArea.cs b/src/Umbraco.Web/Mvc/PluginControllerArea.cs index 838e304847..a4440ec4a6 100644 --- a/src/Umbraco.Web/Mvc/PluginControllerArea.cs +++ b/src/Umbraco.Web/Mvc/PluginControllerArea.cs @@ -6,6 +6,7 @@ using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Web.WebApi; @@ -17,7 +18,7 @@ namespace Umbraco.Web.Mvc /// internal class PluginControllerArea : AreaRegistration { - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IEnumerable _surfaceControllers; private readonly IEnumerable _apiControllers; @@ -30,7 +31,7 @@ namespace Umbraco.Web.Mvc /// /// /// - public PluginControllerArea(IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IEnumerable pluginControllers) + public PluginControllerArea(GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IEnumerable pluginControllers) { _globalSettings = globalSettings; _hostingEnvironment = hostingEnvironment; diff --git a/src/Umbraco.Web/Mvc/RenderMvcController.cs b/src/Umbraco.Web/Mvc/RenderMvcController.cs index d9691cb186..00c485bca8 100644 --- a/src/Umbraco.Web/Mvc/RenderMvcController.cs +++ b/src/Umbraco.Web/Mvc/RenderMvcController.cs @@ -1,7 +1,9 @@ using System; using System.Web.Mvc; +using Microsoft.Extensions.Options; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -25,7 +27,7 @@ namespace Umbraco.Web.Mvc ActionInvoker = new RenderActionInvoker(); } - public RenderMvcController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) + public RenderMvcController(IOptions globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, logger) { ActionInvoker = new RenderActionInvoker(); diff --git a/src/Umbraco.Web/Mvc/RenderNoContentController.cs b/src/Umbraco.Web/Mvc/RenderNoContentController.cs index 9334591fbb..52ee7cf44d 100644 --- a/src/Umbraco.Web/Mvc/RenderNoContentController.cs +++ b/src/Umbraco.Web/Mvc/RenderNoContentController.cs @@ -1,6 +1,7 @@ using System; using System.Web.Mvc; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Web.Models; @@ -10,9 +11,9 @@ namespace Umbraco.Web.Mvc { private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly IIOHelper _ioHelper; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; - public RenderNoContentController(IUmbracoContextAccessor umbracoContextAccessor, IIOHelper ioHelper, IGlobalSettings globalSettings) + public RenderNoContentController(IUmbracoContextAccessor umbracoContextAccessor, IIOHelper ioHelper, GlobalSettings globalSettings) { _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); diff --git a/src/Umbraco.Web/Mvc/StatusCodeFilterAttribute.cs b/src/Umbraco.Web/Mvc/StatusCodeFilterAttribute.cs deleted file mode 100644 index 727c29b93c..0000000000 --- a/src/Umbraco.Web/Mvc/StatusCodeFilterAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Net; -using System.Web.Mvc; -using Umbraco.Core; -using Umbraco.Web.Composing; - -namespace Umbraco.Web.Mvc -{ - /// - /// Forces the response to have a specific http status code - /// - /// Migrated already to .Net Core - internal class StatusCodeResultAttribute : ActionFilterAttribute - { - private readonly HttpStatusCode _statusCode; - - public StatusCodeResultAttribute(HttpStatusCode statusCode) - { - _statusCode = statusCode; - } - - public override void OnActionExecuted(ActionExecutedContext filterContext) - { - base.OnActionExecuted(filterContext); - - filterContext.HttpContext.Response.StatusCode = (int)_statusCode; - filterContext.HttpContext.Response.TrySkipIisCustomErrors = Current.Configs.WebRouting().TrySkipIisCustomErrors; - } - } -} diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs index b5c6185069..64a9e56014 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs @@ -2,8 +2,9 @@ using System.Web; using System.Web.Mvc; using Umbraco.Core; -using Umbraco.Web.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; +using Umbraco.Web.Composing; using Umbraco.Web.Security; namespace Umbraco.Web.Mvc @@ -55,7 +56,7 @@ namespace Umbraco.Web.Mvc { if (redirectToUmbracoLogin) { - _redirectUrl = Current.Configs.Global().GetBackOfficePath(Current.HostingEnvironment).EnsureStartsWith("~"); + _redirectUrl = new GlobalSettings().GetBackOfficePath(Current.HostingEnvironment).EnsureStartsWith("~"); } } diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs index 0f1ea42df5..759c3536c1 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs @@ -1,5 +1,7 @@ -using Umbraco.Core.Cache; +using Microsoft.Extensions.Options; +using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Services; @@ -21,7 +23,7 @@ namespace Umbraco.Web.Mvc { } - protected UmbracoAuthorizedController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) + protected UmbracoAuthorizedController(IOptions globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, logger) { } diff --git a/src/Umbraco.Web/Mvc/UmbracoController.cs b/src/Umbraco.Web/Mvc/UmbracoController.cs index 10b7dc8f1a..de4a4d7523 100644 --- a/src/Umbraco.Web/Mvc/UmbracoController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoController.cs @@ -1,12 +1,14 @@ using System; using System.Web; using System.Web.Mvc; +using Microsoft.Extensions.Options; using Microsoft.Owin; using Umbraco.Core.Cache; using Umbraco.Web.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Services; using Umbraco.Web.Security; @@ -23,7 +25,7 @@ namespace Umbraco.Web.Mvc /// /// Gets or sets the Umbraco context. /// - public IGlobalSettings GlobalSettings { get; } + public IOptions GlobalSettings { get; } /// /// Gets the Umbraco context. @@ -69,7 +71,7 @@ namespace Umbraco.Web.Mvc protected UmbracoController() : this( - Current.Factory.GetInstance(), + Current.Factory.GetInstance>(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), @@ -79,7 +81,7 @@ namespace Umbraco.Web.Mvc { } - protected UmbracoController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) + protected UmbracoController(IOptions globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, ILogger logger) { GlobalSettings = globalSettings; UmbracoContextAccessor = umbracoContextAccessor; diff --git a/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs index 9a0aa6b600..b88d1c0736 100644 --- a/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs +++ b/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs @@ -16,7 +16,7 @@ namespace Umbraco.Web.Mvc protected override void HandleNonHttpsRequest(AuthorizationContext filterContext) { // If Umbraco.Core.UseHttps is set, let base method handle redirect. Otherwise, we don't care. - if (Current.Configs.Global().UseHttps) + if (/*Current.Configs.Global().UseHttps*/ false) { base.HandleNonHttpsRequest(filterContext); } @@ -29,7 +29,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 (Current.Configs.Global().UseHttps) + if (/*Current.Configs.Global().UseHttps*/ false) { base.OnAuthorization(filterContext); } diff --git a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs index a687e7c9cd..f461fb9a22 100644 --- a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs +++ b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs @@ -3,9 +3,11 @@ using System.Text; using System.Web; using System.Web.Mvc; using System.Web.WebPages; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -22,8 +24,8 @@ namespace Umbraco.Web.Mvc /// public abstract class UmbracoViewPage : WebViewPage { - private readonly IGlobalSettings _globalSettings; - private readonly IContentSettings _contentSettings; + private readonly GlobalSettings _globalSettings; + private readonly ContentSettings _contentSettings; private IUmbracoContext _umbracoContext; private UmbracoHelper _helper; @@ -105,18 +107,20 @@ namespace Umbraco.Web.Mvc : this( Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), - Current.Factory.GetInstance() + Current.Factory.GetInstance>(), + Current.Factory.GetInstance>() ) { } - protected UmbracoViewPage(ServiceContext services, AppCaches appCaches, IGlobalSettings globalSettings, IContentSettings contentSettings) + protected UmbracoViewPage(ServiceContext services, AppCaches appCaches, IOptions globalSettings, IOptions contentSettings) { + if (globalSettings == null) throw new ArgumentNullException(nameof(globalSettings)); + if (contentSettings == null) throw new ArgumentNullException(nameof(contentSettings)); Services = services; AppCaches = appCaches; - _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); - _contentSettings = contentSettings ?? throw new ArgumentNullException(nameof(contentSettings)); + _globalSettings = globalSettings.Value; + _contentSettings = contentSettings.Value; } // view logic below: diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 1dbe6ac556..487212840b 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -73,8 +73,10 @@ namespace Umbraco.Web { return content.IsAllowedTemplate( Current.Services.ContentTypeService, - Current.Configs.WebRouting().DisableAlternativeTemplates, + /*Current.Configs.WebRouting().DisableAlternativeTemplates, Current.Configs.WebRouting().ValidateAlternativeTemplates, + TODO get values from config*/ + false, false, templateId); } @@ -83,8 +85,10 @@ namespace Umbraco.Web return content.IsAllowedTemplate( Current.Services.FileService, Current.Services.ContentTypeService, - Current.Configs.WebRouting().DisableAlternativeTemplates, - Current.Configs.WebRouting().ValidateAlternativeTemplates, + /*Current.Configs.WebRouting().DisableAlternativeTemplates, + Current.Configs.WebRouting().ValidateAlternativeTemplates, + TODO get values from config*/ + false, false, templateAlias); } diff --git a/src/Umbraco.Web/RoutableDocumentFilter.cs b/src/Umbraco.Web/RoutableDocumentFilter.cs index cf87e3cf56..03f264ab22 100644 --- a/src/Umbraco.Web/RoutableDocumentFilter.cs +++ b/src/Umbraco.Web/RoutableDocumentFilter.cs @@ -9,6 +9,7 @@ using System.Collections.Generic; using System.Linq; using System.Collections.Concurrent; using Umbraco.Core.Collections; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; using Umbraco.Web.Composing; @@ -22,14 +23,14 @@ namespace Umbraco.Web /// public sealed class RoutableDocumentFilter { - public RoutableDocumentFilter(IGlobalSettings globalSettings, IIOHelper ioHelper) + public RoutableDocumentFilter(GlobalSettings globalSettings, IIOHelper ioHelper) { _globalSettings = globalSettings; _ioHelper = ioHelper; } private static readonly ConcurrentDictionary RouteChecks = new ConcurrentDictionary(); - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; private object _locker = new object(); private bool _isInit = false; diff --git a/src/Umbraco.Web/Runtime/WebInitialComponent.cs b/src/Umbraco.Web/Runtime/WebInitialComponent.cs index dbd0a1fb3a..9108dd820e 100644 --- a/src/Umbraco.Web/Runtime/WebInitialComponent.cs +++ b/src/Umbraco.Web/Runtime/WebInitialComponent.cs @@ -8,13 +8,11 @@ using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Strings; -using Umbraco.Core.IO; -using Umbraco.Web.Install; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; - using Constants = Umbraco.Core.Constants; using Current = Umbraco.Web.Composing.Current; @@ -25,7 +23,7 @@ namespace Umbraco.Web.Runtime private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly SurfaceControllerTypeCollection _surfaceControllerTypes; private readonly UmbracoApiControllerTypeCollection _apiControllerTypes; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IShortStringHelper _shortStringHelper; @@ -33,7 +31,7 @@ namespace Umbraco.Web.Runtime IUmbracoContextAccessor umbracoContextAccessor, SurfaceControllerTypeCollection surfaceControllerTypes, UmbracoApiControllerTypeCollection apiControllerTypes, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IShortStringHelper shortStringHelper) { @@ -111,7 +109,7 @@ namespace Umbraco.Web.Runtime // internal for tests internal static void CreateRoutes( IUmbracoContextAccessor umbracoContextAccessor, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IShortStringHelper shortStringHelper, SurfaceControllerTypeCollection surfaceControllerTypes, UmbracoApiControllerTypeCollection apiControllerTypes, @@ -149,7 +147,7 @@ namespace Umbraco.Web.Runtime } private static void RoutePluginControllers( - IGlobalSettings globalSettings, + GlobalSettings globalSettings, SurfaceControllerTypeCollection surfaceControllerTypes, UmbracoApiControllerTypeCollection apiControllerTypes, IHostingEnvironment hostingEnvironment) diff --git a/src/Umbraco.Web/Security/ActiveDirectoryBackOfficeUserPasswordChecker.cs b/src/Umbraco.Web/Security/ActiveDirectoryBackOfficeUserPasswordChecker.cs index 930cabeee3..82c9cb8496 100644 --- a/src/Umbraco.Web/Security/ActiveDirectoryBackOfficeUserPasswordChecker.cs +++ b/src/Umbraco.Web/Security/ActiveDirectoryBackOfficeUserPasswordChecker.cs @@ -1,22 +1,24 @@ using System; using System.DirectoryServices.AccountManagement; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.Security { // TODO: This relies on an assembly that is not .NET Standard (at least not at the time of implementation) :( public class ActiveDirectoryBackOfficeUserPasswordChecker : IBackOfficeUserPasswordChecker { - private readonly IActiveDirectorySettings _settings; + private readonly IOptions _activeDirectorySettings; - public ActiveDirectoryBackOfficeUserPasswordChecker(IActiveDirectorySettings settings) + public ActiveDirectoryBackOfficeUserPasswordChecker(IOptions activeDirectorySettings) { - _settings = settings; + _activeDirectorySettings = activeDirectorySettings; } - public virtual string ActiveDirectoryDomain => _settings.ActiveDirectoryDomain; + public virtual string ActiveDirectoryDomain => _activeDirectorySettings.Value.Domain; public Task CheckPasswordAsync(BackOfficeIdentityUser user, string password) { diff --git a/src/Umbraco.Web/Security/AppBuilderExtensions.cs b/src/Umbraco.Web/Security/AppBuilderExtensions.cs index ac5434aa4e..e51b68ef54 100644 --- a/src/Umbraco.Web/Security/AppBuilderExtensions.cs +++ b/src/Umbraco.Web/Security/AppBuilderExtensions.cs @@ -8,6 +8,7 @@ using Owin; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Web.Composing; using Constants = Umbraco.Core.Constants; @@ -34,7 +35,7 @@ namespace Umbraco.Web.Security /// /// By default this will be configured to execute on PipelineStage.Authenticate /// - public static IAppBuilder UseUmbracoBackOfficeExternalCookieAuthentication(this IAppBuilder app, IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtimeState,IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IRequestCache requestCache) + public static IAppBuilder UseUmbracoBackOfficeExternalCookieAuthentication(this IAppBuilder app, IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtimeState,GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IRequestCache requestCache) { return app.UseUmbracoBackOfficeExternalCookieAuthentication(umbracoContextAccessor, runtimeState, globalSettings, hostingEnvironment, requestCache, PipelineStage.Authenticate); } @@ -53,7 +54,7 @@ namespace Umbraco.Web.Security /// public static IAppBuilder UseUmbracoBackOfficeExternalCookieAuthentication(this IAppBuilder app, IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtimeState, - IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IRequestCache requestCache, PipelineStage stage) + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IRequestCache requestCache, PipelineStage stage) { if (app == null) throw new ArgumentNullException(nameof(app)); if (runtimeState == null) throw new ArgumentNullException(nameof(runtimeState)); @@ -68,7 +69,7 @@ namespace Umbraco.Web.Security CookiePath = "/", CookieSecure = globalSettings.UseHttps ? CookieSecureOption.Always : CookieSecureOption.SameAsRequest, CookieHttpOnly = true, - CookieDomain = Current.Configs.Security().AuthCookieDomain + CookieDomain = new SecuritySettings().AuthCookieDomain // TODO inject settings }, stage); return app; diff --git a/src/Umbraco.Web/Security/AuthenticationExtensions.cs b/src/Umbraco.Web/Security/AuthenticationExtensions.cs index 2b8ba2ddfb..de5abf8a6b 100644 --- a/src/Umbraco.Web/Security/AuthenticationExtensions.cs +++ b/src/Umbraco.Web/Security/AuthenticationExtensions.cs @@ -13,6 +13,7 @@ using Microsoft.Owin.Security; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.BackOffice; +using Umbraco.Core.Configuration.Models; using Umbraco.Extensions; using Umbraco.Web.Composing; using Constants = Umbraco.Core.Constants; @@ -68,7 +69,7 @@ namespace Umbraco.Web.Security if (ex is FormatException || ex is JsonReaderException) { // this will occur if the cookie data is invalid - + } else { @@ -104,7 +105,7 @@ namespace Umbraco.Web.Security /// /// This will return the current back office identity. /// - /// + /// /// /// Returns the current back office identity if an admin is authenticated otherwise null /// @@ -151,7 +152,7 @@ namespace Umbraco.Web.Security public static AuthenticationTicket GetUmbracoAuthTicket(this HttpContextBase http) { if (http == null) throw new ArgumentNullException(nameof(http)); - return GetAuthTicket(http, Current.Configs.Security().AuthCookieName); + return GetAuthTicket(http, /*Current.Configs.Security() TODO*/new SecuritySettings().AuthCookieName); } internal static AuthenticationTicket GetUmbracoAuthTicket(this HttpContext http) @@ -163,7 +164,7 @@ namespace Umbraco.Web.Security public static AuthenticationTicket GetUmbracoAuthTicket(this IOwinContext ctx) { if (ctx == null) throw new ArgumentNullException(nameof(ctx)); - return GetAuthTicket(ctx, Current.Configs.Security().AuthCookieName); + return GetAuthTicket(ctx, /*Current.Configs.Security() TODO introduce injection instead of default value*/new SecuritySettings().AuthCookieName); } private static AuthenticationTicket GetAuthTicket(this IOwinContext owinCtx, string cookieName) @@ -215,7 +216,7 @@ namespace Umbraco.Web.Security catch (Exception) { // occurs when decryption fails - + return null; } } @@ -236,6 +237,6 @@ namespace Umbraco.Web.Security return secureDataFormat.Unprotect(formsCookie); } - + } } diff --git a/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs b/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs index 26b85d6c39..6ce61c90d6 100644 --- a/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs +++ b/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs @@ -1,11 +1,13 @@ using System; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.Extensions.Options; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Services; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; @@ -19,23 +21,23 @@ namespace Umbraco.Web.Security { private readonly IUserService _userService; private readonly IRuntimeState _runtimeState; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; - private readonly ISecuritySettings _securitySettings; + private readonly SecuritySettings _securitySettings; - public BackOfficeCookieAuthenticationProvider(IUserService userService, IRuntimeState runtimeState, IGlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, ISecuritySettings securitySettings) + public BackOfficeCookieAuthenticationProvider(IUserService userService, IRuntimeState runtimeState, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IOptions securitySettings) { _userService = userService; _runtimeState = runtimeState; _globalSettings = globalSettings; _hostingEnvironment = hostingEnvironment; - _securitySettings = securitySettings; + _securitySettings = securitySettings.Value; } public override void ResponseSignOut(CookieResponseSignOutContext context) { - + } diff --git a/src/Umbraco.Web/Security/BackOfficeOwinUserManager.cs b/src/Umbraco.Web/Security/BackOfficeOwinUserManager.cs index 771c3239b6..65d7836d42 100644 --- a/src/Umbraco.Web/Security/BackOfficeOwinUserManager.cs +++ b/src/Umbraco.Web/Security/BackOfficeOwinUserManager.cs @@ -8,6 +8,7 @@ using Microsoft.Owin.Security.DataProtection; using Umbraco.Core; using Umbraco.Core.BackOffice; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Mapping; using Umbraco.Core.Security; using Umbraco.Core.Services; @@ -20,7 +21,7 @@ namespace Umbraco.Web.Security public const string OwinMarkerKey = "Umbraco.Web.Security.Identity.BackOfficeUserManagerMarker"; public BackOfficeOwinUserManager( - IUserPasswordConfiguration passwordConfiguration, + IOptions passwordConfiguration, IIpResolver ipResolver, IUserStore store, IOptions optionsAccessor, @@ -32,7 +33,7 @@ namespace Umbraco.Web.Security ILogger> logger) : base(ipResolver, store, optionsAccessor, null, userValidators, passwordValidators, keyNormalizer, errors, null, logger, passwordConfiguration) { - PasswordConfiguration = passwordConfiguration; + PasswordConfiguration = passwordConfiguration.Value; InitUserManager(this, dataProtectionProvider); } @@ -45,9 +46,9 @@ namespace Umbraco.Web.Security IUserService userService, IEntityService entityService, IExternalLoginService externalLoginService, - IGlobalSettings globalSettings, + IOptions globalSettings, UmbracoMapper mapper, - IUserPasswordConfiguration passwordConfiguration, + IOptions passwordConfiguration, IIpResolver ipResolver, BackOfficeIdentityErrorDescriber errors, IDataProtectionProvider dataProtectionProvider, @@ -68,7 +69,7 @@ namespace Umbraco.Web.Security /// Creates a BackOfficeUserManager instance with all default options and a custom BackOfficeUserManager instance /// public static BackOfficeOwinUserManager Create( - IUserPasswordConfiguration passwordConfiguration, + IOptions passwordConfiguration, IIpResolver ipResolver, IUserStore customUserStore, BackOfficeIdentityErrorDescriber errors, @@ -83,11 +84,11 @@ namespace Umbraco.Web.Security // Configure validation logic for passwords var passwordValidators = new List> { new PasswordValidator() }; - options.Password.RequiredLength = passwordConfiguration.RequiredLength; - options.Password.RequireNonAlphanumeric = passwordConfiguration.RequireNonLetterOrDigit; - options.Password.RequireDigit = passwordConfiguration.RequireDigit; - options.Password.RequireLowercase = passwordConfiguration.RequireLowercase; - options.Password.RequireUppercase = passwordConfiguration.RequireUppercase; + options.Password.RequiredLength = passwordConfiguration.Value.RequiredLength; + options.Password.RequireNonAlphanumeric = passwordConfiguration.Value.RequireNonLetterOrDigit; + options.Password.RequireDigit = passwordConfiguration.Value.RequireDigit; + options.Password.RequireLowercase = passwordConfiguration.Value.RequireLowercase; + options.Password.RequireUppercase = passwordConfiguration.Value.RequireUppercase; // Ensure Umbraco security stamp claim type is used options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier; @@ -96,7 +97,7 @@ namespace Umbraco.Web.Security options.ClaimsIdentity.SecurityStampClaimType = Constants.Security.SecurityStampClaimType; options.Lockout.AllowedForNewUsers = true; - options.Lockout.MaxFailedAccessAttempts = passwordConfiguration.MaxFailedAccessAttemptsBeforeLockout; + options.Lockout.MaxFailedAccessAttempts = passwordConfiguration.Value.MaxFailedAccessAttemptsBeforeLockout; //NOTE: This just needs to be in the future, we currently don't support a lockout timespan, it's either they are locked // or they are not locked, but this determines what is set on the account lockout date which corresponds to whether they are // locked out or not. diff --git a/src/Umbraco.Web/Security/BackOfficeSignInManager.cs b/src/Umbraco.Web/Security/BackOfficeSignInManager.cs index 021adaed97..0dc86f7b1b 100644 --- a/src/Umbraco.Web/Security/BackOfficeSignInManager.cs +++ b/src/Umbraco.Web/Security/BackOfficeSignInManager.cs @@ -9,8 +9,7 @@ using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Umbraco.Core; using Umbraco.Core.BackOffice; -using Umbraco.Core.Configuration; -using Umbraco.Core.BackOffice; +using Umbraco.Core.Configuration.Models; namespace Umbraco.Web.Security { @@ -25,7 +24,7 @@ namespace Umbraco.Web.Security private readonly IUserClaimsPrincipalFactory _claimsPrincipalFactory; private readonly IAuthenticationManager _authenticationManager; private readonly ILogger _logger; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IOwinRequest _request; public BackOfficeSignInManager( @@ -33,7 +32,7 @@ namespace Umbraco.Web.Security IUserClaimsPrincipalFactory claimsPrincipalFactory, IAuthenticationManager authenticationManager, ILogger logger, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IOwinRequest request) { _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); @@ -52,7 +51,7 @@ namespace Umbraco.Web.Security return claimsPrincipal.Identity as ClaimsIdentity; } - public static BackOfficeSignInManager Create(IOwinContext context, IGlobalSettings globalSettings, ILogger logger) + public static BackOfficeSignInManager Create(IOwinContext context, GlobalSettings globalSettings, ILogger logger) { var userManager = context.GetBackOfficeUserManager(); @@ -248,7 +247,7 @@ namespace Umbraco.Web.Security } return null; } - + /// /// Two factor verification step /// diff --git a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs b/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs index fc84cd270d..52239f0fda 100644 --- a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs +++ b/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.Security { _defaultUserGroups = defaultUserGroups ?? new[] { Constants.Security.EditorGroupAlias }; _autoLinkExternalAccount = autoLinkExternalAccount; - _defaultCulture = defaultCulture ?? Current.Configs.Global().DefaultUILanguage; + _defaultCulture = defaultCulture ?? /*Current.Configs.Global().DefaultUILanguage TODO reintroduce config value*/ "en-US"; } private readonly string[] _defaultUserGroups; diff --git a/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs b/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs index 3ab37f0f70..62724a4846 100644 --- a/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs +++ b/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs @@ -3,14 +3,13 @@ using System.Diagnostics; using System.Globalization; using System.Threading.Tasks; using System.Web; +using Microsoft.Extensions.Options; using Microsoft.Owin; using Microsoft.Owin.Logging; using Umbraco.Core; using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; -using Umbraco.Core.Security; namespace Umbraco.Web.Security { @@ -25,23 +24,23 @@ namespace Umbraco.Web.Security internal class GetUserSecondsMiddleWare : OwinMiddleware { private readonly UmbracoBackOfficeCookieAuthOptions _authOptions; - private readonly IGlobalSettings _globalSettings; - private readonly ISecuritySettings _security; + private readonly GlobalSettings _globalSettings; + private readonly SecuritySettings _security; private readonly ILogger _logger; private readonly IHostingEnvironment _hostingEnvironment; public GetUserSecondsMiddleWare( OwinMiddleware next, UmbracoBackOfficeCookieAuthOptions authOptions, - IGlobalSettings globalSettings, - ISecuritySettings security, + GlobalSettings globalSettings, + IOptions security, ILogger logger, IHostingEnvironment hostingEnvironment) : base(next) { _authOptions = authOptions ?? throw new ArgumentNullException(nameof(authOptions)); _globalSettings = globalSettings; - _security = security; + _security = security.Value; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _hostingEnvironment = hostingEnvironment; } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 0e03d1e0ce..ffc5da3b21 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -110,10 +110,6 @@
- - {fbe7c065-dac0-4025-a78b-63b24d3ab00b} - Umbraco.Configuration - {29aa69d9-b597-4395-8d42-43b1263c240a} Umbraco.Core @@ -179,7 +175,6 @@ - @@ -247,7 +242,6 @@ - @@ -301,7 +295,6 @@ - diff --git a/src/Umbraco.Web/UmbracoApplication.cs b/src/Umbraco.Web/UmbracoApplication.cs index 92f7826ac6..35b2f0e076 100644 --- a/src/Umbraco.Web/UmbracoApplication.cs +++ b/src/Umbraco.Web/UmbracoApplication.cs @@ -1,18 +1,16 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using System.Threading; +using System.Runtime.InteropServices; using System.Web; using Microsoft.Extensions.Logging; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Runtime; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; +using Umbraco.Core.Runtime; using Umbraco.Web.Runtime; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Umbraco.Web @@ -22,15 +20,10 @@ namespace Umbraco.Web /// public class UmbracoApplication : UmbracoApplicationBase { - protected override IRuntime GetRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) + protected override IRuntime GetRuntime(GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) { - - var connectionStringConfig = configs.ConnectionStrings()[Constants.System.UmbracoConnectionName]; - var dbProviderFactoryCreator = new UmbracoDbProviderFactoryCreator(); - var globalSettings = configs.Global(); - var connectionStrings = configs.ConnectionStrings(); // Determine if we should use the sql main dom or the default var appSettingMainDomLock = globalSettings.MainDomLock; @@ -49,7 +42,7 @@ namespace Umbraco.Web new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); var umbracoBootPermissionChecker = new AspNetUmbracoBootPermissionChecker(); - return new CoreRuntime(configs, umbracoVersion, ioHelper, logger, loggerFactory, profiler, umbracoBootPermissionChecker, hostingEnvironment, backOfficeInfo, dbProviderFactoryCreator, mainDom, + return new CoreRuntime(globalSettings, connectionStrings,umbracoVersion, ioHelper, logger, loggerFactory, profiler, umbracoBootPermissionChecker, hostingEnvironment, backOfficeInfo, dbProviderFactoryCreator, mainDom, GetTypeFinder(hostingEnvironment, logger, profiler), appCaches); } diff --git a/src/Umbraco.Web/UmbracoApplicationBase.cs b/src/Umbraco.Web/UmbracoApplicationBase.cs index 1136f6bdd1..2a477b620c 100644 --- a/src/Umbraco.Web/UmbracoApplicationBase.cs +++ b/src/Umbraco.Web/UmbracoApplicationBase.cs @@ -1,26 +1,29 @@ -using Serilog.Context; -using System; +using System; using System.IO; using System.Reflection; using System.Threading; using System.Web; using System.Web.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Serilog; +using Serilog.Context; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Logging.Serilog; using Umbraco.Core.Logging.Serilog.Enrichers; using Umbraco.Net; -using Umbraco.Web.AspNet; using Umbraco.Web.Hosting; using Umbraco.Web.Logging; +using ConnectionStrings = Umbraco.Core.Configuration.Models.ConnectionStrings; using Current = Umbraco.Web.Composing.Current; +using GlobalSettings = Umbraco.Core.Configuration.Models.GlobalSettings; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Umbraco.Web @@ -30,6 +33,9 @@ namespace Umbraco.Web /// public abstract class UmbracoApplicationBase : HttpApplication { + private readonly SecuritySettings _securitySettings; + private readonly GlobalSettings _globalSettings; + private readonly ConnectionStrings _connectionStrings; private IRuntime _runtime; private IFactory _factory; private ILoggerFactory _loggerFactory; @@ -38,12 +44,12 @@ namespace Umbraco.Web { if (!Umbraco.Composing.Current.IsInitialized) { - var configFactory = new ConfigsFactory(); + HostingSettings hostingSettings = null; + GlobalSettings globalSettings = null; + SecuritySettings securitySettings = null; + WebRoutingSettings webRoutingSettings = null; - var hostingSettings = configFactory.HostingSettings; - var globalSettings = configFactory.GlobalSettings; - - var hostingEnvironment = new AspNetHostingEnvironment(hostingSettings); + var hostingEnvironment = new AspNetHostingEnvironment(Options.Create(hostingSettings)); var loggingConfiguration = new LoggingConfiguration( Path.Combine(hostingEnvironment.ApplicationPhysicalPath, "App_Data\\Logs"), Path.Combine(hostingEnvironment.ApplicationPhysicalPath, "config\\serilog.config"), @@ -65,11 +71,12 @@ namespace Umbraco.Web var logger = _loggerFactory.CreateLogger(); - var configs = configFactory.Create(); - - var backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, ioHelper, _loggerFactory.CreateLogger(), configFactory.WebRoutingSettings); + var backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, ioHelper, _loggerFactory.CreateLogger(), Options.Create(webRoutingSettings)); var profiler = GetWebProfiler(hostingEnvironment); - Umbraco.Composing.Current.Initialize(logger, configs, ioHelper, hostingEnvironment, backOfficeInfo, profiler); + Umbraco.Composing.Current.Initialize(logger, + securitySettings, + globalSettings, + ioHelper, hostingEnvironment, backOfficeInfo, profiler); Logger = logger; } } @@ -90,12 +97,16 @@ namespace Umbraco.Web return webProfiler; } - protected UmbracoApplicationBase(Microsoft.Extensions.Logging.ILogger logger, Configs configs, IIOHelper ioHelper, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) + protected UmbracoApplicationBase(Microsoft.Extensions.Logging.ILogger logger, SecuritySettings securitySettings, GlobalSettings globalSettings, ConnectionStrings connectionStrings, IIOHelper ioHelper, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo) { + _securitySettings = securitySettings; + _globalSettings = globalSettings; + _connectionStrings = connectionStrings; + if (!Umbraco.Composing.Current.IsInitialized) { Logger = logger; - Umbraco.Composing.Current.Initialize(logger, configs, ioHelper, hostingEnvironment, backOfficeInfo, profiler); + Umbraco.Composing.Current.Initialize(logger, securitySettings, globalSettings, ioHelper, hostingEnvironment, backOfficeInfo, profiler); } } @@ -138,12 +149,12 @@ namespace Umbraco.Web /// /// Gets a runtime. /// - protected abstract IRuntime GetRuntime(Configs configs, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo); + protected abstract IRuntime GetRuntime(GlobalSettings globalSettings, ConnectionStrings connectionStrings, IUmbracoVersion umbracoVersion, IIOHelper ioHelper, ILogger logger, ILoggerFactory loggerFactory, IProfiler profiler, IHostingEnvironment hostingEnvironment, IBackOfficeInfo backOfficeInfo); /// /// Gets the application register. /// - protected virtual IRegister GetRegister(IGlobalSettings globalSettings) + protected virtual IRegister GetRegister(GlobalSettings globalSettings) { return RegisterFactory.Create(globalSettings); } @@ -177,14 +188,15 @@ namespace Umbraco.Web // ******** THIS IS WHERE EVERYTHING BEGINS ******** - var globalSettings = Umbraco.Composing.Current.Configs.Global(); - var umbracoVersion = new UmbracoVersion(globalSettings); + var globalSettings = _globalSettings; + var umbracoVersion = new UmbracoVersion(); // create the register for the application, and boot // the boot manager is responsible for registrations var register = GetRegister(globalSettings); _runtime = GetRuntime( - Umbraco.Composing.Current.Configs, + _globalSettings, + _connectionStrings, umbracoVersion, Umbraco.Composing.Current.IOHelper, Umbraco.Composing.Current.Logger, diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index ae1cf885b3..bda836c847 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -1,7 +1,7 @@ using System; using System.Web; using Umbraco.Core; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Composing; @@ -17,7 +17,7 @@ namespace Umbraco.Web public class UmbracoContext : DisposableObjectSlim, IDisposeOnRequestEnd, IUmbracoContext { private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly ICookieManager _cookieManager; private readonly Lazy _publishedSnapshot; @@ -31,7 +31,7 @@ namespace Umbraco.Web internal UmbracoContext(IHttpContextAccessor httpContextAccessor, IPublishedSnapshotService publishedSnapshotService, IWebSecurity webSecurity, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IVariationContextAccessor variationContextAccessor, UriUtility uriUtility, diff --git a/src/Umbraco.Web/UmbracoContextFactory.cs b/src/Umbraco.Web/UmbracoContextFactory.cs index bfb4dd627d..4eba56c36f 100644 --- a/src/Umbraco.Web/UmbracoContextFactory.cs +++ b/src/Umbraco.Web/UmbracoContextFactory.cs @@ -2,6 +2,7 @@ using System.IO; using System.Text; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; @@ -20,7 +21,7 @@ namespace Umbraco.Web private readonly IVariationContextAccessor _variationContextAccessor; private readonly IDefaultCultureAccessor _defaultCultureAccessor; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IUserService _userService; private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; @@ -35,7 +36,7 @@ namespace Umbraco.Web IPublishedSnapshotService publishedSnapshotService, IVariationContextAccessor variationContextAccessor, IDefaultCultureAccessor defaultCultureAccessor, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IUserService userService, IHostingEnvironment hostingEnvironment, UriUtility uriUtility, diff --git a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs index 600b58cf06..edd429946f 100644 --- a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs +++ b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs @@ -1,9 +1,11 @@ using System; +using Microsoft.Extensions.Options; using Microsoft.Owin; using Owin; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; using Umbraco.Core.IO; @@ -28,9 +30,8 @@ namespace Umbraco.Web public class UmbracoDefaultOwinStartup { protected IUmbracoContextAccessor UmbracoContextAccessor => Current.UmbracoContextAccessor; - protected IGlobalSettings GlobalSettings => Current.Factory.GetInstance(); - protected IContentSettings ContentSettings => Current.Factory.GetInstance(); - protected ISecuritySettings SecuritySettings => Current.Factory.GetInstance(); + protected GlobalSettings GlobalSettings => Current.Factory.GetInstance(); + protected SecuritySettings SecuritySettings => Current.Factory.GetInstance>().Value; protected IUserPasswordConfiguration UserPasswordConfig => Current.Factory.GetInstance(); protected IRuntimeState RuntimeState => Current.RuntimeState; protected ServiceContext Services => Current.Services; diff --git a/src/Umbraco.Web/UmbracoInjectedModule.cs b/src/Umbraco.Web/UmbracoInjectedModule.cs index 74b4190b16..7faa4b3b4a 100644 --- a/src/Umbraco.Web/UmbracoInjectedModule.cs +++ b/src/Umbraco.Web/UmbracoInjectedModule.cs @@ -1,18 +1,16 @@ using System; -using System.Collections.Generic; using System.Web; using System.Web.Routing; using Microsoft.Extensions.Logging; using Umbraco.Core; -using Umbraco.Core.Security; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Exceptions; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; +using Umbraco.Core.Security; using Umbraco.Web.Composing; using Umbraco.Web.Routing; -using Umbraco.Web.Security; namespace Umbraco.Web { @@ -39,7 +37,7 @@ namespace Umbraco.Web private readonly IUmbracoContextFactory _umbracoContextFactory; private readonly RoutableDocumentFilter _routableDocumentLookup; private readonly IRequestCache _requestCache; - private readonly IGlobalSettings _globalSettings; + private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly UriUtility _uriUtility; @@ -51,7 +49,7 @@ namespace Umbraco.Web RoutableDocumentFilter routableDocumentLookup, UriUtility uriUtility, IRequestCache requestCache, - IGlobalSettings globalSettings, + GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment) { _runtime = runtime; diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index 7e4ac6c3d5..932861a89c 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -75,7 +75,7 @@ namespace Umbraco.Web else if (pcr.Is404) { response.StatusCode = 404; - response.TrySkipIisCustomErrors = Current.Configs.WebRouting().TrySkipIisCustomErrors; + response.TrySkipIisCustomErrors = /*Current.Configs.WebRouting().TrySkipIisCustomErrors; TODO introduce from config*/ false; if (response.TrySkipIisCustomErrors == false) logger.LogWarning("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 f71036c0ae..4c2174840e 100644 --- a/src/Umbraco.Web/UmbracoWebService.cs +++ b/src/Umbraco.Web/UmbracoWebService.cs @@ -1,14 +1,7 @@ -using System; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; +using System.Web.Mvc; using System.Web.Services; -using Microsoft.Extensions.Logging; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; -using Umbraco.Core.Persistence; using Umbraco.Core.Services; using Umbraco.Web.Composing; using Umbraco.Web.Security; @@ -23,7 +16,7 @@ namespace Umbraco.Web { private UrlHelper _url; - protected UmbracoWebService(ILogger logger, IProfilingLogger profilingLogger, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, IGlobalSettings globalSettings) + protected UmbracoWebService(ILogger logger, IProfilingLogger profilingLogger, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, GlobalSettings globalSettings) { Logger = logger; ProfilingLogger = profilingLogger; @@ -33,7 +26,7 @@ namespace Umbraco.Web } protected UmbracoWebService() - : this(Current.Logger, Current.ProfilingLogger, Current.UmbracoContextAccessor, Current.Services, Current.Configs.Global()) + : this(Current.Logger, Current.ProfilingLogger, Current.UmbracoContextAccessor, Current.Services, new GlobalSettings()) { } @@ -65,7 +58,7 @@ namespace Umbraco.Web /// /// Gets the global settings. /// - public IGlobalSettings GlobalSettings { get; } + public GlobalSettings GlobalSettings { get; } /// /// Gets the web security helper. diff --git a/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs b/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs deleted file mode 100644 index 09fd5e080c..0000000000 --- a/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Web.Http.Controllers; -using System.Web.Http.Filters; -using Umbraco.Core; -using Umbraco.Web.Composing; -using Umbraco.Core.BackOffice; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Security; -using Umbraco.Web.Security; -using Umbraco.Core.Mapping; -using Umbraco.Core.Models; - -namespace Umbraco.Web.WebApi.Filters -{ - /// - /// This filter will check if the current Principal/Identity assigned to the request has stale data in it compared - /// to what is persisted for the current user and will update the current auth ticket with the correct data if required and output - /// a custom response header for the UI to be notified of it. - /// - /// - /// This could/should be created as a filter on the BackOfficeCookieAuthenticationProvider just like the SecurityStampValidator does - /// - public sealed class CheckIfUserTicketDataIsStaleAttribute : ActionFilterAttribute - { - // this is an attribute - no choice - private UmbracoMapper Mapper => Current.Mapper; - - public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) - { - await CheckStaleData(actionContext); - } - - public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) - { - await CheckStaleData(actionExecutedContext.ActionContext); - - //we need new tokens and append the custom header if changes have been made - if (actionExecutedContext.ActionContext.Request.Properties.ContainsKey(typeof(CheckIfUserTicketDataIsStaleAttribute).Name)) - { - var tokenFilter = new SetAngularAntiForgeryTokensAttribute(); - tokenFilter.OnActionExecuted(actionExecutedContext); - - //add the header - AppendUserModifiedHeaderAttribute.AppendHeader(actionExecutedContext); - } - } - - private async Task CheckStaleData(HttpActionContext actionContext) - { - if (actionContext == null - || actionContext.Request == null - || actionContext.RequestContext == null - || actionContext.RequestContext.Principal == null - || actionContext.RequestContext.Principal.Identity == null) - { - return; - } - - //don't execute if it's already been done - if (actionContext.Request.Properties.ContainsKey(typeof(CheckIfUserTicketDataIsStaleAttribute).Name)) - return; - - var identity = actionContext.RequestContext.Principal.Identity as UmbracoBackOfficeIdentity; - if (identity == null) return; - - var userId = identity.Id.TryConvertTo(); - if (userId == false) return; - - var user = Current.Services.UserService.GetUserById(userId.Result); - if (user == null) return; - - //a list of checks to execute, if any of them pass then we resync - var checks = new Func[] - { - () => user.Username != identity.Username, - () => - { - var culture = user.GetUserCulture(Current.Services.TextService, Current.Configs.Global()); - return culture != null && culture.ToString() != identity.Culture; - }, - () => user.AllowedSections.UnsortedSequenceEqual(identity.AllowedApplications) == false, - () => user.Groups.Select(x => x.Alias).UnsortedSequenceEqual(identity.Roles) == false, - () => - { - var startContentIds = user.CalculateContentStartNodeIds(Current.Services.EntityService); - return startContentIds.UnsortedSequenceEqual(identity.StartContentNodes) == false; - }, - () => - { - var startMediaIds = user.CalculateMediaStartNodeIds(Current.Services.EntityService); - return startMediaIds.UnsortedSequenceEqual(identity.StartMediaNodes) == false; - } - }; - - if (checks.Any(check => check())) - { - await ReSync(user, actionContext); - } - } - - /// - /// This will update the current request IPrincipal to be correct and re-create the auth ticket - /// - /// - /// - /// - private async Task ReSync(IUser user, HttpActionContext actionContext) - { - var owinCtx = actionContext.Request.TryGetOwinContext(); - 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); - - //flag that we've made changes - actionContext.Request.Properties[typeof(CheckIfUserTicketDataIsStaleAttribute).Name] = true; - } - } - } -} diff --git a/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs b/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs deleted file mode 100644 index dadf2367b6..0000000000 --- a/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Web.Http.Filters; -using Umbraco.Core; -using Umbraco.Web.Composing; - -namespace Umbraco.Web.WebApi.Filters -{ - /// - /// A filter to set the csrf cookie token based on angular conventions - /// - public sealed class SetAngularAntiForgeryTokensAttribute : ActionFilterAttribute - { - public override void OnActionExecuted(HttpActionExecutedContext context) - { - if (context.Response == null) return; - - //DO not set the token cookies if the request has failed!! - if (context.Response.StatusCode != HttpStatusCode.OK) return; - - //don't need to set the cookie if they already exist and they are valid - if (context.Request.Headers.GetCookies(Constants.Web.AngularCookieName).Any() - && context.Request.Headers.GetCookies(Constants.Web.CsrfValidationCookieName).Any()) - { - //if they are not valid for some strange reason - we need to continue setting valid ones - string failedReason; - if (AngularAntiForgeryHelper.ValidateHeaders(context.Request.Headers, out failedReason)) - { - return; - } - } - - string cookieToken, headerToken; - AngularAntiForgeryHelper.GetTokens(out cookieToken, out headerToken); - - //We need to set 2 cookies: one is the cookie value that angular will use to set a header value on each request, - // the 2nd is the validation value generated by the anti-forgery helper that we use to validate the header token against. - - var angularCookie = new CookieHeaderValue(Constants.Web.AngularCookieName, headerToken) - { - Path = "/", - //must be js readable - HttpOnly = false, - Secure = Current.Configs.Global().UseHttps - }; - - var validationCookie = new CookieHeaderValue(Constants.Web.CsrfValidationCookieName, cookieToken) - { - Path = "/", - HttpOnly = true, - Secure = Current.Configs.Global().UseHttps - }; - - context.Response.Headers.AddCookies(new[] { angularCookie, validationCookie }); - } - } -} diff --git a/src/Umbraco.Web/WebApi/UmbracoApiController.cs b/src/Umbraco.Web/WebApi/UmbracoApiController.cs index a832b4e823..724ea810c9 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiController.cs @@ -3,6 +3,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Persistence; @@ -20,7 +21,7 @@ namespace Umbraco.Web.WebApi { } - protected UmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + protected UmbracoApiController(GlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs index d009528bc7..7c15775f7b 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs @@ -6,6 +6,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Web.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Core.Mapping; using Umbraco.Core.Persistence; @@ -38,7 +39,7 @@ namespace Umbraco.Web.WebApi /// Dependencies are obtained from the service locator. protected UmbracoApiControllerBase() : this( - Current.Factory.GetInstance(), + Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), @@ -53,10 +54,9 @@ namespace Umbraco.Web.WebApi /// /// Initializes a new instance of the class with all its dependencies. /// - protected UmbracoApiControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + protected UmbracoApiControllerBase(GlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) { UmbracoContextAccessor = umbracoContextAccessor; - GlobalSettings = globalSettings; SqlContext = sqlContext; Services = services; AppCaches = appCaches; @@ -72,11 +72,6 @@ namespace Umbraco.Web.WebApi /// For debugging purposes. internal Guid InstanceId { get; } = Guid.NewGuid(); - /// - /// Gets the Umbraco context. - /// - public virtual IGlobalSettings GlobalSettings { get; } - /// /// Gets the Umbraco context. /// diff --git a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs index 48b3de44fd..7858d6955a 100644 --- a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs @@ -1,6 +1,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Logging; using Umbraco.Web.WebApi.Filters; using Umbraco.Core.Persistence; @@ -24,7 +25,7 @@ namespace Umbraco.Web.WebApi [UmbracoAuthorize] [DisableBrowserCache] // [UmbracoWebApiRequireHttps] - [CheckIfUserTicketDataIsStale] + // [CheckIfUserTicketDataIsStale] [UnhandedExceptionLoggerConfiguration] [EnableDetailedErrors] public abstract class UmbracoAuthorizedApiController : UmbracoApiController @@ -35,7 +36,7 @@ namespace Umbraco.Web.WebApi { } - protected UmbracoAuthorizedApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + protected UmbracoAuthorizedApiController(GlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/WebAssets/CDF/ClientDependencyComponent.cs b/src/Umbraco.Web/WebAssets/CDF/ClientDependencyComponent.cs index 0d8d4b8bf2..47dd0908dd 100644 --- a/src/Umbraco.Web/WebAssets/CDF/ClientDependencyComponent.cs +++ b/src/Umbraco.Web/WebAssets/CDF/ClientDependencyComponent.cs @@ -3,9 +3,11 @@ using System.Collections.Specialized; using System.IO; using ClientDependency.Core.CompositeFiles.Providers; using ClientDependency.Core.Config; +using Microsoft.Extensions.Options; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.Hosting; using Umbraco.Web.Runtime; @@ -14,18 +16,18 @@ namespace Umbraco.Web.WebAssets.CDF [ComposeAfter(typeof(WebInitialComponent))] public sealed class ClientDependencyComponent : IComponent { - private readonly IHostingSettings _hostingSettings; + private readonly HostingSettings _hostingSettings; private readonly IHostingEnvironment _hostingEnvironment; - private readonly IRuntimeSettings _settings; + private readonly RuntimeSettings _settings; public ClientDependencyComponent( - IHostingSettings hostingSettings, + IOptions hostingSettings, IHostingEnvironment hostingEnvironment, - IRuntimeSettings settings) + IOptions settings) { - _hostingSettings = hostingSettings; + _hostingSettings = hostingSettings.Value; _hostingEnvironment = hostingEnvironment; - _settings = settings; + _settings = settings.Value; } public void Initialize() diff --git a/src/Umbraco.Web/WebAssets/CDF/UmbracoClientDependencyLoader.cs b/src/Umbraco.Web/WebAssets/CDF/UmbracoClientDependencyLoader.cs index a89cf8f908..a0704140f1 100644 --- a/src/Umbraco.Web/WebAssets/CDF/UmbracoClientDependencyLoader.cs +++ b/src/Umbraco.Web/WebAssets/CDF/UmbracoClientDependencyLoader.cs @@ -2,6 +2,7 @@ using ClientDependency.Core.Controls; using ClientDependency.Core.FileRegistration.Providers; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Models; using Umbraco.Core.IO; namespace Umbraco.Web.WebAssets.CDF @@ -15,7 +16,7 @@ namespace Umbraco.Web.WebAssets.CDF /// /// Set the defaults /// - public UmbracoClientDependencyLoader(IGlobalSettings globalSettings, IIOHelper ioHelper) + public UmbracoClientDependencyLoader(GlobalSettings globalSettings, IIOHelper ioHelper) : base() { this.AddPath("UmbracoRoot", ioHelper.ResolveUrl(globalSettings.UmbracoPath)); @@ -23,7 +24,7 @@ namespace Umbraco.Web.WebAssets.CDF } - public static ClientDependencyLoader TryCreate(Control parent, out bool isNew, IGlobalSettings globalSettings, IIOHelper ioHelper) + public static ClientDependencyLoader TryCreate(Control parent, out bool isNew, GlobalSettings globalSettings, IIOHelper ioHelper) { if (ClientDependencyLoader.Instance == null) { diff --git a/src/umbraco.sln b/src/umbraco.sln index b2922abf3e..6216b3128b 100644 --- a/src/umbraco.sln +++ b/src/umbraco.sln @@ -137,8 +137,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Umbraco.ModelsBuilder.Embed EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Infrastructure", "Umbraco.Infrastructure\Umbraco.Infrastructure.csproj", "{3AE7BF57-966B-45A5-910A-954D7C554441}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Configuration", "Umbraco.Configuration\Umbraco.Configuration.csproj", "{FBE7C065-DAC0-4025-A78B-63B24D3AB00B}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Umbraco.Persistance.SqlCe", "Umbraco.Persistance.SqlCe\Umbraco.Persistance.SqlCe.csproj", "{33085570-9BF2-4065-A9B0-A29D920D13BA}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Umbraco.TestData", "Umbraco.TestData\Umbraco.TestData.csproj", "{FB5676ED-7A69-492C-B802-E7B24144C0FC}" @@ -199,10 +197,6 @@ Global {3AE7BF57-966B-45A5-910A-954D7C554441}.Debug|Any CPU.Build.0 = Debug|Any CPU {3AE7BF57-966B-45A5-910A-954D7C554441}.Release|Any CPU.ActiveCfg = Release|Any CPU {3AE7BF57-966B-45A5-910A-954D7C554441}.Release|Any CPU.Build.0 = Release|Any CPU - {FBE7C065-DAC0-4025-A78B-63B24D3AB00B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FBE7C065-DAC0-4025-A78B-63B24D3AB00B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FBE7C065-DAC0-4025-A78B-63B24D3AB00B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FBE7C065-DAC0-4025-A78B-63B24D3AB00B}.Release|Any CPU.Build.0 = Release|Any CPU {33085570-9BF2-4065-A9B0-A29D920D13BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {33085570-9BF2-4065-A9B0-A29D920D13BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {33085570-9BF2-4065-A9B0-A29D920D13BA}.Release|Any CPU.ActiveCfg = Release|Any CPU