From c90d6be8ab4cd54af149171221034939a74ec546 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 6 Apr 2018 13:51:54 +1000 Subject: [PATCH] U4-8861 Extract GlobalSettings to an interface and expose on the standard UmbracoConfig.For settings singleton including a bunch of cleanup, getting the installer and steps to be DI --- .../ConfigurationCompositionRoot.cs | 1 + src/Umbraco.Core/Composing/TypeLoader.cs | 75 +-- .../Configuration/GlobalSettings.cs | 466 ++---------------- .../Configuration/GlobalSettingsExtensions.cs | 141 ++++++ .../Configuration/IGlobalSettings.cs | 84 ++++ .../Configuration/LocalTempStorage.cs | 2 +- .../Configuration/UmbracoConfig.cs | 22 +- src/Umbraco.Core/Constants-Web.cs | 2 + src/Umbraco.Core/IO/SystemDirectories.cs | 7 +- src/Umbraco.Core/IO/SystemFiles.cs | 35 +- .../Migrations/Install/DatabaseBuilder.cs | 8 +- .../Models/Identity/BackOfficeIdentityUser.cs | 5 +- .../Models/Identity/IdentityProfile.cs | 5 +- src/Umbraco.Core/Models/Membership/User.cs | 2 +- src/Umbraco.Core/Models/UserExtensions.cs | 9 +- .../Packaging/PackageInstallation.cs | 2 +- .../Repositories/Implement/UserRepository.cs | 14 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 5 +- .../Runtime/CoreRuntimeComponent.cs | 5 +- src/Umbraco.Core/RuntimeState.cs | 7 +- .../BackOfficeCookieAuthenticationProvider.cs | 25 +- .../Security/BackOfficeSignInManager.cs | 33 +- .../Security/BackOfficeUserManager.cs | 7 +- .../Security/BackOfficeUserStore.cs | 7 +- .../Security/SessionIdValidator.cs | 13 +- .../Services/Implement/NotificationService.cs | 12 +- .../Services/Implement/UserService.cs | 6 +- src/Umbraco.Core/Sync/ApplicationUrlHelper.cs | 18 +- src/Umbraco.Core/Sync/ConfigServerAddress.cs | 8 +- .../Sync/ConfigServerRegistrar.cs | 9 +- .../Sync/DatabaseServerMessenger.cs | 11 +- src/Umbraco.Core/Umbraco.Core.csproj | 2 + src/Umbraco.Core/UriExtensions.cs | 78 +-- src/Umbraco.Tests/App.config | 2 +- .../PublishedContentCacheTests.cs | 15 +- .../Composing/ComposingTestBase.cs | 3 +- .../Composing/TypeLoaderTests.cs | 5 +- .../Configurations/GlobalSettingsTests.cs | 34 +- .../CoreThings/TryConvertToTests.cs | 2 +- src/Umbraco.Tests/CoreThings/UdiTests.cs | 5 +- .../CoreThings/UriExtensionsTests.cs | 5 +- src/Umbraco.Tests/IO/FileSystemsTests.cs | 2 +- src/Umbraco.Tests/Macros/MacroTests.cs | 2 +- .../Misc/ApplicationUrlHelperTests.cs | 84 ++-- src/Umbraco.Tests/Misc/UriUtilityTests.cs | 7 +- src/Umbraco.Tests/Models/ContentTests.cs | 2 +- src/Umbraco.Tests/Models/MacroTests.cs | 2 +- .../Packaging/PackageExtractionTests.cs | 2 +- .../Repositories/UserRepositoryTest.cs | 4 +- .../PropertyEditorValueEditorTests.cs | 2 +- .../PublishedContentMoreTests.cs | 7 +- .../PublishedContent/PublishedMediaTests.cs | 2 +- .../ContentFinderByNiceUrlAndTemplateTests.cs | 12 +- .../Routing/ContentFinderByNiceUrlTests.cs | 45 +- .../ContentFinderByNiceUrlWithDomainsTests.cs | 17 +- .../Routing/DomainsAndCulturesTests.cs | 17 +- .../Routing/NiceUrlProviderTests.cs | 62 ++- .../Routing/NiceUrlRoutesTests.cs | 53 +- .../NiceUrlsProviderWithDomainsTests.cs | 94 ++-- .../Routing/RenderRouteHandlerTests.cs | 7 +- .../Routing/UmbracoModuleTests.cs | 2 +- .../Routing/UrlsWithNestedDomains.cs | 13 +- .../Runtimes/CoreRuntimeTests.cs | 2 +- .../Scoping/ScopedNuCacheTests.cs | 10 +- src/Umbraco.Tests/Scoping/ScopedXmlTests.cs | 4 +- .../Security/BackOfficeCookieManagerTests.cs | 13 +- .../Services/PackagingServiceTests.cs | 2 +- .../Strings/CmsHelperCasingTests.cs | 4 +- .../Strings/DefaultShortStringHelperTests.cs | 48 +- .../TestHelpers/BaseUsingSqlCeSyntax.cs | 3 +- .../TestControllerActivatorBase.cs | 14 +- .../TestHelpers/SettingsForTests.cs | 139 +++--- .../TestHelpers/TestObjects-Mocks.cs | 16 +- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 11 +- .../TestHelpers/TestWithDatabaseBase.cs | 34 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 16 +- src/Umbraco.Tests/Umbraco.Tests.csproj | 11 +- .../UmbracoExamine/ExamineBaseTest.cs | 2 +- .../Controllers/PluginControllerAreaTests.cs | 9 +- ...RenderIndexActionSelectorAttributeTests.cs | 16 +- .../Web/Mvc/SurfaceControllerTests.cs | 20 +- .../Web/Mvc/UmbracoViewPageTests.cs | 9 +- .../Web/TemplateUtilitiesTests.cs | 8 +- .../Web/WebExtensionMethodTests.cs | 15 +- src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs | 2 +- .../umbraco/Views/Default.cshtml | 3 +- src/Umbraco.Web.UI/web.Template.Debug.config | 4 +- src/Umbraco.Web.UI/web.Template.config | 2 +- src/Umbraco.Web/AppBuilderExtensions.cs | 5 +- .../BatchedDatabaseServerMessenger.cs | 5 +- .../Cache/CacheRefresherComponent.cs | 3 +- ...aseServerRegistrarAndMessengerComponent.cs | 5 +- .../InstallerCompositionRoot.cs | 42 ++ .../Editors/AuthenticationController.cs | 8 +- .../Editors/BackOfficeController.cs | 4 +- .../Editors/BackOfficeServerVariables.cs | 6 +- src/Umbraco.Web/Editors/PreviewController.cs | 8 +- .../Editors/UpdateCheckController.cs | 4 +- src/Umbraco.Web/Editors/UsersController.cs | 6 +- .../HealthCheck/Checks/Security/HttpsCheck.cs | 7 +- .../HtmlHelperBackOfficeExtensions.cs | 5 +- .../Controllers/InstallApiController.cs | 30 +- .../Install/Controllers/InstallController.cs | 13 +- src/Umbraco.Web/Install/InstallHelper.cs | 60 +-- .../Install/InstallStepCollection.cs | 40 ++ .../MajorVersion7UpgradeReport.cs | 134 ----- .../Install/InstallSteps/NewInstallStep.cs | 6 +- .../InstallSteps/SetUmbracoVersionStep.cs | 19 +- .../InstallSteps/StarterKitDownloadStep.cs | 8 +- .../InstallSteps/Version73FileCleanup.cs | 90 ---- src/Umbraco.Web/Macros/MacroRenderer.cs | 2 +- .../Models/ContentEditing/ContentTypeBasic.cs | 2 +- .../Models/Mapping/UserMapperProfile.cs | 10 +- src/Umbraco.Web/Models/Trees/TreeNode.cs | 2 +- .../Mvc/AreaRegistrationExtensions.cs | 24 +- src/Umbraco.Web/Mvc/BackOfficeArea.cs | 17 +- src/Umbraco.Web/Mvc/PluginControllerArea.cs | 27 +- .../Mvc/UmbracoAuthorizeAttribute.cs | 2 +- src/Umbraco.Web/Mvc/UmbracoController.cs | 7 + .../Mvc/UmbracoRequireHttpsAttribute.cs | 5 +- src/Umbraco.Web/Mvc/UrlHelperExtensions.cs | 6 +- .../NotificationServiceExtensions.cs | 32 +- .../PropertyEditors/RteEmbedController.cs | 3 +- .../PublishedCache/NuCache/ContentCache.cs | 7 +- .../NuCache/PublishedSnapshotService.cs | 7 +- .../PublishedContentCache.cs | 9 +- .../PublishedSnapshotService.cs | 19 +- .../XmlPublishedCache/XmlCacheComponent.cs | 6 +- .../XmlPublishedCache/XmlStore.cs | 15 +- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 15 +- .../Routing/ContentFinderByProfile.cs | 67 --- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 9 +- .../Runtime/WebRuntimeComponent.cs | 38 +- .../Security/AuthenticationExtensions.cs | 3 + .../Security/Identity/AppBuilderExtensions.cs | 98 +++- .../Identity/BackOfficeCookieManager.cs | 12 +- .../Identity/ExternalSignInAutoLinkOptions.cs | 17 +- .../Identity/GetUserSecondsMiddleWare.cs | 7 +- .../PreviewAuthenticationMiddleware.cs | 7 +- .../UmbracoBackOfficeCookieAuthOptions.cs | 11 +- src/Umbraco.Web/Security/OwinExtensions.cs | 3 +- src/Umbraco.Web/Security/WebSecurity.cs | 17 +- .../Trees/LegacyTreeDataConverter.cs | 3 +- src/Umbraco.Web/UI/Pages/BasePage.cs | 2 +- .../UI/Pages/UmbracoEnsuredPage.cs | 3 +- src/Umbraco.Web/Umbraco.Web.csproj | 5 +- src/Umbraco.Web/UmbracoContext.cs | 60 ++- src/Umbraco.Web/UmbracoDefaultOwinStartup.cs | 24 +- src/Umbraco.Web/UmbracoModule.cs | 18 +- src/Umbraco.Web/UriUtility.cs | 7 +- .../CheckIfUserTicketDataIsStaleAttribute.cs | 3 +- .../SetAngularAntiForgeryTokensAttribute.cs | 4 +- .../UmbracoWebApiRequireHttpsAttribute.cs | 2 +- .../WebApi/UmbracoApiControllerBase.cs | 7 + .../WebServices/EmbedMediaService.cs | 2 +- .../UmbracoAuthorizedWebService.cs | 7 - .../WebServices/UmbracoWebService.cs | 16 +- .../umbraco/dialogs/sendToTranslation.aspx.cs | 5 +- .../umbraco/translation/xml.aspx.cs | 2 +- .../webservices/CheckForUpgrade.asmx.cs | 6 +- .../umbraco/webservices/nodeSorter.asmx.cs | 3 +- 161 files changed, 1637 insertions(+), 1608 deletions(-) create mode 100644 src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs create mode 100644 src/Umbraco.Core/Configuration/IGlobalSettings.cs create mode 100644 src/Umbraco.Web/Composing/CompositionRoots/InstallerCompositionRoot.cs create mode 100644 src/Umbraco.Web/Install/InstallStepCollection.cs delete mode 100644 src/Umbraco.Web/Install/InstallSteps/MajorVersion7UpgradeReport.cs delete mode 100644 src/Umbraco.Web/Install/InstallSteps/Version73FileCleanup.cs delete mode 100644 src/Umbraco.Web/Routing/ContentFinderByProfile.cs diff --git a/src/Umbraco.Core/Composing/CompositionRoots/ConfigurationCompositionRoot.cs b/src/Umbraco.Core/Composing/CompositionRoots/ConfigurationCompositionRoot.cs index a254c7820d..82912163b6 100644 --- a/src/Umbraco.Core/Composing/CompositionRoots/ConfigurationCompositionRoot.cs +++ b/src/Umbraco.Core/Composing/CompositionRoots/ConfigurationCompositionRoot.cs @@ -15,6 +15,7 @@ namespace Umbraco.Core.Composing.CompositionRoots container.Register(factory => factory.GetInstance().Content); container.Register(factory => factory.GetInstance().Templates); container.Register(factory => factory.GetInstance().RequestHandler); + container.Register(factory => UmbracoConfig.For.GlobalSettings()); // fixme - other sections we need to add? } diff --git a/src/Umbraco.Core/Composing/TypeLoader.cs b/src/Umbraco.Core/Composing/TypeLoader.cs index 9ca1b2fa1c..46157c1748 100644 --- a/src/Umbraco.Core/Composing/TypeLoader.cs +++ b/src/Umbraco.Core/Composing/TypeLoader.cs @@ -29,6 +29,7 @@ namespace Umbraco.Core.Composing private const string CacheKey = "umbraco-types.list"; private readonly IRuntimeCacheProvider _runtimeCache; + private readonly IGlobalSettings _globalSettings; private readonly ProfilingLogger _logger; private readonly object _typesLock = new object(); @@ -45,11 +46,13 @@ namespace Umbraco.Core.Composing /// Initializes a new instance of the class. /// /// The application runtime cache. + /// /// A profiling logger. /// Whether to detect changes using hashes. - internal TypeLoader(IRuntimeCacheProvider runtimeCache, ProfilingLogger logger, bool detectChanges = true) + internal TypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, ProfilingLogger logger, bool detectChanges = true) { _runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); + _globalSettings = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); if (detectChanges) @@ -354,17 +357,17 @@ namespace Umbraco.Core.Composing } // internal for tests - internal static string GetTypesListFilePath() => GetFileBasePath() + ".list"; + internal string GetTypesListFilePath() => GetFileBasePath() + ".list"; - private static string GetTypesHashFilePath() => GetFileBasePath() + ".hash"; + private string GetTypesHashFilePath() => GetFileBasePath() + ".hash"; - private static string GetFileBasePath() + private string GetFileBasePath() { - var localTempStorage = GlobalSettings.LocalTempStorageLocation; + var localTempStorage = _globalSettings.LocalTempStorageLocation; if (_localTempStorage != localTempStorage) { string path; - switch (GlobalSettings.LocalTempStorageLocation) + switch (_globalSettings.LocalTempStorageLocation) { case LocalTempStorage.AspNetTemp: path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types"); @@ -398,38 +401,38 @@ namespace Umbraco.Core.Composing return _fileBasePath; } - private static string GetFilePath(string extension) - { - string path; - switch (GlobalSettings.LocalTempStorageLocation) - { - case LocalTempStorage.AspNetTemp: - path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types." + extension); - break; - case LocalTempStorage.EnvironmentTemp: - // include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back - // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not - // utilizing an old path - assuming we cannot have SHA1 collisions on AppDomainAppId - var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1(); - var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", appDomainHash); - path = Path.Combine(cachePath, "umbraco-types." + extension); - break; - case LocalTempStorage.Default: - default: - var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/TypesCache"); - path = Path.Combine(tempFolder, "umbraco-types." + NetworkHelper.FileSafeMachineName + "." + extension); - break; - } + //private string GetFilePath(string extension) + //{ + // string path; + // switch (_globalSettings.LocalTempStorageLocation) + // { + // case LocalTempStorage.AspNetTemp: + // path = Path.Combine(HttpRuntime.CodegenDir, "UmbracoData", "umbraco-types." + extension); + // break; + // case LocalTempStorage.EnvironmentTemp: + // // include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back + // // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not + // // utilizing an old path - assuming we cannot have SHA1 collisions on AppDomainAppId + // var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1(); + // var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", appDomainHash); + // path = Path.Combine(cachePath, "umbraco-types." + extension); + // break; + // case LocalTempStorage.Default: + // default: + // var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/TypesCache"); + // path = Path.Combine(tempFolder, "umbraco-types." + NetworkHelper.FileSafeMachineName + "." + extension); + // break; + // } - // ensure that the folder exists - var directory = Path.GetDirectoryName(path); - if (directory == null) - throw new InvalidOperationException($"Could not determine folder for file \"{path}\"."); - if (Directory.Exists(directory) == false) - Directory.CreateDirectory(directory); + // // ensure that the folder exists + // var directory = Path.GetDirectoryName(path); + // if (directory == null) + // throw new InvalidOperationException($"Could not determine folder for file \"{path}\"."); + // if (Directory.Exists(directory) == false) + // Directory.CreateDirectory(directory); - return path; - } + // return path; + //} // internal for tests internal void WriteCache() diff --git a/src/Umbraco.Core/Configuration/GlobalSettings.cs b/src/Umbraco.Core/Configuration/GlobalSettings.cs index 060ecf5d17..5ce9dd0a35 100644 --- a/src/Umbraco.Core/Configuration/GlobalSettings.cs +++ b/src/Umbraco.Core/Configuration/GlobalSettings.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Configuration; using System.Web; using System.Web.Configuration; using System.Web.Hosting; -using System.Web.Routing; using System.Web.Security; using System.Xml; using System.Xml.Linq; @@ -18,36 +16,22 @@ using Umbraco.Core.Security; namespace Umbraco.Core.Configuration { - //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... - // we have this two tasks logged: - // http://issues.umbraco.org/issue/U4-58 - // http://issues.umbraco.org/issue/U4-115 - - // TODO: There's a current task and branch to refactor this into interfaces and proper config: http://issues.umbraco.org/issue/U4-8861 - // PR https://github.com/umbraco/Umbraco-CMS/compare/dev-v8...temp-U4-8861?expand=1 - //TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults! /// /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings /// - [Obsolete("TODO: Need to move this configuration class into the proper configuration accesors for v8!")] - public class GlobalSettings + public class GlobalSettings : IGlobalSettings { #region Private static fields - private static Version _version; - private static readonly object Locker = new object(); - //make this volatile so that we can ensure thread safety with a double check lock - private static volatile string _reservedUrlsCache; - private static string _reservedPathsCache; - private static HashSet _reservedList = new HashSet(); + private static string _reservedPaths; private static string _reservedUrls; //ensure the built on (non-changeable) reserved paths are there at all times - private const string StaticReservedPaths = "~/app_plugins/,~/install/,"; - private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,"; + internal const string StaticReservedPaths = "~/app_plugins/,~/install/,"; + internal const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,"; #endregion /// @@ -55,7 +39,7 @@ namespace Umbraco.Core.Configuration /// private static void ResetInternal() { - _reservedUrlsCache = null; + GlobalSettingsExtensions.Reset(); _reservedPaths = null; _reservedUrls = null; HasSmtpServer = null; @@ -69,7 +53,8 @@ namespace Umbraco.Core.Configuration { ResetInternal(); } - + + //fixme should this go on the interface or some other helper? public static bool HasSmtpServerConfigured(string appPath) { if (HasSmtpServer.HasValue) return HasSmtpServer.Value; @@ -93,15 +78,15 @@ namespace Umbraco.Core.Configuration /// Gets the reserved urls from web.config. /// /// The reserved urls. - public static string ReservedUrls + public string ReservedUrls { get - { + { if (_reservedUrls == null) { var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls") - ? ConfigurationManager.AppSettings["umbracoReservedUrls"] - : string.Empty; + ? ConfigurationManager.AppSettings["umbracoReservedUrls"] + : string.Empty; //ensure the built on (non-changeable) reserved paths are there at all times _reservedUrls = StaticReservedUrls + urls; @@ -115,7 +100,7 @@ namespace Umbraco.Core.Configuration /// Gets the reserved paths from web.config /// /// The reserved paths. - public static string ReservedPaths + public string ReservedPaths { get { @@ -137,7 +122,6 @@ namespace Umbraco.Core.Configuration } return _reservedPaths; } - internal set { _reservedPaths = value; } } /// @@ -147,7 +131,7 @@ namespace Umbraco.Core.Configuration /// /// Defaults to ~/App_Data/umbraco.config /// - public static string ContentXmlFile + public string ContentXmlFile { get { @@ -156,26 +140,12 @@ namespace Umbraco.Core.Configuration : "~/App_Data/umbraco.config"; } } - - /// - /// Gets the path to the storage directory (/data by default). - /// - /// The storage directory. - public static string StorageDirectory - { - get - { - return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory") - ? ConfigurationManager.AppSettings["umbracoStorageDirectory"] - : "~/App_Data"; - } - } - + /// /// Gets the path to umbraco's root directory (/umbraco by default). /// /// The path. - public static string Path + public string Path { get { @@ -183,56 +153,13 @@ namespace Umbraco.Core.Configuration ? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"]) : string.Empty; } - } - - /// - /// This returns the string of the MVC Area route. - /// - /// - /// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION - /// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY. - /// - /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... - /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin - /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. - /// - /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something - /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". - /// - public static string UmbracoMvcArea - { - get - { - if (Path.IsNullOrWhiteSpace()) - { - throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); - } - var path = Path; - if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518 - path = path.Substring(SystemDirectories.Root.Length); - return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); - } - } - - /// - /// Gets the path to umbraco's client directory (/umbraco_client by default). - /// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco' - /// folder since the CSS paths to images depend on it. - /// - /// The path. - public static string ClientPath - { - get - { - return Path + "/../umbraco_client"; - } - } + } /// /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. /// /// The configuration status. - public static string ConfigurationStatus + public string ConfigurationStatus { get { @@ -245,39 +172,7 @@ namespace Umbraco.Core.Configuration SaveSetting("umbracoConfigurationStatus", value); } } - - /// - /// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean - /// - /// The useLegacyEncoding status. - public static bool UmbracoMembershipProviderLegacyEncoding - { - get - { - return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName); - } - set - { - SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value); - } - } - - /// - /// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean - /// - /// The useLegacyEncoding status. - public static bool UmbracoUsersMembershipProviderLegacyEncoding - { - get - { - return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider); - } - set - { - SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value); - } - } - + /// /// Saves a setting into the configuration file. /// @@ -320,64 +215,15 @@ namespace Umbraco.Core.Configuration ConfigurationManager.RefreshSection("appSettings"); } } - - private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding) - { - //check if this can even be configured. - var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; - if (membershipProvider == null) - { - return; - } - if (membershipProvider.GetType().Namespace == "umbraco.providers.members") - { - //its the legacy one, this cannot be changed - return; - } - - var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); - var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace); - - var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList(); - - if (membershipConfigs.Any() == false) - return; - - var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName); - - if (provider == null) - return; - - provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding); - - webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting); - } - - private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName) - { - //check if this can even be configured. - var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; - if (membershipProvider == null) - { - return false; - } - - return membershipProvider.UseLegacyEncoding; - } - - /// - /// Gets the full path to root. - /// - /// The fullpath to root. - public static string FullpathToRoot - { - get { return IOHelper.GetRootDirectorySafe(); } - } + + [Obsolete("Use IOHelper.GetRootDirectorySafe() instead")] + public static string FullPathToRoot => IOHelper.GetRootDirectorySafe(); /// /// Gets a value indicating whether umbraco is running in [debug mode]. /// /// true if [debug mode]; otherwise, false. + //fixme surely thsi doesn't belong here and it's also a web request context thing public static bool DebugMode { get @@ -403,7 +249,7 @@ namespace Umbraco.Core.Configuration /// Gets the time out in minutes. /// /// The time out in minutes. - public static int TimeOutInMinutes + public int TimeOutInMinutes { get { @@ -422,7 +268,7 @@ namespace Umbraco.Core.Configuration /// Gets a value indicating whether umbraco uses directory urls. /// /// true if umbraco uses directory urls; otherwise, false. - public static bool UseDirectoryUrls + public bool UseDirectoryUrls { get { @@ -441,7 +287,7 @@ namespace Umbraco.Core.Configuration /// Returns a string value to determine if umbraco should skip version-checking. /// /// The version check period in days (0 = never). - public static int VersionCheckPeriod + public int VersionCheckPeriod { get { @@ -455,34 +301,14 @@ namespace Umbraco.Core.Configuration } } } - - /// - /// Returns a string value to determine if umbraco should disbable xslt extensions - /// - /// "true" if version xslt extensions are disabled, otherwise, "false" - [Obsolete("This is no longer used and will be removed from the codebase in future releases")] - public static string DisableXsltExtensions - { - get - { - return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions") - ? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"] - : "false"; - } - } - - internal static bool ContentCacheXmlStoredInCodeGen - { - get { return LocalTempStorageLocation == LocalTempStorage.AspNetTemp; } - } - + /// /// This is the location type to store temporary files such as cache files or other localized files for a given machine /// /// /// Currently used for the xml cache file and the plugin cache files /// - internal static LocalTempStorage LocalTempStorageLocation + public LocalTempStorage LocalTempStorageLocation { get { @@ -494,21 +320,12 @@ namespace Umbraco.Core.Configuration } } - /// - /// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor - /// - /// "true" if Xhtml mode is enable, otherwise, "false" - [Obsolete("This is no longer used and will be removed from the codebase in future releases")] - public static string EditXhtmlMode - { - get { return "true"; } - } - /// /// Gets the default UI language. /// /// The default UI language. - public static string DefaultUILanguage + // ReSharper disable once InconsistentNaming + public string DefaultUILanguage { get { @@ -518,28 +335,13 @@ namespace Umbraco.Core.Configuration } } - /// - /// Gets the profile URL. - /// - /// The profile URL. - public static string ProfileUrl - { - get - { - //the default will be 'profiler' - return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl") - ? ConfigurationManager.AppSettings["umbracoProfileUrl"] - : "profiler"; - } - } - /// /// 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 static bool HideTopLevelNodeFromPath + public bool HideTopLevelNodeFromPath { get { @@ -554,95 +356,16 @@ namespace Umbraco.Core.Configuration } } - /// - /// Gets the current version. - /// - /// The current version. - [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] - public static string CurrentVersion - { - get { return UmbracoVersion.SemanticVersion.ToSemanticString(); } - } - - /// - /// Gets the major version number. - /// - /// The major version number. - [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] - public static int VersionMajor - { - get - { - return UmbracoVersion.Current.Major; - } - } - - /// - /// Gets the minor version number. - /// - /// The minor version number. - [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] - public static int VersionMinor - { - get - { - return UmbracoVersion.Current.Minor; - } - } - - /// - /// Gets the patch version number. - /// - /// The patch version number. - [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] - public static int VersionPatch - { - get - { - return UmbracoVersion.Current.Build; - } - } - - /// - /// Gets the version comment (like beta or RC). - /// - /// The version comment. - [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] - public static string VersionComment - { - get - { - return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment; - } - } - - - /// - /// Requests the is in umbraco application directory structure. - /// - /// The context. - /// - public static bool RequestIsInUmbracoApplication(HttpContext context) - { - return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; - } - - public static bool RequestIsInUmbracoApplication(HttpContextBase context) - { - return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; - } - /// /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. /// - /// true if [use SSL]; otherwise, false. - public static bool UseSSL + public bool UseHttps { get { try { - return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]); + return bool.Parse(ConfigurationManager.AppSettings["umbracoUseHttps"]); } catch { @@ -651,131 +374,6 @@ namespace Umbraco.Core.Configuration } } - /// - /// Gets the umbraco license. - /// - /// The license. - public static string License - { - get - { - string license = - "the open source license MIT. The umbraco UI is freeware licensed under the umbraco license."; - - var versionDoc = new XmlDocument(); - var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml")); - versionDoc.Load(versionReader); - versionReader.Close(); - - // check for license - try - { - string licenseUrl = - versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value; - string licenseValidation = - versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value; - string licensedTo = - versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value; - - if (licensedTo != "" && licenseUrl != "") - { - license = "umbraco Commercial License
Registered to:
" + - licensedTo.Replace("\n", "
") + "
For use with domain:
" + - licenseUrl; - } - } - catch - { - } - - return license; - } - } - - /// - /// Determines whether the current request is reserved based on the route table and - /// whether the specified URL is reserved or is inside a reserved path. - /// - /// - /// - /// The route collection to lookup the request in - /// - public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes) - { - if (httpContext == null) throw new ArgumentNullException("httpContext"); - if (routes == null) throw new ArgumentNullException("routes"); - - //check if the current request matches a route, if so then it is reserved. - var route = routes.GetRouteData(httpContext); - if (route != null) - return true; - - //continue with the standard ignore routine - return IsReservedPathOrUrl(url); - } - - /// - /// Determines whether the specified URL is reserved or is inside a reserved path. - /// - /// The URL to check. - /// - /// true if the specified URL is reserved; otherwise, false. - /// - public static bool IsReservedPathOrUrl(string url) - { - if (_reservedUrlsCache == null) - { - lock (Locker) - { - if (_reservedUrlsCache == null) - { - // store references to strings to determine changes - _reservedPathsCache = GlobalSettings.ReservedPaths; - _reservedUrlsCache = GlobalSettings.ReservedUrls; - - // add URLs and paths to a new list - var newReservedList = new HashSet(); - foreach (var reservedUrlTrimmed in _reservedUrlsCache - .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) - .Select(x => x.Trim().ToLowerInvariant()) - .Where(x => x.IsNullOrWhiteSpace() == false) - .Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/")) - .Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false)) - { - newReservedList.Add(reservedUrlTrimmed); - } - - foreach (var reservedPathTrimmed in _reservedPathsCache - .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) - .Select(x => x.Trim().ToLowerInvariant()) - .Where(x => x.IsNullOrWhiteSpace() == false) - .Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/")) - .Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false)) - { - newReservedList.Add(reservedPathTrimmed); - } - - // use the new list from now on - _reservedList = newReservedList; - } - } - } - - //The url should be cleaned up before checking: - // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' - // * We shouldn't be comparing the query at all - var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); - if (pathPart.Contains(".") == false) - { - pathPart = pathPart.EnsureEndsWith('/'); - } - - // return true if url starts with an element of the reserved list - return _reservedList.Any(x => pathPart.InvariantStartsWith(x)); - } - - - } diff --git a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs new file mode 100644 index 0000000000..1e37ae0668 --- /dev/null +++ b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Routing; +using Umbraco.Core.IO; + +namespace Umbraco.Core.Configuration +{ + public static class GlobalSettingsExtensions + { + /// + /// Used in unit testing to reset all config items, this is automatically called by GlobalSettings.Reset() + /// + internal static void Reset() + { + _reservedUrlsCache = null; + _mvcArea = null; + } + + private static readonly object Locker = new object(); + //make this volatile so that we can ensure thread safety with a double check lock + private static volatile string _reservedUrlsCache; + private static string _reservedPathsCache; + private static HashSet _reservedList = new HashSet(); + private static string _mvcArea; + + /// + /// This returns the string of the MVC Area route. + /// + /// + /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... + /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin + /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. + /// + /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something + /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". + /// + public static string GetUmbracoMvcArea(this IGlobalSettings globalSettings) + { + if (_mvcArea != null) return _mvcArea; + + if (globalSettings.Path.IsNullOrWhiteSpace()) + { + throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); + } + + var path = globalSettings.Path; + if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518 + path = path.Substring(SystemDirectories.Root.Length); + _mvcArea = path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); + return _mvcArea; + } + + /// + /// Determines whether the specified URL is reserved or is inside a reserved path. + /// + /// + /// The URL to check. + /// + /// true if the specified URL is reserved; otherwise, false. + /// + internal static bool IsReservedPathOrUrl(this IGlobalSettings globalSettings, string url) + { + if (_reservedUrlsCache == null) + { + lock (Locker) + { + if (_reservedUrlsCache == null) + { + // store references to strings to determine changes + _reservedPathsCache = globalSettings.ReservedPaths; + _reservedUrlsCache = globalSettings.ReservedUrls; + + // add URLs and paths to a new list + var newReservedList = new HashSet(); + foreach (var reservedUrlTrimmed in _reservedUrlsCache + .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim().ToLowerInvariant()) + .Where(x => x.IsNullOrWhiteSpace() == false) + .Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/")) + .Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false)) + { + newReservedList.Add(reservedUrlTrimmed); + } + + foreach (var reservedPathTrimmed in _reservedPathsCache + .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim().ToLowerInvariant()) + .Where(x => x.IsNullOrWhiteSpace() == false) + .Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/")) + .Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false)) + { + newReservedList.Add(reservedPathTrimmed); + } + + // use the new list from now on + _reservedList = newReservedList; + } + } + } + + //The url should be cleaned up before checking: + // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' + // * We shouldn't be comparing the query at all + var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); + if (pathPart.Contains(".") == false) + { + pathPart = pathPart.EnsureEndsWith('/'); + } + + // return true if url starts with an element of the reserved list + return _reservedList.Any(x => pathPart.InvariantStartsWith(x)); + } + + /// + /// Determines whether the current request is reserved based on the route table and + /// whether the specified URL is reserved or is inside a reserved path. + /// + /// + /// + /// + /// The route collection to lookup the request in + /// + internal static bool IsReservedPathOrUrl(this IGlobalSettings globalSettings, string url, HttpContextBase httpContext, RouteCollection routes) + { + if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); + if (routes == null) throw new ArgumentNullException(nameof(routes)); + + //check if the current request matches a route, if so then it is reserved. + var route = routes.GetRouteData(httpContext); + if (route != null) + return true; + + //continue with the standard ignore routine + return globalSettings.IsReservedPathOrUrl(url); + } + + + } +} diff --git a/src/Umbraco.Core/Configuration/IGlobalSettings.cs b/src/Umbraco.Core/Configuration/IGlobalSettings.cs new file mode 100644 index 0000000000..cf9478d30a --- /dev/null +++ b/src/Umbraco.Core/Configuration/IGlobalSettings.cs @@ -0,0 +1,84 @@ +namespace Umbraco.Core.Configuration +{ + /// + /// Contains general settings information for the entire Umbraco instance based on information from web.config appsettings + /// + public interface IGlobalSettings + { + /// + /// 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 name of the content XML file. + /// + /// The content XML. + /// + /// Defaults to ~/App_Data/umbraco.config + /// + string ContentXmlFile { get; } + + /// + /// Gets the path to umbraco's root directory (/umbraco by default). + /// + string Path { 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 a value indicating whether umbraco uses directory urls. + /// + /// true if umbraco uses directory urls; otherwise, false. + bool UseDirectoryUrls { 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; } + + /// + /// This is the location type to store temporary files such as cache files or other localized files for a given machine + /// + /// + /// Used for some cache files and for specific environments such as Azure + /// + LocalTempStorage LocalTempStorageLocation { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/LocalTempStorage.cs b/src/Umbraco.Core/Configuration/LocalTempStorage.cs index 1231ee7156..0013fb68e4 100644 --- a/src/Umbraco.Core/Configuration/LocalTempStorage.cs +++ b/src/Umbraco.Core/Configuration/LocalTempStorage.cs @@ -1,6 +1,6 @@ namespace Umbraco.Core.Configuration { - internal enum LocalTempStorage + public enum LocalTempStorage { Unknown = 0, Default, diff --git a/src/Umbraco.Core/Configuration/UmbracoConfig.cs b/src/Umbraco.Core/Configuration/UmbracoConfig.cs index 6daa9f6f6f..f16faab06e 100644 --- a/src/Umbraco.Core/Configuration/UmbracoConfig.cs +++ b/src/Umbraco.Core/Configuration/UmbracoConfig.cs @@ -65,17 +65,20 @@ namespace Umbraco.Core.Configuration /// /// /// - public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks) + /// + public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks, IGlobalSettings globalSettings) { SetHealthCheckSettings(healthChecks); SetUmbracoSettings(umbracoSettings); SetDashboardSettings(dashboardSettings); + SetGlobalConfig(globalSettings); } private IHealthChecks _healthChecks; private IDashboardSection _dashboardSection; private IUmbracoSettingsSection _umbracoSettings; private IGridConfig _gridConfig; + private IGlobalSettings _globalSettings; /// /// Gets the IHealthCheck config @@ -134,6 +137,23 @@ namespace Umbraco.Core.Configuration _umbracoSettings = value; } + /// + /// Only for testing + /// + /// + public void SetGlobalConfig(IGlobalSettings value) + { + _globalSettings = value; + } + + /// + /// Gets the IGlobalSettings + /// + public IGlobalSettings GlobalSettings() + { + return _globalSettings ?? (_globalSettings = new GlobalSettings()); + } + /// /// Gets the IUmbracoSettings /// diff --git a/src/Umbraco.Core/Constants-Web.cs b/src/Umbraco.Core/Constants-Web.cs index ec06b742da..a5f140ddba 100644 --- a/src/Umbraco.Core/Constants-Web.cs +++ b/src/Umbraco.Core/Constants-Web.cs @@ -21,6 +21,8 @@ namespace Umbraco.Core /// public const string PreviewCookieName = "UMB_PREVIEW"; + public const string InstallerCookieName = "umb_installId"; + /// /// The auth cookie name /// diff --git a/src/Umbraco.Core/IO/SystemDirectories.cs b/src/Umbraco.Core/IO/SystemDirectories.cs index d9f0eba841..7d3bfd3ae0 100644 --- a/src/Umbraco.Core/IO/SystemDirectories.cs +++ b/src/Umbraco.Core/IO/SystemDirectories.cs @@ -1,4 +1,5 @@ -using System.Web; +using System; +using System.Web; namespace Umbraco.Core.IO { @@ -66,9 +67,11 @@ namespace Umbraco.Core.IO if (_root != null) return _root; var appPath = HttpRuntime.AppDomainAppVirtualPath; - if (appPath == "/") appPath = string.Empty; + // ReSharper disable once ConditionIsAlwaysTrueOrFalse + if (appPath == null || appPath == "/") appPath = string.Empty; _root = appPath; + return _root; } //Only required for unit tests diff --git a/src/Umbraco.Core/IO/SystemFiles.cs b/src/Umbraco.Core/IO/SystemFiles.cs index 20b7bf6a3e..a0ca748cd6 100644 --- a/src/Umbraco.Core/IO/SystemFiles.cs +++ b/src/Umbraco.Core/IO/SystemFiles.cs @@ -18,27 +18,24 @@ namespace Umbraco.Core.IO public static string FeedProxyConfig => string.Concat(SystemDirectories.Config, "/feedProxy.config"); // fixme - kill - public static string ContentCacheXml + public static string GetContentCacheXml(IGlobalSettings globalSettings) { - get + switch (globalSettings.LocalTempStorageLocation) { - switch (GlobalSettings.LocalTempStorageLocation) - { - case LocalTempStorage.AspNetTemp: - return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config"); - case LocalTempStorage.EnvironmentTemp: - var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1(); - var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", - //include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back - // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not - // utilizing an old path - appDomainHash); - return Path.Combine(cachePath, "umbraco.config"); - case LocalTempStorage.Default: - return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config"); - default: - throw new ArgumentOutOfRangeException(); - } + case LocalTempStorage.AspNetTemp: + return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config"); + case LocalTempStorage.EnvironmentTemp: + var appDomainHash = HttpRuntime.AppDomainAppId.ToSHA1(); + var cachePath = Path.Combine(Environment.ExpandEnvironmentVariables("%temp%"), "UmbracoData", + //include the appdomain hash is just a safety check, for example if a website is moved from worker A to worker B and then back + // to worker A again, in theory the %temp% folder should already be empty but we really want to make sure that its not + // utilizing an old path + appDomainHash); + return Path.Combine(cachePath, "umbraco.config"); + case LocalTempStorage.Default: + return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config"); + default: + throw new ArgumentOutOfRangeException(); } } } diff --git a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs index a4a4097e36..a3fd35df44 100644 --- a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs @@ -24,6 +24,7 @@ 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; @@ -32,9 +33,10 @@ namespace Umbraco.Core.Migrations.Install private DatabaseSchemaResult _databaseSchemaValidationResult; - public DatabaseBuilder(IScopeProvider scopeProvider, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, PostMigrationCollection postMigrations) + public DatabaseBuilder(IScopeProvider scopeProvider, IGlobalSettings globalSettings, IUmbracoDatabaseFactory databaseFactory, IRuntimeState runtime, ILogger logger, IMigrationBuilder migrationBuilder, IKeyValueService keyValueService, PostMigrationCollection postMigrations) { _scopeProvider = scopeProvider; + _globalSettings = globalSettings; _databaseFactory = databaseFactory; _runtime = runtime; _logger = logger; @@ -132,7 +134,7 @@ namespace Umbraco.Core.Migrations.Install { SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe, logger); - var path = Path.Combine(GlobalSettings.FullpathToRoot, "App_Data", "Umbraco.sdf"); + var path = Path.Combine(GlobalSettings.FullPathToRoot, "App_Data", "Umbraco.sdf"); if (File.Exists(path) == false) { // this should probably be in a "using (new SqlCeEngine)" clause but not sure @@ -488,7 +490,7 @@ namespace Umbraco.Core.Migrations.Install var installedSchemaVersion = schemaResult.DetermineInstalledVersion(); //If Configuration Status is empty and the determined version is "empty" its a new install - otherwise upgrade the existing - if (string.IsNullOrEmpty(GlobalSettings.ConfigurationStatus) && installedSchemaVersion.Equals(new Version(0, 0, 0))) + if (string.IsNullOrEmpty(_globalSettings.ConfigurationStatus) && installedSchemaVersion.Equals(new Version(0, 0, 0))) { if (_runtime.Level == RuntimeLevel.Run) throw new Exception("Umbraco is already configured!"); diff --git a/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs b/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs index bd4905729d..75ed8238d0 100644 --- a/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Reflection; using System.Security.Claims; using System.Threading.Tasks; +using Umbraco.Core.Configuration; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; using Umbraco.Core.Security; @@ -64,7 +65,7 @@ namespace Umbraco.Core.Models.Identity _startContentIds = new int[] { }; _groups = new IReadOnlyUserGroup[] { }; _allowedSections = new string[] { }; - _culture = Configuration.GlobalSettings.DefaultUILanguage; + _culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? _groups = new IReadOnlyUserGroup[0]; _roles = new ObservableCollection>(); _roles.CollectionChanged += _roles_CollectionChanged; @@ -81,7 +82,7 @@ namespace Umbraco.Core.Models.Identity _startContentIds = new int[] { }; _groups = new IReadOnlyUserGroup[] { }; _allowedSections = new string[] { }; - _culture = Configuration.GlobalSettings.DefaultUILanguage; + _culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? _groups = groups.ToArray(); _roles = new ObservableCollection>(_groups.Select(x => new IdentityUserRole { diff --git a/src/Umbraco.Core/Models/Identity/IdentityProfile.cs b/src/Umbraco.Core/Models/Identity/IdentityProfile.cs index eef2a17aa5..f44003b62a 100644 --- a/src/Umbraco.Core/Models/Identity/IdentityProfile.cs +++ b/src/Umbraco.Core/Models/Identity/IdentityProfile.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using AutoMapper; +using Umbraco.Core.Configuration; using Umbraco.Core.Models.Membership; using Umbraco.Core.Security; using Umbraco.Core.Services; @@ -9,7 +10,7 @@ namespace Umbraco.Core.Models.Identity { public class IdentityProfile : Profile { - public IdentityProfile(ILocalizedTextService textService, IEntityService entityService) + public IdentityProfile(ILocalizedTextService textService, IEntityService entityService, IGlobalSettings globalSettings) { CreateMap() .BeforeMap((src, dest) => @@ -25,7 +26,7 @@ namespace Umbraco.Core.Models.Identity .ForMember(dest => dest.IsApproved, opt => opt.MapFrom(src => src.IsApproved)) .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.Username)) .ForMember(dest => dest.PasswordHash, opt => opt.MapFrom(user => GetPasswordHash(user.RawPasswordValue))) - .ForMember(dest => dest.Culture, opt => opt.MapFrom(src => src.GetUserCulture(textService))) + .ForMember(dest => dest.Culture, opt => opt.MapFrom(src => src.GetUserCulture(textService, globalSettings))) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name)) .ForMember(dest => dest.StartMediaIds, opt => opt.MapFrom(src => src.StartMediaIds)) .ForMember(dest => dest.StartContentIds, opt => opt.MapFrom(src => src.StartContentIds)) diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 2dd750a353..0e3ab70e0a 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -27,7 +27,7 @@ namespace Umbraco.Core.Models.Membership { SessionTimeout = 60; _userGroups = new HashSet(); - _language = GlobalSettings.DefaultUILanguage; + _language = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? _isApproved = true; _isLockedOut = false; _startContentIds = new int[] { }; diff --git a/src/Umbraco.Core/Models/UserExtensions.cs b/src/Umbraco.Core/Models/UserExtensions.cs index f66f0b4ef7..f78de43f01 100644 --- a/src/Umbraco.Core/Models/UserExtensions.cs +++ b/src/Umbraco.Core/Models/UserExtensions.cs @@ -126,15 +126,16 @@ namespace Umbraco.Core.Models /// /// /// + /// /// - public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService) + public static CultureInfo GetUserCulture(this IUser user, ILocalizedTextService textService, IGlobalSettings globalSettings) { if (user == null) throw new ArgumentNullException(nameof(user)); if (textService == null) throw new ArgumentNullException(nameof(textService)); - return GetUserCulture(user.Language, textService); + return GetUserCulture(user.Language, textService, globalSettings); } - internal static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService) + internal static CultureInfo GetUserCulture(string userLanguage, ILocalizedTextService textService, IGlobalSettings globalSettings) { try { @@ -148,7 +149,7 @@ namespace Umbraco.Core.Models catch (CultureNotFoundException) { //return the default one - return CultureInfo.GetCultureInfo(GlobalSettings.DefaultUILanguage); + return CultureInfo.GetCultureInfo(globalSettings.DefaultUILanguage); } } diff --git a/src/Umbraco.Core/Packaging/PackageInstallation.cs b/src/Umbraco.Core/Packaging/PackageInstallation.cs index 9a62fe8b9a..2e33bfbf2b 100644 --- a/src/Umbraco.Core/Packaging/PackageInstallation.cs +++ b/src/Umbraco.Core/Packaging/PackageInstallation.cs @@ -25,7 +25,7 @@ namespace Umbraco.Core.Packaging public PackageInstallation(IPackagingService packagingService, IMacroService macroService, IFileService fileService, IPackageExtraction packageExtraction) - : this(packagingService, macroService, fileService, packageExtraction, GlobalSettings.FullpathToRoot) + : this(packagingService, macroService, fileService, packageExtraction, GlobalSettings.FullPathToRoot) {} public PackageInstallation(IPackagingService packagingService, IMacroService macroService, diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs index 636c9fda69..05fe456bbd 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs @@ -27,29 +27,33 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class UserRepository : NPocoRepositoryBase, IUserRepository { private readonly IMapperCollection _mapperCollection; + private readonly IGlobalSettings _globalSettings; private string _passwordConfigJson; private bool _passwordConfigInitialized; /// /// Constructor /// - /// + /// /// /// - /// + /// /// 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, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection) + /// + public UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IGlobalSettings globalSettings) : base(scopeAccessor, cacheHelper, logger) { _mapperCollection = mapperCollection; + _globalSettings = globalSettings; } // for tests - internal UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IDictionary passwordConfig) + internal UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IDictionary passwordConfig, IGlobalSettings globalSettings) : base(scopeAccessor, cacheHelper, logger) { _mapperCollection = mapperCollection; + _globalSettings = globalSettings; _passwordConfigJson = JsonConvert.SerializeObject(passwordConfig); _passwordConfigInitialized = true; } @@ -192,7 +196,7 @@ ORDER BY colName"; return false; //now detect if there's been a timeout - if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes)) + if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(_globalSettings.TimeOutInMinutes)) { //timeout detected, update the record ClearLoginSession(sessionId); diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index 731f84e20f..35ac5aff86 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -7,6 +7,7 @@ using LightInject; using Umbraco.Core.Cache; using Umbraco.Core.Components; using Umbraco.Core.Composing; +using Umbraco.Core.Composing.CompositionRoots; using Umbraco.Core.Configuration; using Umbraco.Core.Exceptions; using Umbraco.Core.IO; @@ -194,6 +195,8 @@ namespace Umbraco.Core.Runtime container.RegisterSingleton(); container.RegisterSingleton(); + container.RegisterFrom(); + // register caches // need the deep clone runtime cache profiver to ensure entities are cached properly, ie // are cloned in and cloned out - no request-based cache here since no web-based context, @@ -206,7 +209,7 @@ namespace Umbraco.Core.Runtime container.RegisterSingleton(f => f.GetInstance().RuntimeCache); // register the plugin manager - container.RegisterSingleton(f => new TypeLoader(f.GetInstance(), f.GetInstance())); + container.RegisterSingleton(f => new TypeLoader(f.GetInstance(), f.GetInstance(), f.GetInstance())); // register syntax providers - required by database factory container.Register("MySqlSyntaxProvider"); diff --git a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs index 6a5a3f4dc0..eeacba2b7c 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs @@ -35,7 +35,6 @@ namespace Umbraco.Core.Runtime base.Compose(composition); // register from roots - composition.Container.RegisterFrom(); composition.Container.RegisterFrom(); composition.Container.RegisterFrom(); composition.Container.RegisterFrom(); @@ -78,7 +77,7 @@ namespace Umbraco.Core.Runtime composition.Container.RegisterSingleton(f => { if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled) - return new ConfigServerRegistrar(UmbracoConfig.For.UmbracoSettings(), f.GetInstance()); + return new ConfigServerRegistrar(f.GetInstance(), f.GetInstance(), f.GetInstance()); if ("true".InvariantEquals(ConfigurationManager.AppSettings["umbracoDisableElectionForSingleServer"])) return new SingleServerRegistrar(f.GetInstance()); return new DatabaseServerRegistrar( @@ -94,8 +93,8 @@ namespace Umbraco.Core.Runtime factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), - factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), true, new DatabaseServerMessengerOptions())); composition.Container.RegisterCollectionBuilder() diff --git a/src/Umbraco.Core/RuntimeState.cs b/src/Umbraco.Core/RuntimeState.cs index d740352649..a1401e035a 100644 --- a/src/Umbraco.Core/RuntimeState.cs +++ b/src/Umbraco.Core/RuntimeState.cs @@ -103,14 +103,15 @@ namespace Umbraco.Core /// /// Ensures that the property has a value. /// + /// /// /// - internal void EnsureApplicationUrl(HttpRequestBase request = null, IUmbracoSettingsSection settings = null) + internal void EnsureApplicationUrl(IUmbracoSettingsSection settings, IGlobalSettings globalSettings, HttpRequestBase request = null) { // see U4-10626 - in some cases we want to reset the application url // (this is a simplified version of what was in 7.x) // note: should this be optional? is it expensive? - var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request); + var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request, globalSettings); var change = url != null && !_applicationUrls.Contains(url); if (change) { @@ -119,7 +120,7 @@ namespace Umbraco.Core } if (ApplicationUrl != null && !change) return; - ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, request, settings)); + ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, globalSettings, settings, request)); } private readonly ManualResetEventSlim _runLevel = new ManualResetEventSlim(false); diff --git a/src/Umbraco.Core/Security/BackOfficeCookieAuthenticationProvider.cs b/src/Umbraco.Core/Security/BackOfficeCookieAuthenticationProvider.cs index a52f720b53..4d6a4fdaeb 100644 --- a/src/Umbraco.Core/Security/BackOfficeCookieAuthenticationProvider.cs +++ b/src/Umbraco.Core/Security/BackOfficeCookieAuthenticationProvider.cs @@ -16,9 +16,16 @@ namespace Umbraco.Core.Security { public class BackOfficeCookieAuthenticationProvider : CookieAuthenticationProvider { - // fixme inject - private IUserService UserService => Current.Services.UserService; - private IRuntimeState RuntimeState => Current.RuntimeState; + private readonly IUserService _userService; + private readonly IRuntimeState _runtimeState; + private readonly IGlobalSettings _globalSettings; + + public BackOfficeCookieAuthenticationProvider(IUserService userService, IRuntimeState runtimeState, IGlobalSettings globalSettings) + { + _userService = userService; + _runtimeState = runtimeState; + _globalSettings = globalSettings; + } public override void ResponseSignIn(CookieResponseSignInContext context) { @@ -27,8 +34,8 @@ namespace Umbraco.Core.Security //generate a session id and assign it //create a session token - if we are configured and not in an upgrade state then use the db, otherwise just generate one - var session = RuntimeState.Level == RuntimeLevel.Run - ? UserService.CreateLoginSession(backOfficeIdentity.Id, context.OwinContext.GetCurrentRequestIpAddress()) + var session = _runtimeState.Level == RuntimeLevel.Run + ? _userService.CreateLoginSession(backOfficeIdentity.Id, context.OwinContext.GetCurrentRequestIpAddress()) : Guid.NewGuid(); backOfficeIdentity.SessionId = session.ToString(); @@ -46,7 +53,7 @@ namespace Umbraco.Core.Security var sessionId = claimsIdentity.FindFirstValue(Constants.Security.SessionIdClaimType); if (sessionId.IsNullOrWhiteSpace() == false && Guid.TryParse(sessionId, out var guidSession)) { - UserService.ClearLoginSession(guidSession); + _userService.ClearLoginSession(guidSession); } } @@ -96,10 +103,10 @@ namespace Umbraco.Core.Security /// /// So that we are not overloading the database this throttles it's check to every minute /// - protected virtual async Task EnsureValidSessionId(CookieValidateIdentityContext context) + protected virtual async Task EnsureValidSessionId(CookieValidateIdentityContext context) { - if (RuntimeState.Level == RuntimeLevel.Run) - await SessionIdValidator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context); + if (_runtimeState.Level == RuntimeLevel.Run) + await SessionIdValidator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context, _globalSettings); } diff --git a/src/Umbraco.Core/Security/BackOfficeSignInManager.cs b/src/Umbraco.Core/Security/BackOfficeSignInManager.cs index 0362ab00b8..d156871697 100644 --- a/src/Umbraco.Core/Security/BackOfficeSignInManager.cs +++ b/src/Umbraco.Core/Security/BackOfficeSignInManager.cs @@ -17,14 +17,16 @@ namespace Umbraco.Core.Security { private readonly ILogger _logger; private readonly IOwinRequest _request; + private readonly IGlobalSettings _globalSettings; - public BackOfficeSignInManager(UserManager userManager, IAuthenticationManager authenticationManager, ILogger logger, IOwinRequest request) + public BackOfficeSignInManager(UserManager userManager, IAuthenticationManager authenticationManager, ILogger logger, IGlobalSettings globalSettings, IOwinRequest request) : base(userManager, authenticationManager) { if (logger == null) throw new ArgumentNullException("logger"); if (request == null) throw new ArgumentNullException("request"); _logger = logger; _request = request; + _globalSettings = globalSettings; AuthenticationType = Constants.Security.BackOfficeAuthenticationType; } @@ -33,12 +35,13 @@ namespace Umbraco.Core.Security return user.GenerateUserIdentityAsync((BackOfficeUserManager)UserManager); } - public static BackOfficeSignInManager Create(IdentityFactoryOptions options, IOwinContext context, ILogger logger) + public static BackOfficeSignInManager Create(IdentityFactoryOptions options, IOwinContext context, IGlobalSettings globalSettings, ILogger logger) { return new BackOfficeSignInManager( context.GetBackOfficeUserManager(), context.Authentication, logger, + globalSettings, context.Request); } @@ -55,31 +58,19 @@ namespace Umbraco.Core.Security { case SignInStatus.Success: _logger.WriteCore(TraceEventType.Information, 0, - string.Format( - "User: {0} logged in from IP address {1}", - userName, - _request.RemoteIpAddress), null, null); + $"User: {userName} logged in from IP address {_request.RemoteIpAddress}", null, null); break; case SignInStatus.LockedOut: _logger.WriteCore(TraceEventType.Information, 0, - string.Format( - "Login attempt failed for username {0} from IP address {1}, the user is locked", - userName, - _request.RemoteIpAddress), null, null); + $"Login attempt failed for username {userName} from IP address {_request.RemoteIpAddress}, the user is locked", null, null); break; case SignInStatus.RequiresVerification: _logger.WriteCore(TraceEventType.Information, 0, - string.Format( - "Login attempt requires verification for username {0} from IP address {1}", - userName, - _request.RemoteIpAddress), null, null); + $"Login attempt requires verification for username {userName} from IP address {_request.RemoteIpAddress}", null, null); break; case SignInStatus.Failure: _logger.WriteCore(TraceEventType.Information, 0, - string.Format( - "Login attempt failed for username {0} from IP address {1}", - userName, - _request.RemoteIpAddress), null, null); + $"Login attempt failed for username {userName} from IP address {_request.RemoteIpAddress}", null, null); break; default: throw new ArgumentOutOfRangeException(); @@ -107,7 +98,7 @@ namespace Umbraco.Core.Security //if the user is null, create an empty one which can be used for auto-linking if (user == null) - user = BackOfficeIdentityUser.CreateNew(userName, null, GlobalSettings.DefaultUILanguage); + user = BackOfficeIdentityUser.CreateNew(userName, null, _globalSettings.DefaultUILanguage); //check the password for the user, this will allow a developer to auto-link //an account if they have specified an IBackOfficeUserPasswordChecker @@ -202,7 +193,7 @@ namespace Umbraco.Core.Security IsPersistent = isPersistent, AllowRefresh = true, IssuedUtc = nowUtc, - ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes) + ExpiresUtc = nowUtc.AddMinutes(_globalSettings.TimeOutInMinutes) }, userIdentity, rememberBrowserIdentity); } else @@ -212,7 +203,7 @@ namespace Umbraco.Core.Security IsPersistent = isPersistent, AllowRefresh = true, IssuedUtc = nowUtc, - ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes) + ExpiresUtc = nowUtc.AddMinutes(_globalSettings.TimeOutInMinutes) }, userIdentity); } diff --git a/src/Umbraco.Core/Security/BackOfficeUserManager.cs b/src/Umbraco.Core/Security/BackOfficeUserManager.cs index 4c651e9432..8324ec11a0 100644 --- a/src/Umbraco.Core/Security/BackOfficeUserManager.cs +++ b/src/Umbraco.Core/Security/BackOfficeUserManager.cs @@ -54,6 +54,7 @@ namespace Umbraco.Core.Security /// /// /// + /// /// public static BackOfficeUserManager Create( IdentityFactoryOptions options, @@ -62,14 +63,16 @@ namespace Umbraco.Core.Security IEntityService entityService, IExternalLoginService externalLoginService, MembershipProviderBase membershipProvider, - IContentSection contentSectionConfig) + IContentSection contentSectionConfig, + IGlobalSettings globalSettings) { if (options == null) throw new ArgumentNullException("options"); if (userService == null) throw new ArgumentNullException("userService"); if (memberTypeService == null) throw new ArgumentNullException("memberTypeService"); if (externalLoginService == null) throw new ArgumentNullException("externalLoginService"); - var manager = new BackOfficeUserManager(new BackOfficeUserStore(userService, memberTypeService, entityService, externalLoginService, membershipProvider)); + var manager = new BackOfficeUserManager( + new BackOfficeUserStore(userService, memberTypeService, entityService, externalLoginService, globalSettings, membershipProvider)); manager.InitUserManager(manager, membershipProvider, contentSectionConfig, options); return manager; } diff --git a/src/Umbraco.Core/Security/BackOfficeUserStore.cs b/src/Umbraco.Core/Security/BackOfficeUserStore.cs index dc6a939c65..2f70f32d89 100644 --- a/src/Umbraco.Core/Security/BackOfficeUserStore.cs +++ b/src/Umbraco.Core/Security/BackOfficeUserStore.cs @@ -8,6 +8,7 @@ using System.Web.Security; using AutoMapper; using Microsoft.AspNet.Identity; using Microsoft.Owin; +using Umbraco.Core.Configuration; using Umbraco.Core.Exceptions; using Umbraco.Core.Models; using Umbraco.Core.Models.Identity; @@ -38,14 +39,16 @@ namespace Umbraco.Core.Security private readonly IMemberTypeService _memberTypeService; private readonly IEntityService _entityService; private readonly IExternalLoginService _externalLoginService; + private readonly IGlobalSettings _globalSettings; private bool _disposed = false; - public BackOfficeUserStore(IUserService userService, IMemberTypeService memberTypeService, IEntityService entityService, IExternalLoginService externalLoginService, MembershipProviderBase usersMembershipProvider) + public BackOfficeUserStore(IUserService userService, IMemberTypeService memberTypeService, IEntityService entityService, IExternalLoginService externalLoginService, IGlobalSettings globalSettings, MembershipProviderBase usersMembershipProvider) { _userService = userService; _memberTypeService = memberTypeService; _entityService = entityService; _externalLoginService = externalLoginService; + _globalSettings = globalSettings; if (userService == null) throw new ArgumentNullException("userService"); if (usersMembershipProvider == null) throw new ArgumentNullException("usersMembershipProvider"); if (externalLoginService == null) throw new ArgumentNullException("externalLoginService"); @@ -88,7 +91,7 @@ namespace Umbraco.Core.Security var userEntity = new User(user.Name, user.Email, user.UserName, emptyPasswordValue) { DefaultToLiveEditing = false, - Language = user.Culture ?? Configuration.GlobalSettings.DefaultUILanguage, + Language = user.Culture ?? _globalSettings.DefaultUILanguage, StartContentIds = user.StartContentIds ?? new int[] { }, StartMediaIds = user.StartMediaIds ?? new int[] { }, IsLockedOut = user.IsLockedOut, diff --git a/src/Umbraco.Core/Security/SessionIdValidator.cs b/src/Umbraco.Core/Security/SessionIdValidator.cs index 1737baa778..f738ad9c22 100644 --- a/src/Umbraco.Core/Security/SessionIdValidator.cs +++ b/src/Umbraco.Core/Security/SessionIdValidator.cs @@ -28,12 +28,12 @@ namespace Umbraco.Core.Security { public const string CookieName = "UMB_UCONTEXT_C"; - public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context) + public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context, IGlobalSettings globalSettings) { - if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false) + if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, globalSettings) == false) return; - var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity); + var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity, globalSettings); if (valid == false) { @@ -48,7 +48,8 @@ namespace Umbraco.Core.Security ICookieManager cookieManager, ISystemClock systemClock, DateTimeOffset? authTicketIssueDate, - ClaimsIdentity currentIdentity) + ClaimsIdentity currentIdentity, + IGlobalSettings globalSettings) { if (owinCtx == null) throw new ArgumentNullException("owinCtx"); if (cookieManager == null) throw new ArgumentNullException("cookieManager"); @@ -107,7 +108,7 @@ namespace Umbraco.Core.Security new CookieOptions { HttpOnly = true, - Secure = GlobalSettings.UseSSL || owinCtx.Request.IsSecure, + Secure = globalSettings.UseHttps || owinCtx.Request.IsSecure, Path = "/" }); @@ -115,4 +116,4 @@ namespace Umbraco.Core.Security } } -} \ No newline at end of file +} diff --git a/src/Umbraco.Core/Services/Implement/NotificationService.cs b/src/Umbraco.Core/Services/Implement/NotificationService.cs index 0b57958724..b65218409a 100644 --- a/src/Umbraco.Core/Services/Implement/NotificationService.cs +++ b/src/Umbraco.Core/Services/Implement/NotificationService.cs @@ -25,12 +25,14 @@ namespace Umbraco.Core.Services.Implement private readonly IUserService _userService; private readonly IContentService _contentService; private readonly INotificationsRepository _notificationsRepository; + private readonly IGlobalSettings _globalSettings; private readonly ILogger _logger; public NotificationService(IScopeProvider provider, IUserService userService, IContentService contentService, ILogger logger, - INotificationsRepository notificationsRepository) + INotificationsRepository notificationsRepository, IGlobalSettings globalSettings) { _notificationsRepository = notificationsRepository; + _globalSettings = globalSettings; _uowProvider = provider ?? throw new ArgumentNullException(nameof(provider)); _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _contentService = contentService ?? throw new ArgumentNullException(nameof(contentService)); @@ -425,7 +427,7 @@ namespace Umbraco.Core.Services.Implement " "); } - string protocol = GlobalSettings.UseSSL ? "https" : "http"; + string protocol = _globalSettings.UseHttps ? "https" : "http"; string[] subjectVars = { @@ -471,7 +473,7 @@ namespace Umbraco.Core.Services.Implement // nh, issue 30724. Due to hardcoded http strings in resource files, we need to check for https replacements here // adding the server name to make sure we don't replace external links - if (GlobalSettings.UseSSL && string.IsNullOrEmpty(mail.Body) == false) + if (_globalSettings.UseHttps && string.IsNullOrEmpty(mail.Body) == false) { string serverName = http.Request.ServerVariables["SERVER_NAME"]; mail.Body = mail.Body.Replace( @@ -482,9 +484,9 @@ namespace Umbraco.Core.Services.Implement return new NotificationRequest(mail, actionName, mailingUser.Name, mailingUser.Email); } - private static string ReplaceLinks(string text, HttpRequestBase request) + private string ReplaceLinks(string text, HttpRequestBase request) { - var sb = new StringBuilder(GlobalSettings.UseSSL ? "https://" : "http://"); + var sb = new StringBuilder(_globalSettings.UseHttps ? "https://" : "http://"); sb.Append(request.ServerVariables["SERVER_NAME"]); sb.Append(":"); sb.Append(request.Url.Port); diff --git a/src/Umbraco.Core/Services/Implement/UserService.cs b/src/Umbraco.Core/Services/Implement/UserService.cs index 9c5d65c6f3..4b27fb5c51 100644 --- a/src/Umbraco.Core/Services/Implement/UserService.cs +++ b/src/Umbraco.Core/Services/Implement/UserService.cs @@ -28,14 +28,16 @@ namespace Umbraco.Core.Services.Implement { private readonly IUserRepository _userRepository; private readonly IUserGroupRepository _userGroupRepository; + private readonly IGlobalSettings _globalSettings; private readonly bool _isUpgrading; public UserService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IRuntimeState runtimeState, - IUserRepository userRepository, IUserGroupRepository userGroupRepository) + IUserRepository userRepository, IUserGroupRepository userGroupRepository, IGlobalSettings globalSettings) : base(provider, logger, eventMessagesFactory) { _userRepository = userRepository; _userGroupRepository = userGroupRepository; + _globalSettings = globalSettings; _isUpgrading = runtimeState.Level == RuntimeLevel.Install || runtimeState.Level == RuntimeLevel.Upgrade; } @@ -120,7 +122,7 @@ namespace Umbraco.Core.Services.Implement { DefaultToLiveEditing = false, Email = email, - Language = GlobalSettings.DefaultUILanguage, + Language = _globalSettings.DefaultUILanguage, Name = username, RawPasswordValue = passwordValue, Username = username, diff --git a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs index 1e40f46775..691a325eaa 100644 --- a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs +++ b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs @@ -29,9 +29,9 @@ namespace Umbraco.Core.Sync // FIXME need another way to do it, eg an interface, injected! public static Func ApplicationUrlProvider { get; set; } - internal static string GetApplicationUrl(ILogger logger, HttpRequestBase request = null, IUmbracoSettingsSection settings = null) + internal static string GetApplicationUrl(ILogger logger, IGlobalSettings globalSettings, IUmbracoSettingsSection settings, HttpRequestBase request = null) { - var umbracoApplicationUrl = TryGetApplicationUrl(settings ?? UmbracoConfig.For.UmbracoSettings(), logger); + var umbracoApplicationUrl = TryGetApplicationUrl(settings, logger, globalSettings); if (umbracoApplicationUrl != null) return umbracoApplicationUrl; @@ -45,12 +45,12 @@ namespace Umbraco.Core.Sync if (request == null) return null; - umbracoApplicationUrl = GetApplicationUrlFromCurrentRequest(request); + umbracoApplicationUrl = GetApplicationUrlFromCurrentRequest(request, globalSettings); logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + umbracoApplicationUrl + " (UmbracoModule request)"); return umbracoApplicationUrl; } - internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger) + internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings) { // try umbracoSettings:settings/web.routing/@umbracoApplicationUrl // which is assumed to: @@ -75,7 +75,7 @@ namespace Umbraco.Core.Sync url = settings.ScheduledTasks.BaseUrl; if (url.IsNullOrWhiteSpace() == false) { - var ssl = GlobalSettings.UseSSL ? "s" : ""; + var ssl = globalSettings.UseHttps ? "s" : ""; url = "http" + ssl + "://" + url; var umbracoApplicationUrl = url.TrimEnd('/'); logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + umbracoApplicationUrl + " (using scheduledTasks/@baseUrl)"); @@ -100,7 +100,7 @@ namespace Umbraco.Core.Sync return null; } - public static string GetApplicationUrlFromCurrentRequest(HttpRequestBase request) + public static string GetApplicationUrlFromCurrentRequest(HttpRequestBase request, IGlobalSettings globalSettings) { // if (HTTP and SSL not required) or (HTTPS and SSL required), // use ports from request @@ -108,12 +108,12 @@ namespace Umbraco.Core.Sync // if non-standard ports used, // user may need to set umbracoApplicationUrl manually per // http://our.umbraco.org/documentation/Using-Umbraco/Config-files/umbracoSettings/#ScheduledTasks - var port = (request.IsSecureConnection == false && GlobalSettings.UseSSL == false) - || (request.IsSecureConnection && GlobalSettings.UseSSL) + var port = (request.IsSecureConnection == false && globalSettings.UseHttps == false) + || (request.IsSecureConnection && globalSettings.UseHttps) ? ":" + request.ServerVariables["SERVER_PORT"] : ""; - var useSsl = GlobalSettings.UseSSL || port == "443"; + var useSsl = globalSettings.UseHttps || port == "443"; var ssl = useSsl ? "s" : ""; // force, whatever the first request var url = "http" + ssl + "://" + request.ServerVariables["SERVER_NAME"] + port + IOHelper.ResolveUrl(SystemDirectories.Umbraco); diff --git a/src/Umbraco.Core/Sync/ConfigServerAddress.cs b/src/Umbraco.Core/Sync/ConfigServerAddress.cs index fa1cf20f8e..be00544344 100644 --- a/src/Umbraco.Core/Sync/ConfigServerAddress.cs +++ b/src/Umbraco.Core/Sync/ConfigServerAddress.cs @@ -9,17 +9,17 @@ namespace Umbraco.Core.Sync /// internal class ConfigServerAddress : IServerAddress { - public ConfigServerAddress(IServer n) + public ConfigServerAddress(IServer n, IGlobalSettings globalSettings) { var webServicesUrl = IOHelper.ResolveUrl(SystemDirectories.WebServices); - var protocol = GlobalSettings.UseSSL ? "https" : "http"; + var protocol = globalSettings.UseHttps ? "https" : "http"; if (n.ForceProtocol.IsNullOrWhiteSpace() == false) protocol = n.ForceProtocol; var domain = n.ServerAddress; if (n.ForcePortnumber.IsNullOrWhiteSpace() == false) - domain += string.Format(":{0}", n.ForcePortnumber); - ServerAddress = string.Format("{0}://{1}{2}/cacheRefresher.asmx", protocol, domain, webServicesUrl); + domain += $":{n.ForcePortnumber}"; + ServerAddress = $"{protocol}://{domain}{webServicesUrl}/cacheRefresher.asmx"; } public string ServerAddress { get; private set; } diff --git a/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs b/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs index 5929e307dc..83e085b324 100644 --- a/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs +++ b/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Web; +using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -17,12 +18,12 @@ namespace Umbraco.Core.Sync private readonly ServerRole _serverRole; private readonly string _umbracoApplicationUrl; - public ConfigServerRegistrar(IUmbracoSettingsSection settings, ILogger logger) - : this(settings.DistributedCall, logger) + public ConfigServerRegistrar(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings) + : this(settings.DistributedCall, logger, globalSettings) { } // for tests - internal ConfigServerRegistrar(IDistributedCallSection settings, ILogger logger) + internal ConfigServerRegistrar(IDistributedCallSection settings, ILogger logger, IGlobalSettings globalSettings) { if (settings.Enabled == false) { @@ -35,7 +36,7 @@ namespace Umbraco.Core.Sync var serversA = settings.Servers.ToArray(); _addresses = serversA - .Select(x => new ConfigServerAddress(x)) + .Select(x => new ConfigServerAddress(x, globalSettings)) .Cast() .ToList(); diff --git a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs index f7d3b9a7a0..0fcb7036f7 100644 --- a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs +++ b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs @@ -35,7 +35,7 @@ namespace Umbraco.Core.Sync private readonly object _locko = new object(); private readonly ProfilingLogger _profilingLogger; private readonly ISqlContext _sqlContext; - private readonly Lazy _distCacheFilePath = new Lazy(GetDistCacheFilePath); + private readonly Lazy _distCacheFilePath; private int _lastId = -1; private DateTime _lastSync; private DateTime _lastPruned; @@ -46,18 +46,19 @@ namespace Umbraco.Core.Sync public DatabaseServerMessengerOptions Options { get; } public DatabaseServerMessenger( - IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, ILogger logger, ProfilingLogger proflog, + IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, ProfilingLogger proflog, IGlobalSettings globalSettings, bool distributedEnabled, DatabaseServerMessengerOptions options) : base(distributedEnabled) { ScopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); - Logger = logger ?? throw new ArgumentNullException(nameof(logger)); _sqlContext = sqlContext; _runtime = runtime; _profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog)); + Logger = proflog.Logger; Options = options ?? throw new ArgumentNullException(nameof(options)); _lastPruned = _lastSync = DateTime.UtcNow; _syncIdle = new ManualResetEvent(true); + _distCacheFilePath = new Lazy(() => GetDistCacheFilePath(globalSettings)); } protected ILogger Logger { get; } @@ -522,12 +523,12 @@ namespace Umbraco.Core.Sync + "/D" + AppDomain.CurrentDomain.Id // eg 22 + "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique - private static string GetDistCacheFilePath() + private string GetDistCacheFilePath(IGlobalSettings globalSettings) { var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt"; string distCacheFilePath; - switch (GlobalSettings.LocalTempStorageLocation) + switch (globalSettings.LocalTempStorageLocation) { case LocalTempStorage.AspNetTemp: distCacheFilePath = Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData", fileName); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 7790b8a769..1d91f30097 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -208,6 +208,7 @@ + @@ -229,6 +230,7 @@ + diff --git a/src/Umbraco.Core/UriExtensions.cs b/src/Umbraco.Core/UriExtensions.cs index 88180428c4..742e71ad93 100644 --- a/src/Umbraco.Core/UriExtensions.cs +++ b/src/Umbraco.Core/UriExtensions.cs @@ -13,33 +13,34 @@ namespace Umbraco.Core /// public static class UriExtensions { - /// - /// Checks if the current uri is a back office request - /// - /// - /// - /// The current application path or VirtualPath - /// + /// + /// Checks if the current uri is a back office request + /// + /// + /// + /// The current application path or VirtualPath + /// + /// /// - /// - /// There are some special routes we need to check to properly determine this: - /// - /// If any route has an extension in the path like .aspx = back office - /// - /// These are def back office: - /// /Umbraco/RestServices = back office - /// /Umbraco/BackOffice = back office - /// If it's not any of the above, and there's no extension then we cannot determine if it's back office or front-end - /// so we can only assume that it is not back office. This will occur if people use an UmbracoApiController for the backoffice - /// but do not inherit from UmbracoAuthorizedApiController and do not use [IsBackOffice] attribute. - /// - /// These are def front-end: - /// /Umbraco/Surface = front-end - /// /Umbraco/Api = front-end - /// But if we've got this far we'll just have to assume it's front-end anyways. - /// - /// - internal static bool IsBackOfficeRequest(this Uri url, string applicationPath) + /// + /// There are some special routes we need to check to properly determine this: + /// + /// If any route has an extension in the path like .aspx = back office + /// + /// These are def back office: + /// /Umbraco/RestServices = back office + /// /Umbraco/BackOffice = back office + /// If it's not any of the above, and there's no extension then we cannot determine if it's back office or front-end + /// so we can only assume that it is not back office. This will occur if people use an UmbracoApiController for the backoffice + /// but do not inherit from UmbracoAuthorizedApiController and do not use [IsBackOffice] attribute. + /// + /// These are def front-end: + /// /Umbraco/Surface = front-end + /// /Umbraco/Api = front-end + /// But if we've got this far we'll just have to assume it's front-end anyways. + /// + /// + internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, IGlobalSettings globalSettings) { applicationPath = applicationPath ?? string.Empty; @@ -48,13 +49,13 @@ namespace Umbraco.Core var urlPath = fullUrlPath.TrimStart(appPath).EnsureStartsWith('/'); //check if this is in the umbraco back office - var isUmbracoPath = urlPath.InvariantStartsWith(GlobalSettings.Path.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/')); + var isUmbracoPath = urlPath.InvariantStartsWith(globalSettings.Path.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/')); //if not, then def not back office if (isUmbracoPath == false) return false; //if its the normal /umbraco path - if (urlPath.InvariantEquals("/" + GlobalSettings.UmbracoMvcArea) - || urlPath.InvariantEquals("/" + GlobalSettings.UmbracoMvcArea + "/")) + if (urlPath.InvariantEquals("/" + globalSettings.GetUmbracoMvcArea()) + || urlPath.InvariantEquals("/" + globalSettings.GetUmbracoMvcArea() + "/")) { return true; } @@ -75,15 +76,15 @@ namespace Umbraco.Core } //check for special back office paths - if (urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/BackOffice/") - || urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/RestServices/")) + if (urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/BackOffice/") + || urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/RestServices/")) { return true; } //check for special front-end paths - if (urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/Surface/") - || urlPath.InvariantStartsWith("/" + GlobalSettings.UmbracoMvcArea + "/Api/")) + if (urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/Surface/") + || urlPath.InvariantStartsWith("/" + globalSettings.GetUmbracoMvcArea() + "/Api/")) { return false; } @@ -122,13 +123,14 @@ namespace Umbraco.Core /// Checks if the uri is a request for the default back office page /// /// + /// /// - internal static bool IsDefaultBackOfficeRequest(this Uri url) + internal static bool IsDefaultBackOfficeRequest(this Uri url, IGlobalSettings globalSettings) { - if (url.AbsolutePath.InvariantEquals(GlobalSettings.Path.TrimEnd("/")) - || url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/')) - || url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/') + "Default") - || url.AbsolutePath.InvariantEquals(GlobalSettings.Path.EnsureEndsWith('/') + "Default/")) + if (url.AbsolutePath.InvariantEquals(globalSettings.Path.TrimEnd("/")) + || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/')) + || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default") + || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default/")) { return true; } diff --git a/src/Umbraco.Tests/App.config b/src/Umbraco.Tests/App.config index 58c7c9c409..e909ae8566 100644 --- a/src/Umbraco.Tests/App.config +++ b/src/Umbraco.Tests/App.config @@ -62,7 +62,7 @@ - + diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index a79f961af7..f330c126d0 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -53,16 +53,18 @@ namespace Umbraco.Tests.Cache.PublishedCache _httpContextFactory = new FakeHttpContextFactory("~/Home"); - var settings = SettingsForTests.GenerateMockSettings(); + var umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings(); + var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); + SettingsForTests.ConfigureSettings(umbracoSettings); + SettingsForTests.ConfigureSettings(globalSettings); - SettingsForTests.ConfigureSettings(settings); _xml = new XmlDocument(); _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); var cacheProvider = new StaticCacheProvider(); var domainCache = new DomainCache(ServiceContext.DomainService); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedShapshot( - new PublishedContentCache(xmlStore, domainCache, cacheProvider, ContentTypesCache, null, null), + new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, ContentTypesCache, null, null), new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache), new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache), domainCache); @@ -72,9 +74,10 @@ namespace Umbraco.Tests.Cache.PublishedCache _umbracoContext = new UmbracoContext( _httpContextFactory.HttpContext, publishedSnapshotService.Object, - new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService), - settings, - Enumerable.Empty()); + new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings), + umbracoSettings, + Enumerable.Empty(), + globalSettings); _cache = _umbracoContext.ContentCache; } diff --git a/src/Umbraco.Tests/Composing/ComposingTestBase.cs b/src/Umbraco.Tests/Composing/ComposingTestBase.cs index 37f4df268c..be595885e7 100644 --- a/src/Umbraco.Tests/Composing/ComposingTestBase.cs +++ b/src/Umbraco.Tests/Composing/ComposingTestBase.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Logging; +using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Composing { @@ -19,7 +20,7 @@ namespace Umbraco.Tests.Composing { ProfilingLogger = new ProfilingLogger(Mock.Of(), Mock.Of()); - TypeLoader = new TypeLoader(NullCacheProvider.Instance, ProfilingLogger, detectChanges: false) + TypeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), ProfilingLogger, detectChanges: false) { AssembliesToScan = AssembliesToScan }; diff --git a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs index e2af507871..8965d60018 100644 --- a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Composing; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.PropertyEditors; +using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.PropertyEditors; @@ -25,7 +26,7 @@ namespace Umbraco.Tests.Composing public void Initialize() { // this ensures it's reset - _typeLoader = new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of(), Mock.Of())); + _typeLoader = new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), new ProfilingLogger(Mock.Of(), Mock.Of())); foreach (var file in Directory.GetFiles(IOHelper.MapPath("~/App_Data/TEMP/TypesCache"))) File.Delete(file); @@ -146,7 +147,7 @@ namespace Umbraco.Tests.Composing [Test] public void Detect_Legacy_Plugin_File_List() { - var filePath = TypeLoader.GetTypesListFilePath(); + var filePath = _typeLoader.GetTypesListFilePath(); var fileDir = Path.GetDirectoryName(filePath); Directory.CreateDirectory(fileDir); diff --git a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs index 6c3d5c6eec..d50e940b1a 100644 --- a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs +++ b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs @@ -1,5 +1,6 @@ using System.Web.Mvc; using System.Web.Routing; +using Moq; using NUnit.Framework; using Umbraco.Core.Configuration; using Umbraco.Core.IO; @@ -10,26 +11,24 @@ namespace Umbraco.Tests.Configurations [TestFixture] public class GlobalSettingsTests : BaseWebTest { + private string _root; + public override void SetUp() { base.SetUp(); - - SettingsForTests.UmbracoPath = "~/umbraco"; + _root = SystemDirectories.Root; } public override void TearDown() { base.TearDown(); - - //ensure this is reset - SystemDirectories.Root = null; - SettingsForTests.UmbracoPath = "~/umbraco"; + SystemDirectories.Root = _root; } [Test] public void Is_Debug_Mode() { - Assert.That(Umbraco.Core.Configuration.GlobalSettings.DebugMode, Is.EqualTo(true)); + Assert.That(GlobalSettings.DebugMode, Is.EqualTo(true)); } [Ignore("fixme - ignored test")] @@ -46,9 +45,12 @@ namespace Umbraco.Tests.Configurations [TestCase("~/some-wacky/nestedPath", "/MyVirtualDir/NestedVDir/", "some-wacky-nestedpath")] public void Umbraco_Mvc_Area(string path, string rootPath, string outcome) { - SettingsForTests.UmbracoPath = path; + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.Path).Returns(IOHelper.ResolveUrl(path)); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + SystemDirectories.Root = rootPath; - Assert.AreEqual(outcome, Umbraco.Core.Configuration.GlobalSettings.UmbracoMvcArea); + Assert.AreEqual(outcome, UmbracoConfig.For.GlobalSettings().GetUmbracoMvcArea()); } [TestCase("/umbraco/umbraco.aspx")] @@ -61,7 +63,8 @@ namespace Umbraco.Tests.Configurations [TestCase("/config/splashes/booting.aspx")] public void Is_Reserved_Path_Or_Url(string url) { - Assert.IsTrue(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url)); + var globalSettings = TestObjects.GetGlobalSettings(); + Assert.IsTrue(globalSettings.IsReservedPathOrUrl(url)); } [TestCase("/umbraco_client/Tree/treeIcons.css")] @@ -75,7 +78,8 @@ namespace Umbraco.Tests.Configurations [TestCase("/install.aspx")] public void Is_Not_Reserved_Path_Or_Url(string url) { - Assert.IsFalse(Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url)); + var globalSettings = TestObjects.GetGlobalSettings(); + Assert.IsFalse(globalSettings.IsReservedPathOrUrl(url)); } @@ -92,8 +96,10 @@ namespace Umbraco.Tests.Configurations 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 - Umbraco.Core.Configuration.GlobalSettings.ReservedPaths = ""; - Umbraco.Core.Configuration.GlobalSettings.ReservedUrls = ""; + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.ReservedPaths).Returns(""); + globalSettingsMock.Setup(x => x.ReservedUrls).Returns(""); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); var routes = new RouteCollection(); @@ -112,7 +118,7 @@ namespace Umbraco.Tests.Configurations Assert.AreEqual( shouldMatch, - Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url, context.HttpContext, routes)); + globalSettingsMock.Object.IsReservedPathOrUrl(url, context.HttpContext, routes)); } } } diff --git a/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs b/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs index 39e541aa38..2e187d85a5 100644 --- a/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs +++ b/src/Umbraco.Tests/CoreThings/TryConvertToTests.cs @@ -15,7 +15,7 @@ namespace Umbraco.Tests.CoreThings { base.SetUp(); - var settings = SettingsForTests.GetDefault(); + var settings = SettingsForTests.GetDefaultUmbracoSettings(); // fixme - base should do it! Container.RegisterSingleton(_ => new DefaultShortStringHelper(settings)); diff --git a/src/Umbraco.Tests/CoreThings/UdiTests.cs b/src/Umbraco.Tests/CoreThings/UdiTests.cs index 63cfcb093d..62aa56bd14 100644 --- a/src/Umbraco.Tests/CoreThings/UdiTests.cs +++ b/src/Umbraco.Tests/CoreThings/UdiTests.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Composing; using Umbraco.Core.Deploy; using Umbraco.Core.Logging; using Umbraco.Core.Serialization; +using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.CoreThings { @@ -23,7 +24,9 @@ namespace Umbraco.Tests.CoreThings { // fixme - bad in a unit test - but Udi has a static ctor that wants it?! var container = new Mock(); - container.Setup(x => x.GetInstance(typeof (TypeLoader))).Returns(new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of(), Mock.Of()))); + var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); + container.Setup(x => x.GetInstance(typeof (TypeLoader))).Returns( + new TypeLoader(NullCacheProvider.Instance, globalSettings, new ProfilingLogger(Mock.Of(), Mock.Of()))); Current.Container = container.Object; Udi.ResetUdiTypes(); diff --git a/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs b/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs index ab10be1a65..7f00bed123 100644 --- a/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs +++ b/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs @@ -2,6 +2,7 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.IO; +using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.CoreThings { @@ -48,9 +49,9 @@ namespace Umbraco.Tests.CoreThings public void Is_Back_Office_Request(string input, string virtualPath, bool expected) { SystemDirectories.Root = virtualPath; - + var globalConfig = SettingsForTests.GenerateMockGlobalSettings(); var source = new Uri(input); - Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath)); + Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath, globalConfig)); } [TestCase("http://www.domain.com/install", true)] diff --git a/src/Umbraco.Tests/IO/FileSystemsTests.cs b/src/Umbraco.Tests/IO/FileSystemsTests.cs index ef2fa3ce72..79b1d8bf6c 100644 --- a/src/Umbraco.Tests/IO/FileSystemsTests.cs +++ b/src/Umbraco.Tests/IO/FileSystemsTests.cs @@ -23,7 +23,7 @@ namespace Umbraco.Tests.IO public void Setup() { //init the config singleton - var config = SettingsForTests.GetDefault(); + var config = SettingsForTests.GetDefaultUmbracoSettings(); SettingsForTests.ConfigureSettings(config); _container = new ServiceContainer(); diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 6c5c88f6ff..e3a4db5390 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.Macros new IsolatedRuntimeCache(type => new ObjectCacheRuntimeCacheProvider())); //Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of(), Mock.Of())); - UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefault()); + UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefaultUmbracoSettings()); } [TestCase("123", "IntProp", typeof(int))] diff --git a/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs b/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs index a20b86cc7b..bb134d7e35 100644 --- a/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs +++ b/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs @@ -7,8 +7,10 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Sync; +using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Misc { @@ -20,9 +22,9 @@ namespace Umbraco.Tests.Misc // note: in tests, read appContext._umbracoApplicationUrl and not the property, // because reading the property does run some code, as long as the field is null. - private void Initialize(IUmbracoSettingsSection settings) + private void Initialize(IUmbracoSettingsSection settings, IGlobalSettings globalSettings) { - _registrar = new ConfigServerRegistrar(settings.DistributedCall, Mock.Of()); + _registrar = new ConfigServerRegistrar(settings.DistributedCall, Mock.Of(), globalSettings); var container = new ServiceContainer(); container.ConfigureUmbracoCore(); container.Register(_ => _registrar); @@ -51,15 +53,16 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of()); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); + ApplicationUrlHelper.ApplicationUrlProvider = request => "http://server1.com/umbraco"; - Initialize(settings); + Initialize(settings, globalConfig.Object); var state = new RuntimeState(Mock.Of(), new Lazy(Mock.Of), new Lazy(Mock.Of)); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here - - state.EnsureApplicationUrl(settings: settings); + state.EnsureApplicationUrl(settings, globalConfig.Object); Assert.AreEqual("http://server1.com/umbraco", state.ApplicationUrl.ToString()); } @@ -74,11 +77,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of()); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + Initialize(settings, globalConfig.Object); + + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); // still NOT set Assert.IsNull(url); @@ -99,11 +103,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); + Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.AreEqual("http://server1.com:80/umbraco", url); @@ -126,11 +131,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); + Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.AreEqual("http://server1.com:80/umbraco", url); @@ -153,11 +159,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); + Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.IsNull(url); @@ -174,8 +181,10 @@ namespace Umbraco.Tests.Misc section.DistributedCall == Mock.Of(callSection => callSection.Enabled == false && callSection.Servers == Enumerable.Empty()) && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - Initialize(settings); + + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + + Initialize(settings, globalConfig.Object); var role = _registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Single, role); @@ -191,7 +200,9 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + + Initialize(settings, globalConfig.Object); var role = _registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Unknown, role); @@ -210,7 +221,9 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + + Initialize(settings, globalConfig.Object); var role = _registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Slave, role); @@ -224,11 +237,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(false); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "false"); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + Initialize(settings, globalConfig.Object); + + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.AreEqual("http://mycoolhost.com/umbraco", url); } @@ -241,11 +255,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco/")); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + Initialize(settings, globalConfig.Object); + + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.AreEqual("https://mycoolhost.com/umbraco", url); } @@ -258,11 +273,12 @@ namespace Umbraco.Tests.Misc && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/") && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); - Initialize(settings); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); - ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here + Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of()); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); Assert.AreEqual("httpx://whatever.com/umbraco", url); } diff --git a/src/Umbraco.Tests/Misc/UriUtilityTests.cs b/src/Umbraco.Tests/Misc/UriUtilityTests.cs index 851060ce13..0bd9156f20 100644 --- a/src/Umbraco.Tests/Misc/UriUtilityTests.cs +++ b/src/Umbraco.Tests/Misc/UriUtilityTests.cs @@ -84,7 +84,10 @@ namespace Umbraco.Tests.Misc { ConfigurationManager.AppSettings.Set("umbracoUseDirectoryUrls", directoryUrls ? "true" : "false"); - var settings = SettingsForTests.GenerateMockSettings(); + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseDirectoryUrls).Returns(directoryUrls); + + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var requestMock = Mock.Get(settings.RequestHandler); requestMock.Setup(x => x.AddTrailingSlash).Returns(trailingSlash); SettingsForTests.ConfigureSettings(settings); @@ -93,7 +96,7 @@ namespace Umbraco.Tests.Misc var expectedUri = NewUri(expectedUrl); var sourceUri = NewUri(sourceUrl); - var resultUri = UriUtility.UriFromUmbraco(sourceUri); + var resultUri = UriUtility.UriFromUmbraco(sourceUri, globalConfig.Object, settings.RequestHandler); Assert.AreEqual(expectedUri.ToString(), resultUri.ToString()); } diff --git a/src/Umbraco.Tests/Models/ContentTests.cs b/src/Umbraco.Tests/Models/ContentTests.cs index 93e3e91f6a..be22c39626 100644 --- a/src/Umbraco.Tests/Models/ContentTests.cs +++ b/src/Umbraco.Tests/Models/ContentTests.cs @@ -29,7 +29,7 @@ namespace Umbraco.Tests.Models { base.SetUp(); - var config = SettingsForTests.GetDefault(); + var config = SettingsForTests.GetDefaultUmbracoSettings(); SettingsForTests.ConfigureSettings(config); } diff --git a/src/Umbraco.Tests/Models/MacroTests.cs b/src/Umbraco.Tests/Models/MacroTests.cs index 64e485c965..052c42942b 100644 --- a/src/Umbraco.Tests/Models/MacroTests.cs +++ b/src/Umbraco.Tests/Models/MacroTests.cs @@ -13,7 +13,7 @@ namespace Umbraco.Tests.Models [SetUp] public void Init() { - var config = SettingsForTests.GetDefault(); + var config = SettingsForTests.GetDefaultUmbracoSettings(); SettingsForTests.ConfigureSettings(config); } diff --git a/src/Umbraco.Tests/Packaging/PackageExtractionTests.cs b/src/Umbraco.Tests/Packaging/PackageExtractionTests.cs index a1bdb0979d..118d57ab2a 100644 --- a/src/Umbraco.Tests/Packaging/PackageExtractionTests.cs +++ b/src/Umbraco.Tests/Packaging/PackageExtractionTests.cs @@ -14,7 +14,7 @@ namespace Umbraco.Tests.Packaging private static string GetTestPackagePath(string packageName) { const string testPackagesDirName = "Packaging\\Packages"; - string path = Path.Combine(Core.Configuration.GlobalSettings.FullpathToRoot, testPackagesDirName, packageName); + string path = Path.Combine(Core.Configuration.GlobalSettings.FullPathToRoot, testPackagesDirName, packageName); return path; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs index a636e956f9..fe2c946331 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs @@ -49,7 +49,7 @@ namespace Umbraco.Tests.Persistence.Repositories private UserRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor) provider; - var repository = new UserRepository(accessor, CacheHelper.CreateDisabledCacheHelper(), Mock.Of(), Mock.Of()); + var repository = new UserRepository(accessor, CacheHelper.CreateDisabledCacheHelper(), Mock.Of(), Mock.Of(), TestObjects.GetGlobalSettings()); return repository; } @@ -204,7 +204,7 @@ namespace Umbraco.Tests.Persistence.Repositories var id = user.Id; - var repository2 = new UserRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Logger, Mock.Of()); + var repository2 = new UserRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Logger, Mock.Of(),TestObjects.GetGlobalSettings()); repository2.Delete(user); diff --git a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs index ff2ee0aebd..acbd021319 100644 --- a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs +++ b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs @@ -25,7 +25,7 @@ namespace Umbraco.Tests.PropertyEditors var container = new ServiceContainer(); container.ConfigureUmbracoCore(); container.Register(_ - => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()))); + => new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()))); } [TearDown] diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs index 5d4e0e1691..2713229a5e 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs @@ -65,13 +65,16 @@ namespace Umbraco.Tests.PublishedContent var publishedSnapshotService = new Mock(); publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedSnapshot); + var globalSettings = TestObjects.GetGlobalSettings(); + var httpContext = GetHttpContextFactory("http://umbraco.local/", routeData).HttpContext; var umbracoContext = new UmbracoContext( httpContext, publishedSnapshotService.Object, - new WebSecurity(httpContext, Current.Services.UserService), + new WebSecurity(httpContext, Current.Services.UserService, globalSettings), TestObjects.GetUmbracoSettings(), - Enumerable.Empty()); + Enumerable.Empty(), + globalSettings); return umbracoContext; } diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index f53f761060..adfc9f535a 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -439,7 +439,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void Convert_From_Standard_Xml() { - var config = SettingsForTests.GenerateMockSettings(); + var config = SettingsForTests.GenerateMockUmbracoSettings(); SettingsForTests.ConfigureSettings(config); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs index 713a8e68d6..c58899d4d1 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using Moq; +using NUnit.Framework; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; using Umbraco.Core.Models; @@ -26,15 +27,18 @@ namespace Umbraco.Tests.Routing [TestCase("/home/Sub1.aspx/blah")] public void Match_Document_By_Url_With_Template(string urlAsString) { + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + var template1 = CreateTemplate("test"); var template2 = CreateTemplate("blah"); - var umbracoContext = GetUmbracoContext(urlAsString, template1.Id); + var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByNiceUrlAndTemplate(Logger); - SettingsForTests.HideTopLevelNodeFromPath = false; - var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs index fe8fbcf8f7..66f5cc722a 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs @@ -1,6 +1,8 @@ using System; using System.Globalization; +using Moq; using NUnit.Framework; +using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; @@ -25,13 +27,16 @@ namespace Umbraco.Tests.Routing [TestCase("/test-page", 1172)] public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId) { - var umbracoContext = GetUmbracoContext(urlString); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByNiceUrl(Logger); - SettingsForTests.HideTopLevelNodeFromPath = true; - Assert.IsTrue(Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath); + Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); // fixme debugging - going further down, the routes cache is NOT empty?! if (urlString == "/home/sub1") @@ -58,13 +63,16 @@ namespace Umbraco.Tests.Routing [TestCase("/home/Sub1.aspx", 1173)] public void Match_Document_By_Url(string urlString, int expectedId) { - var umbracoContext = GetUmbracoContext(urlString); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByNiceUrl(Logger); - SettingsForTests.HideTopLevelNodeFromPath = false; - Assert.IsFalse(Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath); + Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); var result = lookup.TryFindContent(frequest); @@ -81,12 +89,15 @@ 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 umbracoContext = GetUmbracoContext(urlString); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByNiceUrl(Logger); - SettingsForTests.HideTopLevelNodeFromPath = false; - + var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); @@ -106,12 +117,15 @@ 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 umbracoContext = GetUmbracoContext(urlString); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/")); var lookup = new ContentFinderByNiceUrl(Logger); - SettingsForTests.HideTopLevelNodeFromPath = false; var result = lookup.TryFindContent(frequest); @@ -133,13 +147,16 @@ 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 umbracoContext = GetUmbracoContext(urlString); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå")); var lookup = new ContentFinderByNiceUrl(Logger); - SettingsForTests.HideTopLevelNodeFromPath = false; - + var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs index e05fed11dc..396697001d 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs @@ -1,4 +1,5 @@ -using NUnit.Framework; +using Moq; +using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; @@ -123,9 +124,11 @@ namespace Umbraco.Tests.Routing { SetDomains3(); - SettingsForTests.HideTopLevelNodeFromPath = true; - - var umbracoContext = GetUmbracoContext(url); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(Container); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -164,9 +167,11 @@ namespace Umbraco.Tests.Routing // defaults depend on test environment expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - SettingsForTests.HideTopLevelNodeFromPath = true; + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - var umbracoContext = GetUmbracoContext(url); + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(Container); var frequest = publishedRouter.CreateRequest(umbracoContext); diff --git a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs index e67248cdfa..b1d024cc8f 100644 --- a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs +++ b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs @@ -1,4 +1,5 @@ using System; +using Moq; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; @@ -263,7 +264,11 @@ namespace Umbraco.Tests.Routing { SetDomains1(); - var umbracoContext = GetUmbracoContext(inputUrl); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object); var publishedRouter = CreatePublishedRouter(Container); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -271,8 +276,7 @@ namespace Umbraco.Tests.Routing publishedRouter.FindDomain(frequest); Assert.AreEqual(expectedCulture, frequest.Culture.Name); - - SettingsForTests.HideTopLevelNodeFromPath = false; + var finder = new ContentFinderByNiceUrl(Logger); var result = finder.TryFindContent(frequest); @@ -310,7 +314,11 @@ namespace Umbraco.Tests.Routing // defaults depend on test environment expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - var umbracoContext = GetUmbracoContext(inputUrl); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext(inputUrl, globalSettings:globalSettings.Object); var publishedRouter = CreatePublishedRouter(Container); var frequest = publishedRouter.CreateRequest(umbracoContext); @@ -318,7 +326,6 @@ namespace Umbraco.Tests.Routing publishedRouter.FindDomain(frequest); // find document - SettingsForTests.HideTopLevelNodeFromPath = false; var finder = new ContentFinderByNiceUrl(Logger); var result = finder.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs b/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs index 0898392484..246a9beb8a 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Routing base.SetUp(); //generate new mock settings and assign so we can configure in individual tests - _umbracoSettings = SettingsForTests.GenerateMockSettings(); + _umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings(); SettingsForTests.ConfigureSettings(_umbracoSettings); } @@ -38,10 +38,16 @@ namespace Umbraco.Tests.Routing [Test] public void Ensure_Cache_Is_Correct() { - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) }); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); + var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler); requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none) @@ -95,10 +101,16 @@ namespace Umbraco.Tests.Routing [TestCase(1172, "/test-page/")] public void Get_Nice_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) { - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); @@ -119,10 +131,16 @@ namespace Umbraco.Tests.Routing [TestCase(1172, "/test-page/")] // not hidden because not first root public void Get_Nice_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) { - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = true; var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); @@ -133,12 +151,19 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Nice_Url_Relative_Or_Absolute() { - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) }); + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); @@ -153,10 +178,15 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Nice_Url_Unpublished() { - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); //mock the Umbraco settings that we need var requestMock = Mock.Get(_umbracoSettings.RequestHandler); diff --git a/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs b/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs index 7d45a0e85b..2c44a26117 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs +++ b/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs @@ -1,4 +1,5 @@ using System; +using Moq; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; @@ -192,12 +193,14 @@ DetermineRouteById(id): [TestCase(2006, false, "/x/b/e")] public void GetRouteByIdNoHide(int id, bool hide, string expected) { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - SettingsForTests.HideTopLevelNodeFromPath = hide; - var route = cache.GetRouteById(false, id); Assert.AreEqual(expected, route); } @@ -215,12 +218,14 @@ DetermineRouteById(id): [TestCase(2006, true, "/b/e")] // risky! public void GetRouteByIdHide(int id, bool hide, string expected) { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - SettingsForTests.HideTopLevelNodeFromPath = hide; - var route = cache.GetRouteById(false, id); Assert.AreEqual(expected, route); } @@ -228,12 +233,14 @@ DetermineRouteById(id): [Test] public void GetRouteByIdCache() { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - - SettingsForTests.HideTopLevelNodeFromPath = false; - + var route = cache.GetRouteById(false, 1000); Assert.AreEqual("/a", route); @@ -258,12 +265,14 @@ DetermineRouteById(id): [TestCase("/x", false, 2000)] public void GetByRouteNoHide(string route, bool hide, int expected) { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - SettingsForTests.HideTopLevelNodeFromPath = hide; - const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?! var content = cache.GetByRoute(preview, route); if (expected < 0) @@ -288,12 +297,14 @@ DetermineRouteById(id): [TestCase("/b/c", true, 1002)] // (hence the 2005 collision) public void GetByRouteHide(string route, bool hide, int expected) { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - SettingsForTests.HideTopLevelNodeFromPath = hide; - const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?! var content = cache.GetByRoute(preview, route); if (expected < 0) @@ -310,12 +321,14 @@ DetermineRouteById(id): [Test] public void GetByRouteCache() { - var umbracoContext = GetUmbracoContext("/test", 0); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object); var cache = umbracoContext.ContentCache as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - - SettingsForTests.HideTopLevelNodeFromPath = false; - + var content = cache.GetByRoute(false, "/a/b/c"); Assert.IsNotNull(content); Assert.AreEqual(1002, content.Id); diff --git a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs b/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs index 349d1011e4..fa223420f2 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs @@ -173,15 +173,20 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "https://domain1.com", false, "/1001-1/")] public void Get_Nice_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); - - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); + SetDomains1(); var currentUri = new Uri(currentUrl); @@ -204,14 +209,19 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")] public void Get_Nice_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains2(); @@ -227,14 +237,19 @@ namespace Umbraco.Tests.Routing [TestCase(1002, "http://domain1.com", false, "/1002/")] public void Get_Nice_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains3(); @@ -256,14 +271,19 @@ namespace Umbraco.Tests.Routing [TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")] public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains4(); @@ -275,14 +295,19 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Nice_Url_DomainsAndCache() { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains4(); @@ -337,14 +362,19 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Nice_Url_Relative_Or_Absolute() { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var requestMock = Mock.Get(settings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; + var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains4(); @@ -366,11 +396,17 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Nice_Url_Alternate() { - var settings = SettingsForTests.GenerateMockSettings(); - var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); SetDomains5(); diff --git a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index 08d0cbadbe..d0b3622127 100644 --- a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs +++ b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs @@ -31,10 +31,9 @@ namespace Umbraco.Tests.Routing { base.SetUp(); - SettingsForTests.UmbracoPath = "~/umbraco"; - WebRuntimeComponent.CreateRoutes( - new TestUmbracoContextAccessor(), + new TestUmbracoContextAccessor(), + TestObjects.GetGlobalSettings(), new SurfaceControllerTypeCollection(Enumerable.Empty()), new UmbracoApiControllerTypeCollection(Enumerable.Empty())); } @@ -71,7 +70,7 @@ namespace Umbraco.Tests.Routing var umbracoApiControllerTypes = new UmbracoApiControllerTypeCollection(Current.TypeLoader.GetUmbracoApiControllers()); Container.RegisterInstance(umbracoApiControllerTypes); - Container.RegisterSingleton(_ => new DefaultShortStringHelper(SettingsForTests.GetDefault())); + Container.RegisterSingleton(_ => new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings())); } public override void TearDown() diff --git a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs index 44c4b5c561..23a0773f71 100644 --- a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs +++ b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs @@ -31,8 +31,8 @@ namespace Umbraco.Tests.Routing var runtime = new RuntimeState(_module.Logger, new Lazy(), new Lazy()); _module.Runtime = runtime; runtime.Level = RuntimeLevel.Run; + _module.GlobalSettings = TestObjects.GetGlobalSettings(); - SettingsForTests.ConfigurationStatus = UmbracoVersion.SemanticVersion.ToSemanticString(); //SettingsForTests.ReservedPaths = "~/umbraco,~/install/"; //SettingsForTests.ReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd"; diff --git a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs index 857f91f0c9..41a7bf730d 100644 --- a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs +++ b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs @@ -28,10 +28,12 @@ namespace Umbraco.Tests.Routing [Test] public void DoNotPolluteCache() { - SettingsForTests.UseDirectoryUrls = true; - SettingsForTests.HideTopLevelNodeFromPath = false; // ignored w/domains + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); request.Setup(x => x.UseDomainPrefixes).Returns(true); @@ -40,7 +42,10 @@ namespace Umbraco.Tests.Routing const string url = "http://domain1.com/1001-1/1001-1-1"; // get the nice url for 100111 - var umbracoContext = GetUmbracoContext(url, 9999, umbracoSettings: settings, urlProviders: new [] { new DefaultUrlProvider(settings.RequestHandler, Logger) }); + var umbracoContext = GetUmbracoContext(url, 9999, umbracoSettings: settings, urlProviders: new [] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + }, globalSettings:globalSettings.Object); Assert.AreEqual("http://domain2.com/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111, true)); // check that the proper route has been cached diff --git a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs index 3288800bac..770dead600 100644 --- a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs +++ b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs @@ -163,7 +163,7 @@ namespace Umbraco.Tests.Runtimes { base.Compose(composition); - composition.Container.Register(factory => SettingsForTests.GetDefault()); + composition.Container.Register(factory => SettingsForTests.GetDefaultUmbracoSettings()); composition.Container.RegisterSingleton(); Composed = true; diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 474f15d29b..585a943416 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -8,6 +8,7 @@ using NUnit.Framework; 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.Models; @@ -89,7 +90,7 @@ namespace Umbraco.Tests.Scoping publishedSnapshotAccessor, Logger, ScopeProvider, - documentRepository, mediaRepository, memberRepository); + documentRepository, mediaRepository, memberRepository, Container.GetInstance()); } protected UmbracoContext GetUmbracoContextNu(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null) @@ -102,9 +103,10 @@ namespace Umbraco.Tests.Scoping var umbracoContext = new UmbracoContext( httpContext, service, - new WebSecurity(httpContext, Current.Services.UserService), - umbracoSettings ?? SettingsForTests.GetDefault(), - urlProviders ?? Enumerable.Empty()); + new WebSecurity(httpContext, Current.Services.UserService, TestObjects.GetGlobalSettings()), + umbracoSettings ?? SettingsForTests.GetDefaultUmbracoSettings(), + urlProviders ?? Enumerable.Empty(), + TestObjects.GetGlobalSettings()); if (setSingleton) Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; diff --git a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs index 6ee0fd1290..258056f198 100644 --- a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs @@ -79,7 +79,7 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(XmlStore, ((PublishedContentCache) umbracoContext.ContentCache).XmlStore); // settings - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var contentMock = Mock.Get(settings.Content); contentMock.Setup(x => x.XmlCacheEnabled).Returns(false); SettingsForTests.ConfigureSettings(settings); @@ -201,7 +201,7 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(XmlStore, ((PublishedContentCache)umbracoContext.ContentCache).XmlStore); // settings - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var contentMock = Mock.Get(settings.Content); contentMock.Setup(x => x.XmlCacheEnabled).Returns(false); SettingsForTests.ConfigureSettings(settings); diff --git a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs index 19bacce0ad..1b182024c3 100644 --- a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs +++ b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs @@ -29,11 +29,12 @@ namespace Umbraco.Tests.Security var umbracoContext = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService), - TestObjects.GetUmbracoSettings(), new List()); + new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), + TestObjects.GetUmbracoSettings(), new List(),TestObjects.GetGlobalSettings()); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); - var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbracoContext), runtime); + var mgr = new BackOfficeCookieManager( + Mock.Of(accessor => accessor.UmbracoContext == umbracoContext), runtime, TestObjects.GetGlobalSettings()); var result = mgr.ShouldAuthenticateRequest(Mock.Of(), new Uri("http://localhost/umbraco")); @@ -46,11 +47,11 @@ namespace Umbraco.Tests.Security var umbCtx = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService), - TestObjects.GetUmbracoSettings(), new List()); + new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), + TestObjects.GetUmbracoSettings(), new List(), TestObjects.GetGlobalSettings()); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); - var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbCtx), runtime); + var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbCtx), runtime, TestObjects.GetGlobalSettings()); var request = new Mock(); request.Setup(owinRequest => owinRequest.Uri).Returns(new Uri("http://localhost/umbraco")); diff --git a/src/Umbraco.Tests/Services/PackagingServiceTests.cs b/src/Umbraco.Tests/Services/PackagingServiceTests.cs index 474f8cd2a1..17c065338d 100644 --- a/src/Umbraco.Tests/Services/PackagingServiceTests.cs +++ b/src/Umbraco.Tests/Services/PackagingServiceTests.cs @@ -76,7 +76,7 @@ namespace Umbraco.Tests.Services private static string GetTestPackagePath(string packageName) { const string testPackagesDirName = "Packaging\\Packages"; - string path = Path.Combine(Core.Configuration.GlobalSettings.FullpathToRoot, testPackagesDirName, packageName); + string path = Path.Combine(Core.Configuration.GlobalSettings.FullPathToRoot, testPackagesDirName, packageName); return path; } diff --git a/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs b/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs index b133632eda..0fb0dee68c 100644 --- a/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs +++ b/src/Umbraco.Tests/Strings/CmsHelperCasingTests.cs @@ -13,7 +13,7 @@ namespace Umbraco.Tests.Strings public void Setup() { //set default config - var config = SettingsForTests.GetDefault(); + var config = SettingsForTests.GetDefaultUmbracoSettings(); SettingsForTests.ConfigureSettings(config); } @@ -39,7 +39,7 @@ 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.GetDefault()); + var helper = new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings()); 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 67baab695c..19cac22287 100644 --- a/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs +++ b/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs @@ -28,7 +28,7 @@ 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.GetDefault()) + _helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.FileName, new DefaultShortStringHelperConfig.Config { //PreFilter = ClearFileChars, // done in IsTerm @@ -96,7 +96,7 @@ namespace Umbraco.Tests.Strings [Test] public void U4_4056() { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var contentMock = Mock.Get(settings.RequestHandler); contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Strings [Test] public void U4_4056_TryAscii() { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var contentMock = Mock.Get(settings.RequestHandler); contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); @@ -148,7 +148,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringUnderscoreInTerm() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // underscore is accepted within terms @@ -158,7 +158,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo_bar*nil", helper.CleanString("foo_bar nil", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // underscore is not accepted within terms @@ -172,7 +172,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringLeadingChars() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // letters and digits are valid leading chars @@ -182,7 +182,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.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { // only letters are valid leading chars @@ -193,14 +193,14 @@ 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.GetDefault())); + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings())); Assert.AreEqual("child2", helper.CleanStringForSafeAlias("1child2")); } [Test] public void CleanStringTermOnUpper() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -210,7 +210,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo*Bar", helper.CleanString("fooBar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -224,7 +224,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringAcronymOnNonUpper() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -237,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.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -254,7 +254,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringGreedyAcronyms() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -267,7 +267,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.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -284,7 +284,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringWhiteSpace() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -297,7 +297,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringSeparator() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -305,7 +305,7 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo*bar", helper.CleanString("foo bar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -313,14 +313,14 @@ namespace Umbraco.Tests.Strings })); Assert.AreEqual("foo bar", helper.CleanString("foo bar", CleanStringType.Alias)); - helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .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.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -332,7 +332,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringSymbols() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -386,7 +386,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringEncoding() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, @@ -395,7 +395,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.GetDefault()) + helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Ascii | CleanStringType.Unchanged, @@ -408,7 +408,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringDefaultConfig() { - var settings = SettingsForTests.GenerateMockSettings(); + var settings = SettingsForTests.GenerateMockUmbracoSettings(); var contentMock = Mock.Get(settings.RequestHandler); contentMock.Setup(x => x.CharCollection).Returns(Enumerable.Empty()); contentMock.Setup(x => x.ConvertUrlsToAscii).Returns(false); @@ -434,7 +434,7 @@ namespace Umbraco.Tests.Strings [Test] public void CleanStringCasing() { - var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefault()) + var helper = new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(SettingsForTests.GetDefaultUmbracoSettings()) .WithConfig(CleanStringType.Alias, new DefaultShortStringHelperConfig.Config { StringType = CleanStringType.Utf8 | CleanStringType.Unchanged, diff --git a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs index 38899170cd..e28e3f7c29 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs @@ -41,7 +41,8 @@ namespace Umbraco.Tests.TestHelpers container.RegisterSingleton(factory => Mock.Of()); var logger = new ProfilingLogger(Mock.Of(), Mock.Of()); - var pluginManager = new TypeLoader(NullCacheProvider.Instance, + var pluginManager = new TypeLoader(NullCacheProvider.Instance, + SettingsForTests.GenerateMockGlobalSettings(), logger, false); container.RegisterInstance(pluginManager); diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index d5213cbcda..0b3e5d6efd 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -68,8 +68,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting localizedTextService:Mock.Of(), sectionService:Mock.Of()); - //ensure the configuration matches the current version for tests - SettingsForTests.ConfigurationStatus = UmbracoVersion.SemanticVersion.ToSemanticString(); + var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); // fixme v8? ////new app context @@ -85,19 +84,25 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting // new ProfilingLogger(Mock.Of(), Mock.Of()), // true); + var httpContextItems = new Dictionary + { + //add the special owin environment to the httpcontext items, this is how the GetOwinContext works + ["owin.Environment"] = new Dictionary() + }; + //httpcontext with an auth'd user var httpContext = Mock.Of( http => http.User == owinContext.Authentication.User //ensure the request exists with a cookies collection && http.Request == Mock.Of(r => r.Cookies == new HttpCookieCollection()) //ensure the request exists with an items collection - && http.Items == Mock.Of()); + && http.Items == httpContextItems); //chuck it into the props since this is what MS does when hosted and it's needed there request.Properties["MS_HttpContext"] = httpContext; var backofficeIdentity = (UmbracoBackOfficeIdentity) owinContext.Authentication.User.Identity; - var webSecurity = new Mock(null, null); + var webSecurity = new Mock(null, null, globalSettings); //mock CurrentUser var groups = new List(); @@ -142,6 +147,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting webSecurity.Object, Mock.Of(section => section.WebRouting == Mock.Of(routingSection => routingSection.UrlProviderMode == UrlProviderMode.Auto.ToString())), Enumerable.Empty(), + globalSettings, true); //replace it var urlHelper = new Mock(); diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index 7c75003378..5d47c82dff 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -5,11 +5,17 @@ using Moq; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.IO; namespace Umbraco.Tests.TestHelpers { public class SettingsForTests { + public static void ConfigureSettings(IGlobalSettings settings) + { + UmbracoConfig.For.SetGlobalConfig(settings); + } + // umbracoSettings /// @@ -21,11 +27,28 @@ namespace Umbraco.Tests.TestHelpers UmbracoConfig.For.SetUmbracoSettings(settings); } + public static IGlobalSettings GenerateMockGlobalSettings() + { + var config = Mock.Of( + settings => + settings.ConfigurationStatus == UmbracoVersion.SemanticVersion.ToSemanticString() && + settings.UseHttps == false && + settings.HideTopLevelNodeFromPath == false && + settings.Path == IOHelper.ResolveUrl("~/umbraco") && + settings.UseDirectoryUrls == true && + settings.TimeOutInMinutes == 20 && + settings.DefaultUILanguage == "en" && + settings.LocalTempStorageLocation == LocalTempStorage.Default && + settings.ReservedPaths == (GlobalSettings.StaticReservedPaths + "~/umbraco") && + settings.ReservedUrls == GlobalSettings.StaticReservedUrls); + return config; + } + /// /// Returns generated settings which can be stubbed to return whatever values necessary /// /// - public static IUmbracoSettingsSection GenerateMockSettings() + public static IUmbracoSettingsSection GenerateMockUmbracoSettings() { var settings = new Mock(); @@ -68,103 +91,83 @@ namespace Umbraco.Tests.TestHelpers return settings.Object; } - // from appSettings + //// from appSettings - private static readonly IDictionary SavedAppSettings = new Dictionary(); + //private static readonly IDictionary SavedAppSettings = new Dictionary(); - static void SaveSetting(string key) - { - SavedAppSettings[key] = ConfigurationManager.AppSettings[key]; - } + //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"); - } + //static void SaveSettings() + //{ + // SaveSetting("umbracoHideTopLevelNodeFromPath"); + // SaveSetting("umbracoUseDirectoryUrls"); + // SaveSetting("umbracoPath"); + // SaveSetting("umbracoReservedPaths"); + // SaveSetting("umbracoReservedUrls"); + // SaveSetting("umbracoConfigurationStatus"); + //} - public static bool HideTopLevelNodeFromPath - { - get { return GlobalSettings.HideTopLevelNodeFromPath; } - set { ConfigurationManager.AppSettings.Set("umbracoHideTopLevelNodeFromPath", value ? "true" : "false"); } - } - - public static bool UseDirectoryUrls - { - get { return GlobalSettings.UseDirectoryUrls; } - set { ConfigurationManager.AppSettings.Set("umbracoUseDirectoryUrls", value ? "true" : "false"); } - } - - public static string UmbracoPath - { - get { return GlobalSettings.Path; } - set { ConfigurationManager.AppSettings.Set("umbracoPath", value); } - } - - public static string ReservedPaths - { - get { return GlobalSettings.ReservedPaths; } - set { GlobalSettings.ReservedPaths = value; } - } - - public static string ReservedUrls - { - get { return GlobalSettings.ReservedUrls; } - set { GlobalSettings.ReservedUrls = value; } - } - - public static string ConfigurationStatus - { - get { return GlobalSettings.ConfigurationStatus; } - set { ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", value); } - } + // reset & defaults - static SettingsForTests() - { - SaveSettings(); - } + //static SettingsForTests() + //{ + // //SaveSettings(); + //} public static void Reset() { - ResetUmbracoSettings(); + ResetSettings(); GlobalSettings.Reset(); - foreach (var kvp in SavedAppSettings) - ConfigurationManager.AppSettings.Set(kvp.Key, kvp.Value); + //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; + //// 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 static void ResetUmbracoSettings() + private static void ResetSettings() { - ConfigureSettings(GetDefault()); + _defaultGlobalSettings = null; + ConfigureSettings(GetDefaultUmbracoSettings()); + ConfigureSettings(GetDefaultGlobalSettings()); } - private static IUmbracoSettingsSection _defaultSettings; + private static IUmbracoSettingsSection _defaultUmbracoSettings; + private static IGlobalSettings _defaultGlobalSettings; - internal static IUmbracoSettingsSection GetDefault() + internal static IGlobalSettings GetDefaultGlobalSettings() { - if (_defaultSettings == null) + if (_defaultGlobalSettings == null) { + _defaultGlobalSettings = GenerateMockGlobalSettings(); + } + return _defaultGlobalSettings; + } + + internal static IUmbracoSettingsSection GetDefaultUmbracoSettings() + { + if (_defaultUmbracoSettings == null) + { + //TODO: Just make this mocks instead of reading from the config + var config = new FileInfo(TestHelper.MapPathForTest("~/Configurations/UmbracoSettings/web.config")); var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = config.FullName }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); - _defaultSettings = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection; + _defaultUmbracoSettings = configuration.GetSection("umbracoConfiguration/defaultSettings") as UmbracoSettingsSection; } - return _defaultSettings; + return _defaultUmbracoSettings; } } } diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 6ee99ef582..50cb115eae 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -7,6 +7,7 @@ using System.Web; using LightInject; using Moq; using Umbraco.Core; +using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.Logging; @@ -112,16 +113,20 @@ namespace Umbraco.Tests.TestHelpers publishedSnapshotServiceMock.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedSnapshot); var publishedSnapshotService = publishedSnapshotServiceMock.Object; - var webSecurity = new Mock(null, null).Object; - var settings = GetUmbracoSettings(); + var umbracoSettings = GetUmbracoSettings(); + var globalSettings = GetGlobalSettings(); + var webSecurity = new Mock(null, null, globalSettings).Object; var urlProviders = Enumerable.Empty(); if (accessor == null) accessor = new TestUmbracoContextAccessor(); - return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, settings, urlProviders, true); + return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, true); } public IUmbracoSettingsSection GetUmbracoSettings() { + //fixme Why not use the SettingsForTest.GenerateMock ... ? + //fixme Shouldn't we use the default ones so they are the same instance for each test? + var umbracoSettingsMock = new Mock(); var webRoutingSectionMock = new Mock(); webRoutingSectionMock.Setup(x => x.UrlProviderMode).Returns(UrlProviderMode.Auto.ToString()); @@ -129,6 +134,11 @@ namespace Umbraco.Tests.TestHelpers return umbracoSettingsMock.Object; } + public IGlobalSettings GetGlobalSettings() + { + return SettingsForTests.GetDefaultGlobalSettings(); + } + #region Inner classes private class MockDbConnection : DbConnection diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index d29ba5e41e..b0676f2eb9 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -9,6 +9,7 @@ using NPoco; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -89,13 +90,14 @@ namespace Umbraco.Tests.TestHelpers /// /// Gets a ServiceContext. /// - /// A repository factory. - /// A database unit of work provider. + /// /// A cache. /// A logger. + /// /// An event messages factory. /// Some url segment providers. /// A container. + /// /// A ServiceContext. /// Should be used sparingly for integration tests only - for unit tests /// just mock the services to be passed to the ctor of the ServiceContext. @@ -103,6 +105,7 @@ namespace Umbraco.Tests.TestHelpers IScopeProvider scopeProvider, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, + IGlobalSettings globalSettings, IEventMessagesFactory eventMessagesFactory, IEnumerable urlSegmentProviders, IServiceFactory container = null) @@ -156,10 +159,10 @@ namespace Umbraco.Tests.TestHelpers var runtimeState = Mock.Of(); var idkMap = new IdkMap(scopeProvider); - var userService = GetLazyService(container, c => new UserService(scopeProvider, logger, eventMessagesFactory, runtimeState, GetRepo(c), GetRepo(c))); + var userService = GetLazyService(container, c => new UserService(scopeProvider, logger, eventMessagesFactory, runtimeState, GetRepo(c), GetRepo(c),globalSettings)); var dataTypeService = GetLazyService(container, c => new DataTypeService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var contentService = GetLazyService(container, c => new ContentService(scopeProvider, logger, eventMessagesFactory, mediaFileSystem, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); - var notificationService = GetLazyService(container, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, logger, GetRepo(c))); + var notificationService = GetLazyService(container, c => new NotificationService(scopeProvider, userService.Value, contentService.Value, logger, GetRepo(c),globalSettings)); var serverRegistrationService = GetLazyService(container, c => new ServerRegistrationService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var memberGroupService = GetLazyService(container, c => new MemberGroupService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var memberService = GetLazyService(container, c => new MemberService(scopeProvider, logger, eventMessagesFactory, memberGroupService.Value, mediaFileSystem, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 83042c4897..9a2828fd9f 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -134,7 +134,9 @@ namespace Umbraco.Tests.TestHelpers } // ensure the configuration matches the current version for tests - SettingsForTests.ConfigurationStatus = UmbracoVersion.Current.ToString(3); + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.ConfigurationStatus).Returns(UmbracoVersion.Current.ToString(3)); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); using (ProfilingLogger.TraceDuration("Initialize database.")) { @@ -247,22 +249,25 @@ namespace Umbraco.Tests.TestHelpers var cache = NullCacheProvider.Instance; ContentTypesCache = new PublishedContentTypeCache( - Current.Services.ContentTypeService, - Current.Services.MediaTypeService, - Current.Services.MemberTypeService, + Container.GetInstance(), + Container.GetInstance(), + Container.GetInstance(), Container.GetInstance(), - Current.Logger); + Logger); // testing=true so XmlStore will not use the file nor the database var publishedSnapshotAccessor = new UmbracoContextPublishedSnapshotAccessor(Umbraco.Web.Composing.Current.UmbracoContextAccessor); var service = new PublishedSnapshotService( - Current.Services, + ServiceContext, Container.GetInstance(), - (ScopeProvider) Current.ScopeProvider, + ScopeProvider, cache, publishedSnapshotAccessor, - Current.Container.GetInstance(), Current.Container.GetInstance(), Current.Container.GetInstance(), - Current.Logger, ContentTypesCache, null, true, Options.PublishedRepositoryEvents); + Container.GetInstance(), Container.GetInstance(), Container.GetInstance(), + Logger, + Container.GetInstance(), + ContentTypesCache, + null, true, Options.PublishedRepositoryEvents); // initialize PublishedCacheService content with an Xml source service.XmlStore.GetXmlDocument = () => @@ -331,14 +336,14 @@ namespace Umbraco.Tests.TestHelpers } catch (Exception ex) { - Core.Composing.Current.Logger.Error("Could not remove the old database file", ex); + Logger.Error("Could not remove the old database file", ex); // swallow this exception - that's because a sub class might require further teardown logic onFail?.Invoke(ex); } } - protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null) + protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null, IGlobalSettings globalSettings = null) { // ensure we have a PublishedCachesService var service = PublishedSnapshotService as PublishedSnapshotService; @@ -358,9 +363,10 @@ namespace Umbraco.Tests.TestHelpers var umbracoContext = new UmbracoContext( httpContext, service, - new WebSecurity(httpContext, Core.Composing.Current.Services.UserService), - umbracoSettings ?? SettingsForTests.GetDefault(), - urlProviders ?? Enumerable.Empty()); + new WebSecurity(httpContext, Container.GetInstance(), Container.GetInstance()), + umbracoSettings ?? Container.GetInstance(), + urlProviders ?? Enumerable.Empty(), + globalSettings ?? Container.GetInstance()); if (setSingleton) Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index b5c10fa4a3..003ba9ff4d 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Components; using Umbraco.Core.Composing; using Umbraco.Core.Composing.CompositionRoots; +using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -225,7 +226,7 @@ namespace Umbraco.Tests.Testing private static TypeLoader CreateCommonPluginManager(IServiceFactory f) { - return new TypeLoader(f.GetInstance().RuntimeCache, f.GetInstance(), false) + return new TypeLoader(f.GetInstance().RuntimeCache, f.GetInstance(), f.GetInstance(), false) { AssembliesToScan = new[] { @@ -249,15 +250,20 @@ namespace Umbraco.Tests.Testing { if (withApplication == false) return; - var settings = SettingsForTests.GetDefault(); + var umbracoSettings = SettingsForTests.GetDefaultUmbracoSettings(); + var globalSettings = SettingsForTests.GetDefaultGlobalSettings(); + //apply these globally + SettingsForTests.ConfigureSettings(umbracoSettings); + SettingsForTests.ConfigureSettings(globalSettings); // default Datalayer/Repositories/SQL/Database/etc... Container.RegisterFrom(); // register basic stuff that might need to be there for some container resolvers to work - Container.RegisterSingleton(factory => SettingsForTests.GetDefault()); - Container.RegisterSingleton(factory => settings.Content); - Container.RegisterSingleton(factory => settings.Templates); + Container.RegisterSingleton(factory => umbracoSettings); + Container.RegisterSingleton(factory => globalSettings); + Container.RegisterSingleton(factory => umbracoSettings.Content); + Container.RegisterSingleton(factory => umbracoSettings.Templates); Container.Register(factory => new MediaFileSystem(Mock.Of())); Container.RegisterSingleton(factory => ExamineManager.Instance); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 017df4450d..90455f910e 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -607,7 +607,16 @@ $(NuGetPackageFolders.Split(';')[0]) + + + + + + + + + @@ -616,5 +625,5 @@ - + \ No newline at end of file diff --git a/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs b/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs index 5f55ed2bd0..4016510f40 100644 --- a/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs +++ b/src/Umbraco.Tests/UmbracoExamine/ExamineBaseTest.cs @@ -32,7 +32,7 @@ namespace Umbraco.Tests.UmbracoExamine { base.Compose(); - Container.RegisterSingleton(_ => new DefaultShortStringHelper(SettingsForTests.GetDefault())); + Container.RegisterSingleton(_ => new DefaultShortStringHelper(SettingsForTests.GetDefaultUmbracoSettings())); } } } diff --git a/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs b/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs index f42a02efe4..669c607aea 100644 --- a/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs @@ -14,7 +14,8 @@ namespace Umbraco.Tests.Web.Controllers public void Ensure_Same_Area1() { Assert.Throws(() => - new PluginControllerArea(new PluginControllerMetadata[] + new PluginControllerArea(TestObjects.GetGlobalSettings(), + new PluginControllerMetadata[] { PluginController.GetMetadata(typeof(Plugin1Controller)), PluginController.GetMetadata(typeof(Plugin2Controller)), @@ -26,7 +27,8 @@ namespace Umbraco.Tests.Web.Controllers public void Ensure_Same_Area3() { Assert.Throws(() => - new PluginControllerArea(new PluginControllerMetadata[] + new PluginControllerArea(TestObjects.GetGlobalSettings(), + new PluginControllerMetadata[] { PluginController.GetMetadata(typeof(Plugin1Controller)), PluginController.GetMetadata(typeof(Plugin2Controller)), @@ -37,7 +39,8 @@ namespace Umbraco.Tests.Web.Controllers [Test] public void Ensure_Same_Area2() { - var area = new PluginControllerArea(new PluginControllerMetadata[] + var area = new PluginControllerArea(TestObjects.GetGlobalSettings(), + new PluginControllerMetadata[] { PluginController.GetMetadata(typeof(Plugin1Controller)), PluginController.GetMetadata(typeof(Plugin2Controller)) diff --git a/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs b/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs index 2afeb3ffba..1a61882949 100644 --- a/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs @@ -58,6 +58,7 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Matches_Default_Index() { + var globalSettings = TestObjects.GetGlobalSettings(); var attr = new RenderIndexActionSelectorAttribute(); var req = new RequestContext(); //var appCtx = new ApplicationContext( @@ -67,9 +68,10 @@ namespace Umbraco.Tests.Web.Mvc Current.UmbracoContextAccessor, Mock.Of(), Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new MatchesDefaultIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -82,15 +84,17 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Matches_Overriden_Index() { + var globalSettings = TestObjects.GetGlobalSettings(); var attr = new RenderIndexActionSelectorAttribute(); var req = new RequestContext(); var umbCtx = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, Mock.Of(), Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new MatchesOverriddenIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -103,15 +107,17 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Matches_Custom_Index() { + var globalSettings = TestObjects.GetGlobalSettings(); var attr = new RenderIndexActionSelectorAttribute(); var req = new RequestContext(); var umbCtx = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, Mock.Of(), Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new MatchesCustomIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -124,15 +130,17 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Matches_Async_Index_Same_Signature() { + var globalSettings = TestObjects.GetGlobalSettings(); var attr = new RenderIndexActionSelectorAttribute(); var req = new RequestContext(); var umbCtx = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, Mock.Of(), Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new MatchesAsyncIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index ea33f5d81e..d9a12751c0 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -36,13 +36,15 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Can_Construct_And_Get_Result() { + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, new Mock().Object, Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new TestSurfaceController { UmbracoContext = umbracoContext }; @@ -55,13 +57,15 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Umbraco_Context_Not_Null() { + var globalSettings = TestObjects.GetGlobalSettings(); var umbCtx = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, new Mock().Object, Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var ctrl = new TestSurfaceController { UmbracoContext = umbCtx }; @@ -72,13 +76,15 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Umbraco_Helper_Not_Null() { + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, new Mock().Object, Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), + globalSettings, true); var controller = new TestSurfaceController { UmbracoContext = umbracoContext }; @@ -95,14 +101,16 @@ namespace Umbraco.Tests.Web.Mvc publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of()); var publishedSnapshotService = new Mock(); publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedSnapshot.Object); + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, new Mock().Object, publishedSnapshotService.Object, - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, Mock.Of(section => section.WebRouting == Mock.Of(routingSection => routingSection.UrlProviderMode == "AutoLegacy")), Enumerable.Empty(), + globalSettings, true); var helper = new UmbracoHelper( @@ -130,14 +138,16 @@ namespace Umbraco.Tests.Web.Mvc public void Mock_Current_Page() { var webRoutingSettings = Mock.Of(section => section.UrlProviderMode == "AutoLegacy"); + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = UmbracoContext.EnsureContext( Current.UmbracoContextAccessor, new Mock().Object, Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, Mock.Of(section => section.WebRouting == webRoutingSettings), Enumerable.Empty(), + globalSettings, true); var content = Mock.Of(publishedContent => publishedContent.Id == 12345); diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index f010cc6958..053a1f7c5d 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -388,7 +388,7 @@ namespace Umbraco.Tests.Web.Mvc ViewContext GetViewContext() { - var settings = SettingsForTests.GetDefault(); + var settings = SettingsForTests.GetDefaultUmbracoSettings(); var logger = Mock.Of(); var umbracoContext = GetUmbracoContext( logger, settings, @@ -425,16 +425,17 @@ namespace Umbraco.Tests.Web.Mvc var factory = Mock.Of(); _service = new PublishedSnapshotService(svcCtx, factory, scopeProvider, cache, Enumerable.Empty(), null, null, null, null, - Current.Logger, null, true, false); // no events + Current.Logger, TestObjects.GetGlobalSettings(), null, true, false); // no events var http = GetHttpContextFactory(url, routeData).HttpContext; var ctx = new UmbracoContext( GetHttpContextFactory(url, routeData).HttpContext, _service, - new WebSecurity(http, Current.Services.UserService), + new WebSecurity(http, Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), - Enumerable.Empty()); + Enumerable.Empty(), + TestObjects.GetGlobalSettings()); //if (setSingleton) //{ diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index 5e33aec072..8b52ce1893 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -36,7 +36,8 @@ namespace Umbraco.Tests.Web // fixme - bad in a unit test - but Udi has a static ctor that wants it?! var container = new Mock(); - container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns(new TypeLoader(NullCacheProvider.Instance, new ProfilingLogger(Mock.Of(), Mock.Of()))); + container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns( + new TypeLoader(NullCacheProvider.Instance, SettingsForTests.GenerateMockGlobalSettings(), new ProfilingLogger(Mock.Of(), Mock.Of()))); container.Setup(x => x.GetInstance(typeof (ServiceContext))).Returns(serviceContext); Current.Container = container.Object; @@ -77,15 +78,18 @@ namespace Umbraco.Tests.Web return "/my-test-url"; }); + var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); + using (var umbCtx = UmbracoContext.EnsureContext( Umbraco.Web.Composing.Current.UmbracoContextAccessor, Mock.Of(), Mock.Of(), - new Mock(null, null).Object, + new Mock(null, null, globalSettings).Object, //setup a quick mock of the WebRouting section Mock.Of(section => section.WebRouting == Mock.Of(routingSection => routingSection.UrlProviderMode == "AutoLegacy")), //pass in the custom url provider new[]{ testUrlProvider.Object }, + globalSettings, true)) { var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider); diff --git a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs index 7b53d624a0..86339c309f 100644 --- a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs +++ b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs @@ -26,9 +26,10 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService), + new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), - new List()); + new List(), + TestObjects.GetGlobalSettings()); var r1 = new RouteData(); r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx); @@ -42,9 +43,10 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService), + new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), - new List()); + new List(), + TestObjects.GetGlobalSettings()); var r1 = new RouteData(); r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx); @@ -68,9 +70,10 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService), + new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), - new List()); + new List(), + TestObjects.GetGlobalSettings()); var httpContext = Mock.Of(); diff --git a/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs b/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs index a148ac6e05..7f9f6b3019 100644 --- a/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs +++ b/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs @@ -13,7 +13,7 @@ namespace Umbraco.Web.UI.Umbraco protected void Page_Load(object sender, EventArgs e) { Response.Status = "301 Moved Permanently"; - Response.AddHeader("Location", GlobalSettings.Path); + Response.AddHeader("Location", UmbracoConfig.For.GlobalSettings().Path); } } } diff --git a/src/Umbraco.Web.UI/umbraco/Views/Default.cshtml b/src/Umbraco.Web.UI/umbraco/Views/Default.cshtml index 22e4c90962..7387072247 100644 --- a/src/Umbraco.Web.UI/umbraco/Views/Default.cshtml +++ b/src/Umbraco.Web.UI/umbraco/Views/Default.cshtml @@ -11,6 +11,7 @@ @using Umbraco.Web @using Umbraco.Web.Editors @using umbraco +@using Umbraco.Core.Configuration @inherits System.Web.Mvc.WebViewPage @@ -94,7 +95,7 @@ view="ysodOverlay.view"> - @Html.BareMinimumServerVariablesScript(Url, Url.Action("ExternalLogin", "BackOffice", new { area = ViewBag.UmbracoPath }), Model.Features) + @Html.BareMinimumServerVariablesScript(Url, Url.Action("ExternalLogin", "BackOffice", new { area = ViewBag.UmbracoPath }), Model.Features, UmbracoConfig.For.GlobalSettings())