diff --git a/src/Umbraco.Configuration/ActiveDirectorySettings.cs b/src/Umbraco.Configuration/ActiveDirectorySettings.cs new file mode 100644 index 0000000000..d85def7f33 --- /dev/null +++ b/src/Umbraco.Configuration/ActiveDirectorySettings.cs @@ -0,0 +1,15 @@ +using System.Configuration; +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration +{ + public class ActiveDirectorySettings : IActiveDirectorySettings + { + public ActiveDirectorySettings() + { + ActiveDirectoryDomain = ConfigurationManager.AppSettings["ActiveDirectoryDomain"]; + } + + public string ActiveDirectoryDomain { get; } + } +} diff --git a/src/Umbraco.Configuration/ConfigsFactory.cs b/src/Umbraco.Configuration/ConfigsFactory.cs index 3979720f9b..3742b7d7fa 100644 --- a/src/Umbraco.Configuration/ConfigsFactory.cs +++ b/src/Umbraco.Configuration/ConfigsFactory.cs @@ -12,6 +12,12 @@ namespace Umbraco.Core.Configuration public ICoreDebug CoreDebug { get; } = new CoreDebug(); public IMachineKeyConfig MachineKeyConfig { get; } = new MachineKeyConfig(); + public IIndexCreatorSettings IndexCreatorSettings { get; } = new IndexCreatorSettings(); + public INuCacheSettings NuCacheSettings { get; } = new NuCacheSettings(); + public ITypeFinderSettings TypeFinderSettings { get; } = new TypeFinderSettings(); + public IRuntimeSettings RuntimeSettings { get; } = new RuntimeSettings(); + public IActiveDirectorySettings ActiveDirectorySettings { get; } = new ActiveDirectorySettings(); + public IExceptionFilterSettings ExceptionFilterSettings { get; } = new ExceptionFilterSettings(); public IUmbracoSettingsSection UmbracoSettings { get; } @@ -31,6 +37,16 @@ namespace Umbraco.Core.Configuration configs.Add(() => CoreDebug); configs.Add(() => MachineKeyConfig); configs.Add(() => new ConnectionStrings(ioHelper)); + configs.Add(() => new ModelsBuilderConfig(ioHelper)); + + + configs.Add(() => IndexCreatorSettings); + configs.Add(() => NuCacheSettings); + configs.Add(() => TypeFinderSettings); + configs.Add(() => RuntimeSettings); + configs.Add(() => ActiveDirectorySettings); + configs.Add(() => ExceptionFilterSettings); + configs.AddCoreConfigs(ioHelper); return configs; } diff --git a/src/Umbraco.Configuration/ExceptionFilterSettings.cs b/src/Umbraco.Configuration/ExceptionFilterSettings.cs new file mode 100644 index 0000000000..628b8755cc --- /dev/null +++ b/src/Umbraco.Configuration/ExceptionFilterSettings.cs @@ -0,0 +1,18 @@ +using System.Configuration; +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration +{ + public class ExceptionFilterSettings : IExceptionFilterSettings + { + public ExceptionFilterSettings() + { + if (bool.TryParse(ConfigurationManager.AppSettings["Umbraco.Web.DisableModelBindingExceptionFilter"], + out var disabled)) + { + Disabled = disabled; + } + } + public bool Disabled { get; } + } +} diff --git a/src/Umbraco.Configuration/GlobalSettings.cs b/src/Umbraco.Configuration/GlobalSettings.cs index a44f7ae636..56e64fff31 100644 --- a/src/Umbraco.Configuration/GlobalSettings.cs +++ b/src/Umbraco.Configuration/GlobalSettings.cs @@ -382,6 +382,10 @@ namespace Umbraco.Core.Configuration private string _databaseFactoryServerVersion; public string DatabaseFactoryServerVersion => GetterWithDefaultValue(Constants.AppSettings.Debug.DatabaseFactoryServerVersion, string.Empty, ref _databaseFactoryServerVersion); + private string _mainDomLock; + + public string MainDomLock => GetterWithDefaultValue(Constants.AppSettings.MainDomLock, string.Empty, ref _mainDomLock); + private T GetterWithDefaultValue(string appSettingKey, T defaultValue, ref T backingField) { if (backingField != null) return backingField; diff --git a/src/Umbraco.Configuration/IndexCreatorSettings.cs b/src/Umbraco.Configuration/IndexCreatorSettings.cs new file mode 100644 index 0000000000..00d1a29dba --- /dev/null +++ b/src/Umbraco.Configuration/IndexCreatorSettings.cs @@ -0,0 +1,15 @@ +using System.Configuration; +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration +{ + public class IndexCreatorSettings : IIndexCreatorSettings + { + public IndexCreatorSettings() + { + LuceneDirectoryFactory = ConfigurationManager.AppSettings["Umbraco.Examine.LuceneDirectoryFactory"]; + } + + public string LuceneDirectoryFactory { get; } + } +} diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsBuilderConfig.cs b/src/Umbraco.Configuration/ModelsBuilderConfig.cs similarity index 94% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsBuilderConfig.cs rename to src/Umbraco.Configuration/ModelsBuilderConfig.cs index d0137ed2b2..151e9908a1 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsBuilderConfig.cs +++ b/src/Umbraco.Configuration/ModelsBuilderConfig.cs @@ -2,11 +2,11 @@ using System.Configuration; using System.IO; using System.Threading; -using System.Web.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.IO; -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Configuration { /// /// Represents the models builder configuration. @@ -21,7 +21,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Configuration private object _flagOutOfDateModelsLock; private bool _flagOutOfDateModelsConfigured; private bool _flagOutOfDateModels; - public const string DefaultModelsNamespace = "Umbraco.Web.PublishedModels"; + public string DefaultModelsDirectory => _ioHelper.MapPath("~/App_Data/Models"); @@ -37,7 +37,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Configuration Enable = ConfigurationManager.AppSettings[Prefix + "Enable"] == "true"; // ensure defaults are initialized for tests - ModelsNamespace = DefaultModelsNamespace; + ModelsNamespace = Constants.ModelsBuilder.DefaultModelsNamespace; ModelsDirectory = DefaultModelsDirectory; DebugLevel = 0; @@ -95,7 +95,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Configuration Enable = enable; _modelsMode = modelsMode; - ModelsNamespace = string.IsNullOrWhiteSpace(modelsNamespace) ? DefaultModelsNamespace : modelsNamespace; + ModelsNamespace = string.IsNullOrWhiteSpace(modelsNamespace) ? Constants.ModelsBuilder.DefaultModelsNamespace : modelsNamespace; EnableFactory = enableFactory; _flagOutOfDateModels = flagOutOfDateModels; ModelsDirectory = string.IsNullOrWhiteSpace(modelsDirectory) ? DefaultModelsDirectory : modelsDirectory; @@ -174,8 +174,13 @@ namespace Umbraco.ModelsBuilder.Embedded.Configuration { get { - var section = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation"); - return section != null && section.Debug; + if (ConfigurationManager.GetSection("system.web/compilation") is ConfigurationSection section && + bool.TryParse(section.ElementInformation.Properties["debug"].Value.ToString(), out var isDebug)) + { + return isDebug; + } + + return false; } } diff --git a/src/Umbraco.Configuration/NuCacheSettings.cs b/src/Umbraco.Configuration/NuCacheSettings.cs new file mode 100644 index 0000000000..c3a286d33d --- /dev/null +++ b/src/Umbraco.Configuration/NuCacheSettings.cs @@ -0,0 +1,14 @@ +using System.Configuration; +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration +{ + public class NuCacheSettings : INuCacheSettings + { + public NuCacheSettings() + { + BTreeBlockSize = ConfigurationManager.AppSettings["Umbraco.Web.PublishedCache.NuCache.BTree.BlockSize"]; + } + public string BTreeBlockSize { get; } + } +} diff --git a/src/Umbraco.Configuration/RuntimeSettings.cs b/src/Umbraco.Configuration/RuntimeSettings.cs new file mode 100644 index 0000000000..6dc8d6f832 --- /dev/null +++ b/src/Umbraco.Configuration/RuntimeSettings.cs @@ -0,0 +1,29 @@ +using System.Configuration; +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration +{ + public class RuntimeSettings : IRuntimeSettings + { + public RuntimeSettings() + { + if (ConfigurationManager.GetSection("system.web/httpRuntime") is ConfigurationSection section) + { + var maxRequestLengthProperty = section.ElementInformation.Properties["maxRequestLength"]; + if (maxRequestLengthProperty != null && maxRequestLengthProperty.Value is int requestLength) + { + MaxRequestLength = requestLength; + } + + var maxQueryStringProperty = section.ElementInformation.Properties["maxQueryStringLength"]; + if (maxQueryStringProperty != null && maxQueryStringProperty.Value is int maxQueryStringLength) + { + MaxQueryStringLength = maxQueryStringLength; + } + } + } + public int? MaxQueryStringLength { get; } + public int? MaxRequestLength { get; } + + } +} diff --git a/src/Umbraco.Configuration/TypeFinderSettings.cs b/src/Umbraco.Configuration/TypeFinderSettings.cs new file mode 100644 index 0000000000..bb3063d7bf --- /dev/null +++ b/src/Umbraco.Configuration/TypeFinderSettings.cs @@ -0,0 +1,17 @@ +using System.Configuration; +using Umbraco.Core.Configuration; +using Umbraco.Core; + +namespace Umbraco.Configuration +{ + public class TypeFinderSettings : ITypeFinderSettings + { + public TypeFinderSettings() + { + AssembliesAcceptingLoadExceptions = ConfigurationManager.AppSettings[ + Constants.AppSettings.AssembliesAcceptingLoadExceptions]; + } + + public string AssembliesAcceptingLoadExceptions { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs b/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs new file mode 100644 index 0000000000..e6b9202c06 --- /dev/null +++ b/src/Umbraco.Core/Configuration/IActiveDirectorySettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration +{ + public interface IActiveDirectorySettings + { + string ActiveDirectoryDomain { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs b/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs new file mode 100644 index 0000000000..169c04da5f --- /dev/null +++ b/src/Umbraco.Core/Configuration/IExceptionFilterSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration +{ + public interface IExceptionFilterSettings + { + bool Disabled { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/IGlobalSettings.cs b/src/Umbraco.Core/Configuration/IGlobalSettings.cs index 1b1f328142..ffc52130cc 100644 --- a/src/Umbraco.Core/Configuration/IGlobalSettings.cs +++ b/src/Umbraco.Core/Configuration/IGlobalSettings.cs @@ -95,5 +95,6 @@ bool DisableElectionForSingleServer { get; } string RegisterType { get; } string DatabaseFactoryServerVersion { get; } + string MainDomLock { get; } } } diff --git a/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs b/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs new file mode 100644 index 0000000000..b3e2854a0d --- /dev/null +++ b/src/Umbraco.Core/Configuration/IIndexCreatorSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration +{ + public interface IIndexCreatorSettings + { + string LuceneDirectoryFactory { get; } + } +} diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs b/src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs similarity index 87% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs rename to src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs index 7e96aec60e..6a071ac277 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs +++ b/src/Umbraco.Core/Configuration/IModelsBuilderConfig.cs @@ -1,4 +1,4 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Core.Configuration { public interface IModelsBuilderConfig { diff --git a/src/Umbraco.Core/Configuration/INuCacheSettings.cs b/src/Umbraco.Core/Configuration/INuCacheSettings.cs new file mode 100644 index 0000000000..c6524297a6 --- /dev/null +++ b/src/Umbraco.Core/Configuration/INuCacheSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration +{ + public interface INuCacheSettings + { + string BTreeBlockSize { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/IRuntimeSettings.cs b/src/Umbraco.Core/Configuration/IRuntimeSettings.cs new file mode 100644 index 0000000000..915e774186 --- /dev/null +++ b/src/Umbraco.Core/Configuration/IRuntimeSettings.cs @@ -0,0 +1,8 @@ +namespace Umbraco.Core.Configuration +{ + public interface IRuntimeSettings + { + int? MaxQueryStringLength { get; } + int? MaxRequestLength { get; } + } +} diff --git a/src/Umbraco.Core/Configuration/ITypeFinderSettings.cs b/src/Umbraco.Core/Configuration/ITypeFinderSettings.cs new file mode 100644 index 0000000000..15e72a1f40 --- /dev/null +++ b/src/Umbraco.Core/Configuration/ITypeFinderSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Configuration +{ + public interface ITypeFinderSettings + { + string AssembliesAcceptingLoadExceptions { get; } + } +} diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs b/src/Umbraco.Core/Configuration/ModelsMode.cs similarity index 92% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs rename to src/Umbraco.Core/Configuration/ModelsMode.cs index e0286fdab1..2483367394 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs +++ b/src/Umbraco.Core/Configuration/ModelsMode.cs @@ -1,4 +1,4 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Core.Configuration { /// /// Defines the models generation modes. @@ -8,7 +8,7 @@ /// /// Do not generate models. /// - Nothing = 0, // default value + Nothing = 0, // default value /// /// Generate models in memory. diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs b/src/Umbraco.Core/Configuration/ModelsModeExtensions.cs similarity index 94% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs rename to src/Umbraco.Core/Configuration/ModelsModeExtensions.cs index be638729ea..8d1b51cd28 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs +++ b/src/Umbraco.Core/Configuration/ModelsModeExtensions.cs @@ -1,4 +1,6 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +using Umbraco.Core.Configuration; + +namespace Umbraco.Configuration { /// /// Provides extensions for the enumeration. diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ITypeFinderConfig.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ITypeFinderConfig.cs index fd5b18ed39..a290c26d15 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ITypeFinderConfig.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/ITypeFinderConfig.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace Umbraco.Core.Configuration.UmbracoSettings { diff --git a/src/Umbraco.Core/Constants-ModelsBuilder.cs b/src/Umbraco.Core/Constants-ModelsBuilder.cs new file mode 100644 index 0000000000..28e70ed383 --- /dev/null +++ b/src/Umbraco.Core/Constants-ModelsBuilder.cs @@ -0,0 +1,17 @@ +namespace Umbraco.Core +{ + /// + /// Defines constants. + /// + public static partial class Constants + { + /// + /// Defines constants for ModelsBuilder. + /// + public static class ModelsBuilder + { + + public const string DefaultModelsNamespace = "Umbraco.Web.PublishedModels"; + } + } +} diff --git a/src/Umbraco.Core/Constants-Web.cs b/src/Umbraco.Core/Constants-Web.cs index a1e138116d..5b64319fb0 100644 --- a/src/Umbraco.Core/Constants-Web.cs +++ b/src/Umbraco.Core/Constants-Web.cs @@ -34,6 +34,7 @@ /// The header name that angular uses to pass in the token to validate the cookie /// public const string AngularHeadername = "X-UMB-XSRF-TOKEN"; + } } } diff --git a/src/Umbraco.Core/Cookie/ICookieManager.cs b/src/Umbraco.Core/Cookie/ICookieManager.cs index af0ee7b1f6..0eced07b37 100644 --- a/src/Umbraco.Core/Cookie/ICookieManager.cs +++ b/src/Umbraco.Core/Cookie/ICookieManager.cs @@ -7,4 +7,5 @@ namespace Umbraco.Core.Cookie void SetCookieValue(string cookieName, string value); bool HasCookie(string cookieName); } + } diff --git a/src/Umbraco.Core/Request/IRequestAccessor.cs b/src/Umbraco.Core/Request/IRequestAccessor.cs new file mode 100644 index 0000000000..63a8de6b1e --- /dev/null +++ b/src/Umbraco.Core/Request/IRequestAccessor.cs @@ -0,0 +1,13 @@ +using System; +using Umbraco.Web.Routing; + +namespace Umbraco.Core.Request +{ + public interface IRequestAccessor + { + string GetRequestValue(string name); + string GetQueryStringValue(string culture); + event EventHandler EndRequest; + event EventHandler RouteAttempt; + } +} diff --git a/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs b/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs similarity index 88% rename from src/Umbraco.Web/Routing/ContentFinderByIdPath.cs rename to src/Umbraco.Core/Routing/ContentFinderByIdPath.cs index bf7d5ef7c4..c4bfd5a697 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByIdPath.cs @@ -4,6 +4,7 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Models.PublishedContent; using System.Globalization; +using Umbraco.Core.Request; namespace Umbraco.Web.Routing { @@ -16,14 +17,14 @@ namespace Umbraco.Web.Routing public class ContentFinderByIdPath : IContentFinder { private readonly ILogger _logger; - private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IRequestAccessor _requestAccessor; private readonly IWebRoutingSection _webRoutingSection; - public ContentFinderByIdPath(IWebRoutingSection webRoutingSection, ILogger logger, IHttpContextAccessor httpContextAccessor) + public ContentFinderByIdPath(IWebRoutingSection webRoutingSection, ILogger logger, IRequestAccessor requestAccessor) { _webRoutingSection = webRoutingSection ?? throw new System.ArgumentNullException(nameof(webRoutingSection)); _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); - _httpContextAccessor = httpContextAccessor; + _requestAccessor = requestAccessor; } /// @@ -56,12 +57,14 @@ namespace Umbraco.Web.Routing if (node != null) { - var httpContext = _httpContextAccessor.GetRequiredHttpContext(); + + var cultureFromQuerystring = _requestAccessor.GetQueryStringValue("culture"); + //if we have a node, check if we have a culture in the query string - if (httpContext.Request.QueryString.ContainsKey("culture")) + if (!string.IsNullOrEmpty(cultureFromQuerystring)) { //we're assuming it will match a culture, if an invalid one is passed in, an exception will throw (there is no TryGetCultureInfo method), i think this is ok though - frequest.Culture = CultureInfo.GetCultureInfo(httpContext.Request.QueryString["culture"]); + frequest.Culture = CultureInfo.GetCultureInfo(cultureFromQuerystring); } frequest.PublishedContent = node; diff --git a/src/Umbraco.Web/Routing/ContentFinderByPageIdQuery.cs b/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs similarity index 69% rename from src/Umbraco.Web/Routing/ContentFinderByPageIdQuery.cs rename to src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs index fb79e13dbc..6a9adda5f8 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByPageIdQuery.cs +++ b/src/Umbraco.Core/Routing/ContentFinderByPageIdQuery.cs @@ -1,4 +1,6 @@ -namespace Umbraco.Web.Routing +using Umbraco.Core.Request; + +namespace Umbraco.Web.Routing { /// /// This looks up a document by checking for the umbPageId of a request/query string @@ -9,17 +11,17 @@ /// public class ContentFinderByPageIdQuery : IContentFinder { - private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IRequestAccessor _requestAccessor; - public ContentFinderByPageIdQuery(IHttpContextAccessor httpContextAccessor) + public ContentFinderByPageIdQuery(IRequestAccessor requestAccessor) { - _httpContextAccessor = httpContextAccessor; + _requestAccessor = requestAccessor; } public bool TryFindContent(IPublishedRequest frequest) { int pageId; - if (int.TryParse(_httpContextAccessor.GetRequiredHttpContext().Request["umbPageID"], out pageId)) + if (int.TryParse(_requestAccessor.GetRequestValue("umbPageID"), out pageId)) { var doc = frequest.UmbracoContext.Content.GetById(pageId); diff --git a/src/Umbraco.Web/Routing/PublishedRouter.cs b/src/Umbraco.Core/Routing/PublishedRouter.cs similarity index 88% rename from src/Umbraco.Web/Routing/PublishedRouter.cs rename to src/Umbraco.Core/Routing/PublishedRouter.cs index 1a6048e4ec..f521c3a95a 100644 --- a/src/Umbraco.Web/Routing/PublishedRouter.cs +++ b/src/Umbraco.Core/Routing/PublishedRouter.cs @@ -4,13 +4,12 @@ using System.Threading; using System.Globalization; using System.IO; using Umbraco.Core; -using Umbraco.Web.Composing; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.Request; using Umbraco.Core.Services; -using Umbraco.Web.Macros; using Umbraco.Web.Security; namespace Umbraco.Web.Routing @@ -23,13 +22,17 @@ namespace Umbraco.Web.Routing private readonly IWebRoutingSection _webRoutingSection; private readonly ContentFinderCollection _contentFinders; private readonly IContentLastChanceFinder _contentLastChanceFinder; - private readonly ServiceContext _services; private readonly IProfilingLogger _profilingLogger; private readonly IVariationContextAccessor _variationContextAccessor; private readonly ILogger _logger; private readonly IUmbracoSettingsSection _umbracoSettingsSection; - private readonly IHttpContextAccessor _httpContextAccessor; private readonly IPublishedUrlProvider _publishedUrlProvider; + private readonly IRequestAccessor _requestAccessor; + private readonly IPublishedValueFallback _publishedValueFallback; + private readonly IPublicAccessChecker _publicAccessChecker; + private readonly IFileService _fileService; + private readonly IContentTypeService _contentTypeService; + private readonly IPublicAccessService _publicAccessService; /// /// Initializes a new instance of the class. @@ -39,22 +42,30 @@ namespace Umbraco.Web.Routing ContentFinderCollection contentFinders, IContentLastChanceFinder contentLastChanceFinder, IVariationContextAccessor variationContextAccessor, - ServiceContext services, IProfilingLogger proflog, IUmbracoSettingsSection umbracoSettingsSection, - IHttpContextAccessor httpContextAccessor, - IPublishedUrlProvider publishedUrlProvider) + IPublishedUrlProvider publishedUrlProvider, + IRequestAccessor requestAccessor, + IPublishedValueFallback publishedValueFallback, + IPublicAccessChecker publicAccessChecker, + IFileService fileService, + IContentTypeService contentTypeService, + IPublicAccessService publicAccessService) { _webRoutingSection = webRoutingSection ?? throw new ArgumentNullException(nameof(webRoutingSection)); _contentFinders = contentFinders ?? throw new ArgumentNullException(nameof(contentFinders)); _contentLastChanceFinder = contentLastChanceFinder ?? throw new ArgumentNullException(nameof(contentLastChanceFinder)); - _services = services ?? throw new ArgumentNullException(nameof(services)); _profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog)); _variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor)); _logger = proflog; _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); - _httpContextAccessor = httpContextAccessor; _publishedUrlProvider = publishedUrlProvider; + _requestAccessor = requestAccessor; + _publishedValueFallback = publishedValueFallback; + _publicAccessChecker = publicAccessChecker; + _fileService = fileService; + _contentTypeService = contentTypeService; + _publicAccessService = publicAccessService; } /// @@ -358,7 +369,7 @@ namespace Umbraco.Web.Routing /// public ITemplate GetTemplate(string alias) { - return _services.FileService.GetTemplate(alias); + return _fileService.GetTemplate(alias); } /// @@ -498,7 +509,7 @@ namespace Umbraco.Web.Routing var redirect = false; var valid = false; IPublishedContent internalRedirectNode = null; - var internalRedirectId = request.PublishedContent.Value(Constants.Conventions.Content.InternalRedirectId, defaultValue: -1); + var internalRedirectId = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.InternalRedirectId, defaultValue: -1); if (internalRedirectId > 0) { @@ -508,7 +519,7 @@ namespace Umbraco.Web.Routing } else { - var udiInternalRedirectId = request.PublishedContent.Value(Constants.Conventions.Content.InternalRedirectId); + var udiInternalRedirectId = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.InternalRedirectId); if (udiInternalRedirectId != null) { // try and get the redirect node from a UDI Guid @@ -555,58 +566,34 @@ namespace Umbraco.Web.Routing var path = request.PublishedContent.Path; - var publicAccessAttempt = _services.PublicAccessService.IsProtected(path); + var publicAccessAttempt = _publicAccessService.IsProtected(path); if (publicAccessAttempt) { _logger.Debug("EnsurePublishedContentAccess: Page is protected, check for access"); - var membershipHelper = Current.Factory.GetInstance(); - - if (membershipHelper.IsLoggedIn() == false) + var status = _publicAccessChecker.HasMemberAccessToContent(request.PublishedContent.Id); + switch (status) { - _logger.Debug("EnsurePublishedContentAccess: Not logged in, redirect to login page"); - - var loginPageId = publicAccessAttempt.Result.LoginNodeId; - - if (loginPageId != request.PublishedContent.Id) - request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(loginPageId); - } - else if (_services.PublicAccessService.HasAccess(request.PublishedContent.Id, _services.ContentService, membershipHelper.CurrentUserName, membershipHelper.GetCurrentUserRoles()) == false) - { - _logger.Debug("EnsurePublishedContentAccess: Current member has not access, redirect to error page"); - var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; - if (errorPageId != request.PublishedContent.Id) - request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId); - } - else - { - // grab the current member - var member = membershipHelper.GetCurrentMember(); - // if the member has the "approved" and/or "locked out" properties, make sure they're correctly set before allowing access - var memberIsActive = true; - if (member != null) - { - if (member.HasProperty(Constants.Conventions.Member.IsApproved) == false) - memberIsActive = member.Value(Constants.Conventions.Member.IsApproved); - - if (member.HasProperty(Constants.Conventions.Member.IsLockedOut) == false) - memberIsActive = member.Value(Constants.Conventions.Member.IsLockedOut) == false; - } - - if (memberIsActive == false) - { - _logger.Debug( - "Current member is either unapproved or locked out, redirect to error page"); - var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; - if (errorPageId != request.PublishedContent.Id) - request.PublishedContent = - request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId); - } - else - { + case PublicAccessStatus.NotLoggedIn: + _logger.Debug("EnsurePublishedContentAccess: Not logged in, redirect to login page"); + SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.LoginNodeId); + break; + case PublicAccessStatus.AccessDenied: + _logger.Debug("EnsurePublishedContentAccess: Current member has not access, redirect to error page"); + SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId); + break; + case PublicAccessStatus.LockedOut: + _logger.Debug("Current member is locked out, redirect to error page"); + SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId); + break; + case PublicAccessStatus.NotApproved: + _logger.Debug("Current member is unapproved, redirect to error page"); + SetPublishedContentAsOtherPage(request, publicAccessAttempt.Result.NoAccessNodeId); + break; + case PublicAccessStatus.AccessAccepted: _logger.Debug("Current member has access"); - } + break; } } else @@ -615,6 +602,12 @@ namespace Umbraco.Web.Routing } } + private static void SetPublishedContentAsOtherPage(IPublishedRequest request, int errorPageId) + { + if (errorPageId != request.PublishedContent.Id) + request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId); + } + /// /// Finds a template for the current node, if any. /// @@ -637,7 +630,7 @@ namespace Umbraco.Web.Routing var useAltTemplate = request.IsInitialPublishedContent || (_webRoutingSection.InternalRedirectPreservesTemplate && request.IsInternalRedirectPublishedContent); var altTemplate = useAltTemplate - ? _httpContextAccessor.GetRequiredHttpContext().Request[Constants.Conventions.Url.AltTemplate] + ? _requestAccessor.GetRequestValue(Constants.Conventions.Url.AltTemplate) : null; if (string.IsNullOrWhiteSpace(altTemplate)) @@ -674,10 +667,15 @@ namespace Umbraco.Web.Routing _logger.Debug("FindTemplate: Look for alternative template alias={AltTemplate}", altTemplate); // IsAllowedTemplate deals both with DisableAlternativeTemplates and ValidateAlternativeTemplates settings - if (request.PublishedContent.IsAllowedTemplate(altTemplate)) + if (request.PublishedContent.IsAllowedTemplate( + _fileService, + _contentTypeService, + _umbracoSettingsSection.WebRouting.DisableAlternativeTemplates, + _umbracoSettingsSection.WebRouting.ValidateAlternativeTemplates, + altTemplate)) { // allowed, use - var template = _services.FileService.GetTemplate(altTemplate); + var template = _fileService.GetTemplate(altTemplate); if (template != null) { @@ -731,7 +729,7 @@ namespace Umbraco.Web.Routing if (templateId == null) throw new InvalidOperationException("The template is not set, the page cannot render."); - var template = _services.FileService.GetTemplate(templateId.Value); + var template = _fileService.GetTemplate(templateId.Value); if (template == null) throw new InvalidOperationException("The template with Id " + templateId + " does not exist, the page cannot render."); _logger.Debug("GetTemplateModel: Got template id={TemplateId} alias={TemplateAlias}", template.Id, template.Alias); @@ -750,7 +748,7 @@ namespace Umbraco.Web.Routing if (request.PublishedContent.HasProperty(Constants.Conventions.Content.Redirect) == false) return; - var redirectId = request.PublishedContent.Value(Constants.Conventions.Content.Redirect, defaultValue: -1); + var redirectId = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.Redirect, defaultValue: -1); var redirectUrl = "#"; if (redirectId > 0) { @@ -759,7 +757,7 @@ namespace Umbraco.Web.Routing else { // might be a UDI instead of an int Id - var redirectUdi = request.PublishedContent.Value(Constants.Conventions.Content.Redirect); + var redirectUdi = request.PublishedContent.Value(_publishedValueFallback, Constants.Conventions.Content.Redirect); if (redirectUdi != null) redirectUrl = _publishedUrlProvider.GetUrl(redirectUdi.Guid); } diff --git a/src/Umbraco.Core/Security/IMemberUserKeyProvider.cs b/src/Umbraco.Core/Security/IMemberUserKeyProvider.cs new file mode 100644 index 0000000000..439e7a82b8 --- /dev/null +++ b/src/Umbraco.Core/Security/IMemberUserKeyProvider.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Security +{ + public interface IMemberUserKeyProvider + { + object GetMemberProviderUserKey(); + } +} diff --git a/src/Umbraco.Core/Security/IPublicAccessChecker.cs b/src/Umbraco.Core/Security/IPublicAccessChecker.cs new file mode 100644 index 0000000000..a47186394e --- /dev/null +++ b/src/Umbraco.Core/Security/IPublicAccessChecker.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Web.Security +{ + public interface IPublicAccessChecker + { + PublicAccessStatus HasMemberAccessToContent(int publishedContentId); + } +} diff --git a/src/Umbraco.Core/Security/PublicAccessStatus.cs b/src/Umbraco.Core/Security/PublicAccessStatus.cs new file mode 100644 index 0000000000..57df423749 --- /dev/null +++ b/src/Umbraco.Core/Security/PublicAccessStatus.cs @@ -0,0 +1,11 @@ +namespace Umbraco.Web.Security +{ + public enum PublicAccessStatus + { + NotLoggedIn, + AccessDenied, + NotApproved, + LockedOut, + AccessAccepted + } +} diff --git a/src/Umbraco.Core/Session/ISessionManager.cs b/src/Umbraco.Core/Session/ISessionManager.cs new file mode 100644 index 0000000000..f3a47202ee --- /dev/null +++ b/src/Umbraco.Core/Session/ISessionManager.cs @@ -0,0 +1,8 @@ +namespace Umbraco.Core.Session +{ + public interface ISessionManager + { + object GetSessionValue(string sessionName); + void SetSessionValue(string sessionName, object value); + } +} diff --git a/src/Umbraco.Core/Sync/IBatchedDatabaseServerMessenger.cs b/src/Umbraco.Core/Sync/IBatchedDatabaseServerMessenger.cs index d63478ef96..d8ec82818d 100644 --- a/src/Umbraco.Core/Sync/IBatchedDatabaseServerMessenger.cs +++ b/src/Umbraco.Core/Sync/IBatchedDatabaseServerMessenger.cs @@ -3,8 +3,10 @@ namespace Umbraco.Core.Sync /// /// An implementation that works by storing messages in the database. /// - public interface IBatchedDatabaseServerMessenger : IServerMessenger + public interface IBatchedDatabaseServerMessenger : IDatabaseServerMessenger { void FlushBatch(); + DatabaseServerMessengerOptions Options { get; } + void Startup(); } } diff --git a/src/Umbraco.Core/Sync/IDatabaseServerMessenger.cs b/src/Umbraco.Core/Sync/IDatabaseServerMessenger.cs new file mode 100644 index 0000000000..a49cfdd023 --- /dev/null +++ b/src/Umbraco.Core/Sync/IDatabaseServerMessenger.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Core.Sync +{ + public interface IDatabaseServerMessenger: IServerMessenger + { + void Sync(); + } +} diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs b/src/Umbraco.Core/UmbracoApiControllerTypeCollection.cs similarity index 100% rename from src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs rename to src/Umbraco.Core/UmbracoApiControllerTypeCollection.cs diff --git a/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs b/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs index ccc0248868..b1d529e6c6 100644 --- a/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs +++ b/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.IO; using Examine; using Examine.LuceneEngine.Directories; using Lucene.Net.Store; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.IO; @@ -19,11 +19,13 @@ namespace Umbraco.Examine { private readonly ITypeFinder _typeFinder; private readonly IIOHelper _ioHelper; + private readonly IIndexCreatorSettings _settings; - protected LuceneIndexCreator(ITypeFinder typeFinder, IIOHelper ioHelper) + protected LuceneIndexCreator(ITypeFinder typeFinder, IIOHelper ioHelper, IIndexCreatorSettings settings) { _typeFinder = typeFinder; _ioHelper = ioHelper; + _settings = settings; } public abstract IEnumerable Create(); @@ -43,7 +45,8 @@ namespace Umbraco.Examine System.IO.Directory.CreateDirectory(dirInfo.FullName); //check if there's a configured directory factory, if so create it and use that to create the lucene dir - var configuredDirectoryFactory = ConfigurationManager.AppSettings["Umbraco.Examine.LuceneDirectoryFactory"]; + var configuredDirectoryFactory = _settings.LuceneDirectoryFactory; + if (!configuredDirectoryFactory.IsNullOrWhiteSpace()) { //this should be a fully qualified type diff --git a/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs b/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs index 173300a472..0f60a7580c 100644 --- a/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs +++ b/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs @@ -4,6 +4,7 @@ using Umbraco.Core.Services; using Lucene.Net.Analysis.Standard; using Examine.LuceneEngine; using Examine; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.IO; @@ -25,7 +26,8 @@ namespace Umbraco.Examine IMemberService memberService, IUmbracoIndexConfig umbracoIndexConfig, IIOHelper ioHelper, - IRuntimeState runtimeState) : base(typeFinder, ioHelper) + IRuntimeState runtimeState, + IIndexCreatorSettings settings) : base(typeFinder, ioHelper, settings) { ProfilingLogger = profilingLogger ?? throw new System.ArgumentNullException(nameof(profilingLogger)); LanguageService = languageService ?? throw new System.ArgumentNullException(nameof(languageService)); diff --git a/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs b/src/Umbraco.Infrastructure/BatchedDatabaseServerMessenger.cs similarity index 87% rename from src/Umbraco.Web/BatchedDatabaseServerMessenger.cs rename to src/Umbraco.Infrastructure/BatchedDatabaseServerMessenger.cs index a62aad3e5d..78b9589a2e 100644 --- a/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs +++ b/src/Umbraco.Infrastructure/BatchedDatabaseServerMessenger.cs @@ -1,21 +1,17 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Web; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; using Umbraco.Core.Sync; using Umbraco.Web.Routing; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Scoping; -using Umbraco.Web.Composing; -using System.ComponentModel; using Umbraco.Core.Hosting; -using Umbraco.Core.IO; +using Umbraco.Core.Request; namespace Umbraco.Web { @@ -29,19 +25,30 @@ namespace Umbraco.Web { private readonly IUmbracoDatabaseFactory _databaseFactory; private readonly IRequestCache _requestCache; + private readonly IRequestAccessor _requestAccessor; public BatchedDatabaseServerMessenger( - IRuntimeState runtime, IUmbracoDatabaseFactory databaseFactory, IScopeProvider scopeProvider, ISqlContext sqlContext, IProfilingLogger proflog, DatabaseServerMessengerOptions options, IHostingEnvironment hostingEnvironment, CacheRefresherCollection cacheRefreshers, IRequestCache requestCache) + IRuntimeState runtime, + IUmbracoDatabaseFactory databaseFactory, + IScopeProvider scopeProvider, + ISqlContext sqlContext, + IProfilingLogger proflog, + DatabaseServerMessengerOptions options, + IHostingEnvironment hostingEnvironment, + CacheRefresherCollection cacheRefreshers, + IRequestCache requestCache, + IRequestAccessor requestAccessor) : base(runtime, scopeProvider, sqlContext, proflog, true, options, hostingEnvironment, cacheRefreshers) { _databaseFactory = databaseFactory; _requestCache = requestCache; + _requestAccessor = requestAccessor; } // invoked by DatabaseServerRegistrarAndMessengerComponent - internal void Startup() + public void Startup() { - UmbracoModule.EndRequest += UmbracoModule_EndRequest; + _requestAccessor.EndRequest += UmbracoModule_EndRequest; if (_databaseFactory.CanConnect == false) { @@ -104,7 +111,7 @@ namespace Umbraco.Web protected ICollection GetBatch(bool create) { - var key = typeof (BatchedDatabaseServerMessenger).Name; + var key = nameof(BatchedDatabaseServerMessenger); if (!_requestCache.IsAvailable) return null; diff --git a/src/Umbraco.Web/Compose/DatabaseServerRegistrarAndMessengerComponent.cs b/src/Umbraco.Infrastructure/Compose/DatabaseServerRegistrarAndMessengerComponent.cs similarity index 91% rename from src/Umbraco.Web/Compose/DatabaseServerRegistrarAndMessengerComponent.cs rename to src/Umbraco.Infrastructure/Compose/DatabaseServerRegistrarAndMessengerComponent.cs index 1fa455ed8a..2a24e6f318 100644 --- a/src/Umbraco.Web/Compose/DatabaseServerRegistrarAndMessengerComponent.cs +++ b/src/Umbraco.Infrastructure/Compose/DatabaseServerRegistrarAndMessengerComponent.cs @@ -4,6 +4,7 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; +using Umbraco.Core.Request; using Umbraco.Core.Services; using Umbraco.Core.Services.Changes; using Umbraco.Core.Sync; @@ -82,7 +83,7 @@ namespace Umbraco.Web.Compose { private object _locker = new object(); private readonly DatabaseServerRegistrar _registrar; - private readonly BatchedDatabaseServerMessenger _messenger; + private readonly IBatchedDatabaseServerMessenger _messenger; private readonly IRuntimeState _runtime; private readonly ILogger _logger; private readonly IServerRegistrationService _registrationService; @@ -91,13 +92,23 @@ namespace Umbraco.Web.Compose private bool _started; private IBackgroundTask[] _tasks; private IndexRebuilder _indexRebuilder; + private readonly IRequestAccessor _requestAccessor; - public DatabaseServerRegistrarAndMessengerComponent(IRuntimeState runtime, IServerRegistrar serverRegistrar, IServerMessenger serverMessenger, IServerRegistrationService registrationService, ILogger logger, IHostingEnvironment hostingEnvironment, IndexRebuilder indexRebuilder) + public DatabaseServerRegistrarAndMessengerComponent( + IRuntimeState runtime, + IServerRegistrar serverRegistrar, + IServerMessenger serverMessenger, + IServerRegistrationService registrationService, + ILogger logger, + IHostingEnvironment hostingEnvironment, + IndexRebuilder indexRebuilder, + IRequestAccessor requestAccessor) { _runtime = runtime; _logger = logger; _registrationService = registrationService; _indexRebuilder = indexRebuilder; + _requestAccessor = requestAccessor; // create task runner for DatabaseServerRegistrar _registrar = serverRegistrar as DatabaseServerRegistrar; @@ -108,7 +119,7 @@ namespace Umbraco.Web.Compose } // create task runner for BatchedDatabaseServerMessenger - _messenger = serverMessenger as BatchedDatabaseServerMessenger; + _messenger = serverMessenger as IBatchedDatabaseServerMessenger; if (_messenger != null) { _processTaskRunner = new BackgroundTaskRunner("ServerInstProcess", @@ -120,7 +131,7 @@ namespace Umbraco.Web.Compose { //We will start the whole process when a successful request is made if (_registrar != null || _messenger != null) - UmbracoModule.RouteAttempt += RegisterBackgroundTasksOnce; + _requestAccessor.RouteAttempt += RegisterBackgroundTasksOnce; // must come last, as it references some _variables _messenger?.Startup(); @@ -137,7 +148,7 @@ namespace Umbraco.Web.Compose /// /// We require this because: /// - ApplicationContext.UmbracoApplicationUrl is initialized by UmbracoModule in BeginRequest - /// - RegisterServer is called on UmbracoModule.RouteAttempt which is triggered in ProcessRequest + /// - RegisterServer is called on _requestAccessor.RouteAttempt which is triggered in ProcessRequest /// we are safe, UmbracoApplicationUrl has been initialized /// private void RegisterBackgroundTasksOnce(object sender, RoutableAttemptEventArgs e) @@ -146,7 +157,7 @@ namespace Umbraco.Web.Compose { case EnsureRoutableOutcome.IsRoutable: case EnsureRoutableOutcome.NotDocumentRequest: - UmbracoModule.RouteAttempt -= RegisterBackgroundTasksOnce; + _requestAccessor.RouteAttempt -= RegisterBackgroundTasksOnce; RegisterBackgroundTasks(); break; } @@ -196,11 +207,11 @@ namespace Umbraco.Web.Compose private class InstructionProcessTask : RecurringTaskBase { - private readonly DatabaseServerMessenger _messenger; + private readonly IDatabaseServerMessenger _messenger; private readonly ILogger _logger; public InstructionProcessTask(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, - DatabaseServerMessenger messenger, ILogger logger) + IDatabaseServerMessenger messenger, ILogger logger) : base(runner, delayMilliseconds, periodMilliseconds) { _messenger = messenger; diff --git a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Configuration.cs b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Configuration.cs index 7169b93cb4..5c931a225b 100644 --- a/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Configuration.cs +++ b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Configuration.cs @@ -1,4 +1,6 @@ -using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Configuration; +using Umbraco.Configuration; +using Umbraco.Core.Configuration.UmbracoSettings; namespace Umbraco.Core.Composing.CompositionExtensions { diff --git a/src/Umbraco.Infrastructure/IPublishedContentQuery.cs b/src/Umbraco.Infrastructure/IPublishedContentQuery.cs index 6a1621b229..c5f49c3e0b 100644 --- a/src/Umbraco.Infrastructure/IPublishedContentQuery.cs +++ b/src/Umbraco.Infrastructure/IPublishedContentQuery.cs @@ -13,12 +13,18 @@ namespace Umbraco.Web /// public interface IPublishedContentQuery { + + + IPublishedContent Content(int id); IPublishedContent Content(Guid id); IPublishedContent Content(Udi id); + IPublishedContent Content(object id); IPublishedContent ContentSingleAtXPath(string xpath, params XPathVariable[] vars); IEnumerable Content(IEnumerable ids); IEnumerable Content(IEnumerable ids); + + IEnumerable Content(IEnumerable ids); IEnumerable ContentAtXPath(string xpath, params XPathVariable[] vars); IEnumerable ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars); IEnumerable ContentAtRoot(); @@ -26,7 +32,10 @@ namespace Umbraco.Web IPublishedContent Media(int id); IPublishedContent Media(Guid id); IPublishedContent Media(Udi id); + + IPublishedContent Media(object id); IEnumerable Media(IEnumerable ids); + IEnumerable Media(IEnumerable ids); IEnumerable Media(IEnumerable ids); IEnumerable MediaAtRoot(); diff --git a/src/Umbraco.Infrastructure/Migrations/PostMigrations/ClearCsrfCookies.cs b/src/Umbraco.Infrastructure/Migrations/PostMigrations/ClearCsrfCookies.cs index ab9c946e05..4f176c797f 100644 --- a/src/Umbraco.Infrastructure/Migrations/PostMigrations/ClearCsrfCookies.cs +++ b/src/Umbraco.Infrastructure/Migrations/PostMigrations/ClearCsrfCookies.cs @@ -2,7 +2,6 @@ using Umbraco.Core.Cookie; using Umbraco.Core.Migrations; - namespace Umbraco.Web.Migrations.PostMigrations { /// diff --git a/src/Umbraco.Infrastructure/PublishedContentQuery.cs b/src/Umbraco.Infrastructure/PublishedContentQuery.cs index f35cea085d..e995850a1f 100644 --- a/src/Umbraco.Infrastructure/PublishedContentQuery.cs +++ b/src/Umbraco.Infrastructure/PublishedContentQuery.cs @@ -14,35 +14,85 @@ using Umbraco.Web.PublishedCache; namespace Umbraco.Web { /// - /// A class used to query for published content, media items + /// A class used to query for published content, media items /// public class PublishedContentQuery : IPublishedContentQuery { + private readonly IExamineManager _examineManager; private readonly IPublishedSnapshot _publishedSnapshot; private readonly IVariationContextAccessor _variationContextAccessor; - private readonly IExamineManager _examineManager; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public PublishedContentQuery(IPublishedSnapshot publishedSnapshot, IVariationContextAccessor variationContextAccessor, IExamineManager examineManager) + public PublishedContentQuery(IPublishedSnapshot publishedSnapshot, + IVariationContextAccessor variationContextAccessor, IExamineManager examineManager) { _publishedSnapshot = publishedSnapshot ?? throw new ArgumentNullException(nameof(publishedSnapshot)); - _variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor)); + _variationContextAccessor = variationContextAccessor ?? + throw new ArgumentNullException(nameof(variationContextAccessor)); _examineManager = examineManager ?? throw new ArgumentNullException(nameof(examineManager)); } + #region Convert Helpers + + private static bool ConvertIdObjectToInt(object id, out int intId) + { + switch (id) + { + case string s: + return int.TryParse(s, out intId); + + case int i: + intId = i; + return true; + + default: + intId = default; + return false; + } + } + + private static bool ConvertIdObjectToGuid(object id, out Guid guidId) + { + switch (id) + { + case string s: + return Guid.TryParse(s, out guidId); + + case Guid g: + guidId = g; + return true; + + default: + guidId = default; + return false; + } + } + private static bool ConvertIdObjectToUdi(object id, out Udi guidId) + { + switch (id) + { + case string s: + return UdiParser.TryParse(s, out guidId); + + case Udi u: + guidId = u; + return true; + + default: + guidId = default; + return false; + } + } + + #endregion + #region Content - public IPublishedContent Content(int id) - { - return ItemById(id, _publishedSnapshot.Content); - } + public IPublishedContent Content(int id) => ItemById(id, _publishedSnapshot.Content); - public IPublishedContent Content(Guid id) - { - return ItemById(id, _publishedSnapshot.Content); - } + public IPublishedContent Content(Guid id) => ItemById(id, _publishedSnapshot.Content); public IPublishedContent Content(Udi id) { @@ -50,49 +100,45 @@ namespace Umbraco.Web return ItemById(udi.Guid, _publishedSnapshot.Content); } - public IPublishedContent ContentSingleAtXPath(string xpath, params XPathVariable[] vars) + public IPublishedContent Content(object id) { - return ItemByXPath(xpath, vars, _publishedSnapshot.Content); + if (ConvertIdObjectToInt(id, out var intId)) + return Content(intId); + if (ConvertIdObjectToGuid(id, out var guidId)) + return Content(guidId); + if (ConvertIdObjectToUdi(id, out var udiId)) + return Content(udiId); + return null; } - public IEnumerable Content(IEnumerable ids) - { - return ItemsByIds(_publishedSnapshot.Content, ids); - } + public IPublishedContent ContentSingleAtXPath(string xpath, params XPathVariable[] vars) => + ItemByXPath(xpath, vars, _publishedSnapshot.Content); - public IEnumerable Content(IEnumerable ids) - { - return ItemsByIds(_publishedSnapshot.Content, ids); - } + public IEnumerable Content(IEnumerable ids) => + ItemsByIds(_publishedSnapshot.Content, ids); - public IEnumerable ContentAtXPath(string xpath, params XPathVariable[] vars) - { - return ItemsByXPath(xpath, vars, _publishedSnapshot.Content); - } + public IEnumerable Content(IEnumerable ids) => + ItemsByIds(_publishedSnapshot.Content, ids); - public IEnumerable ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars) + public IEnumerable Content(IEnumerable ids) { - return ItemsByXPath(xpath, vars, _publishedSnapshot.Content); + return ids.Select(Content).WhereNotNull(); } + public IEnumerable ContentAtXPath(string xpath, params XPathVariable[] vars) => + ItemsByXPath(xpath, vars, _publishedSnapshot.Content); - public IEnumerable ContentAtRoot() - { - return ItemsAtRoot(_publishedSnapshot.Content); - } + public IEnumerable ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars) => + ItemsByXPath(xpath, vars, _publishedSnapshot.Content); + + public IEnumerable ContentAtRoot() => ItemsAtRoot(_publishedSnapshot.Content); #endregion #region Media - public IPublishedContent Media(int id) - { - return ItemById(id, _publishedSnapshot.Media); - } + public IPublishedContent Media(int id) => ItemById(id, _publishedSnapshot.Media); - public IPublishedContent Media(Guid id) - { - return ItemById(id, _publishedSnapshot.Media); - } + public IPublishedContent Media(Guid id) => ItemById(id, _publishedSnapshot.Media); public IPublishedContent Media(Udi id) { @@ -100,21 +146,26 @@ namespace Umbraco.Web return ItemById(udi.Guid, _publishedSnapshot.Media); } - public IEnumerable Media(IEnumerable ids) + public IPublishedContent Media(object id) { - return ItemsByIds(_publishedSnapshot.Media, ids); + if (ConvertIdObjectToInt(id, out var intId)) + return Media(intId); + if (ConvertIdObjectToGuid(id, out var guidId)) + return Media(guidId); + if (ConvertIdObjectToUdi(id, out var udiId)) + return Media(udiId); + return null; } - public IEnumerable Media(IEnumerable ids) + public IEnumerable Media(IEnumerable ids) => ItemsByIds(_publishedSnapshot.Media, ids); + public IEnumerable Media(IEnumerable ids) { - return ItemsByIds(_publishedSnapshot.Media, ids); + return ids.Select(Media).WhereNotNull(); } - public IEnumerable MediaAtRoot() - { - return ItemsAtRoot(_publishedSnapshot.Media); - } + public IEnumerable Media(IEnumerable ids) => ItemsByIds(_publishedSnapshot.Media, ids); + public IEnumerable MediaAtRoot() => ItemsAtRoot(_publishedSnapshot.Media); #endregion @@ -155,44 +206,45 @@ namespace Umbraco.Web return ids.Select(eachId => ItemById(eachId, cache)).WhereNotNull(); } - private static IEnumerable ItemsByXPath(string xpath, XPathVariable[] vars, IPublishedCache cache) + private static IEnumerable ItemsByXPath(string xpath, XPathVariable[] vars, + IPublishedCache cache) { var doc = cache.GetByXPath(xpath, vars); return doc; } - private static IEnumerable ItemsByXPath(XPathExpression xpath, XPathVariable[] vars, IPublishedCache cache) + private static IEnumerable ItemsByXPath(XPathExpression xpath, XPathVariable[] vars, + IPublishedCache cache) { var doc = cache.GetByXPath(xpath, vars); return doc; } - private static IEnumerable ItemsAtRoot(IPublishedCache cache) - { - return cache.GetAtRoot(); - } + private static IEnumerable ItemsAtRoot(IPublishedCache cache) => cache.GetAtRoot(); #endregion #region Search /// - public IEnumerable Search(string term, string culture = "*", string indexName = Constants.UmbracoIndexes.ExternalIndexName) - { - return Search(term, 0, 0, out _, culture, indexName); - } + public IEnumerable Search(string term, string culture = "*", + string indexName = Constants.UmbracoIndexes.ExternalIndexName) => + Search(term, 0, 0, out _, culture, indexName); /// - public IEnumerable Search(string term, int skip, int take, out long totalRecords, string culture = "*", string indexName = Constants.UmbracoIndexes.ExternalIndexName) + public IEnumerable Search(string term, int skip, int take, out long totalRecords, + string culture = "*", string indexName = Constants.UmbracoIndexes.ExternalIndexName) { if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), skip, "The value must be greater than or equal to zero."); + throw new ArgumentOutOfRangeException(nameof(skip), skip, + "The value must be greater than or equal to zero."); } if (take < 0) { - throw new ArgumentOutOfRangeException(nameof(take), take, "The value must be greater than or equal to zero."); + throw new ArgumentOutOfRangeException(nameof(take), take, + "The value must be greater than or equal to zero."); } if (string.IsNullOrEmpty(indexName)) @@ -202,7 +254,8 @@ namespace Umbraco.Web if (!_examineManager.TryGetIndex(indexName, out var index) || !(index is IUmbracoIndex umbIndex)) { - throw new InvalidOperationException($"No index found by name {indexName} or is not of type {typeof(IUmbracoIndex)}"); + throw new InvalidOperationException( + $"No index found by name {indexName} or is not of type {typeof(IUmbracoIndex)}"); } var query = umbIndex.GetSearcher().CreateQuery(IndexTypes.Content); @@ -216,13 +269,16 @@ namespace Umbraco.Web else if (string.IsNullOrWhiteSpace(culture)) { // Only search invariant - queryExecutor = query.Field(UmbracoExamineFieldNames.VariesByCultureFieldName, "n") // Must not vary by culture + queryExecutor = query + .Field(UmbracoExamineFieldNames.VariesByCultureFieldName, "n") // Must not vary by culture .And().ManagedQuery(term); } else { // Only search the specified culture - var fields = umbIndex.GetCultureAndInvariantFields(culture).ToArray(); // Get all index fields suffixed with the culture name supplied + var fields = + umbIndex.GetCultureAndInvariantFields(culture) + .ToArray(); // Get all index fields suffixed with the culture name supplied queryExecutor = query.ManagedQuery(term, fields); } @@ -232,26 +288,28 @@ namespace Umbraco.Web totalRecords = results.TotalItemCount; - return new CultureContextualSearchResults(results.Skip(skip).ToPublishedSearchResults(_publishedSnapshot.Content), _variationContextAccessor, culture); + return new CultureContextualSearchResults( + results.Skip(skip).ToPublishedSearchResults(_publishedSnapshot.Content), _variationContextAccessor, + culture); } /// - public IEnumerable Search(IQueryExecutor query) - { - return Search(query, 0, 0, out _); - } + public IEnumerable Search(IQueryExecutor query) => Search(query, 0, 0, out _); /// - public IEnumerable Search(IQueryExecutor query, int skip, int take, out long totalRecords) + public IEnumerable Search(IQueryExecutor query, int skip, int take, + out long totalRecords) { if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), skip, "The value must be greater than or equal to zero."); + throw new ArgumentOutOfRangeException(nameof(skip), skip, + "The value must be greater than or equal to zero."); } if (take < 0) { - throw new ArgumentOutOfRangeException(nameof(take), take, "The value must be greater than or equal to zero."); + throw new ArgumentOutOfRangeException(nameof(take), take, + "The value must be greater than or equal to zero."); } var results = skip == 0 && take == 0 @@ -264,15 +322,17 @@ namespace Umbraco.Web } /// - /// This is used to contextualize the values in the search results when enumerating over them so that the correct culture values are used + /// This is used to contextualize the values in the search results when enumerating over them so that the correct + /// culture values are used /// private class CultureContextualSearchResults : IEnumerable { - private readonly IEnumerable _wrapped; - private readonly IVariationContextAccessor _variationContextAccessor; private readonly string _culture; + private readonly IVariationContextAccessor _variationContextAccessor; + private readonly IEnumerable _wrapped; - public CultureContextualSearchResults(IEnumerable wrapped, IVariationContextAccessor variationContextAccessor, string culture) + public CultureContextualSearchResults(IEnumerable wrapped, + IVariationContextAccessor variationContextAccessor, string culture) { _wrapped = wrapped; _variationContextAccessor = variationContextAccessor; @@ -287,24 +347,23 @@ namespace Umbraco.Web _variationContextAccessor.VariationContext = new VariationContext(_culture); //now the IPublishedContent returned will be contextualized to the culture specified and will be reset when the enumerator is disposed - return new CultureContextualSearchResultsEnumerator(_wrapped.GetEnumerator(), _variationContextAccessor, originalContext); + return new CultureContextualSearchResultsEnumerator(_wrapped.GetEnumerator(), _variationContextAccessor, + originalContext); } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// - /// Resets the variation context when this is disposed + /// Resets the variation context when this is disposed /// private class CultureContextualSearchResultsEnumerator : IEnumerator { - private readonly IEnumerator _wrapped; - private readonly IVariationContextAccessor _variationContextAccessor; private readonly VariationContext _originalContext; + private readonly IVariationContextAccessor _variationContextAccessor; + private readonly IEnumerator _wrapped; - public CultureContextualSearchResultsEnumerator(IEnumerator wrapped, IVariationContextAccessor variationContextAccessor, VariationContext originalContext) + public CultureContextualSearchResultsEnumerator(IEnumerator wrapped, + IVariationContextAccessor variationContextAccessor, VariationContext originalContext) { _wrapped = wrapped; _variationContextAccessor = variationContextAccessor; @@ -318,10 +377,7 @@ namespace Umbraco.Web _variationContextAccessor.VariationContext = _originalContext; } - public bool MoveNext() - { - return _wrapped.MoveNext(); - } + public bool MoveNext() => _wrapped.MoveNext(); public void Reset() { diff --git a/src/Umbraco.Web/Routing/RedirectTrackingComponent.cs b/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs similarity index 93% rename from src/Umbraco.Web/Routing/RedirectTrackingComponent.cs rename to src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs index dffb956b1a..0eae54bf7d 100644 --- a/src/Umbraco.Web/Routing/RedirectTrackingComponent.cs +++ b/src/Umbraco.Infrastructure/Routing/RedirectTrackingComponent.cs @@ -6,6 +6,7 @@ using Umbraco.Core.Composing; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Events; using Umbraco.Core.Models; +using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Web.PublishedCache; @@ -26,12 +27,14 @@ namespace Umbraco.Web.Routing private readonly IUmbracoSettingsSection _umbracoSettings; private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; private readonly IRedirectUrlService _redirectUrlService; + private readonly IVariationContextAccessor _variationContextAccessor; - public RedirectTrackingComponent(IUmbracoSettingsSection umbracoSettings, IPublishedSnapshotAccessor publishedSnapshotAccessor, IRedirectUrlService redirectUrlService) + public RedirectTrackingComponent(IUmbracoSettingsSection umbracoSettings, IPublishedSnapshotAccessor publishedSnapshotAccessor, IRedirectUrlService redirectUrlService, IVariationContextAccessor variationContextAccessor) { _umbracoSettings = umbracoSettings; _publishedSnapshotAccessor = publishedSnapshotAccessor; _redirectUrlService = redirectUrlService; + _variationContextAccessor = variationContextAccessor; } public void Initialize() @@ -99,12 +102,12 @@ namespace Umbraco.Web.Routing { var contentCache = _publishedSnapshotAccessor.PublishedSnapshot.Content; var entityContent = contentCache.GetById(entity.Id); - if (entityContent == null) return; + if (entityContent == null) return; - // get the default affected cultures by going up the tree until we find the first culture variant entity (default to no cultures) + // get the default affected cultures by going up the tree until we find the first culture variant entity (default to no cultures) var defaultCultures = entityContent.AncestorsOrSelf()?.FirstOrDefault(a => a.Cultures.Any())?.Cultures.Keys.ToArray() ?? new[] { (string)null }; - foreach (var x in entityContent.DescendantsOrSelf()) + foreach (var x in entityContent.DescendantsOrSelf(_variationContextAccessor)) { // if this entity defines specific cultures, use those instead of the default ones var cultures = x.Cultures.Any() ? x.Cultures.Keys : defaultCultures; diff --git a/src/Umbraco.Web/Routing/RedirectTrackingComposer.cs b/src/Umbraco.Infrastructure/Routing/RedirectTrackingComposer.cs similarity index 100% rename from src/Umbraco.Web/Routing/RedirectTrackingComposer.cs rename to src/Umbraco.Infrastructure/Routing/RedirectTrackingComposer.cs diff --git a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs similarity index 96% rename from src/Umbraco.Web/Scheduling/SchedulerComponent.cs rename to src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs index 061f42b9ba..6e5d0ee81e 100644 --- a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs +++ b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs @@ -9,6 +9,7 @@ using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; +using Umbraco.Core.Request; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Sync; @@ -37,6 +38,7 @@ namespace Umbraco.Web.Scheduling private readonly IUmbracoSettingsSection _umbracoSettingsSection; private readonly IIOHelper _ioHelper; private readonly IServerMessenger _serverMessenger; + private readonly IRequestAccessor _requestAccessor; private BackgroundTaskRunner _keepAliveRunner; private BackgroundTaskRunner _publishingRunner; @@ -54,7 +56,7 @@ namespace Umbraco.Web.Scheduling HealthCheckCollection healthChecks, HealthCheckNotificationMethodCollection notifications, IScopeProvider scopeProvider, IUmbracoContextFactory umbracoContextFactory, IProfilingLogger logger, IHostingEnvironment hostingEnvironment, IHealthChecks healthChecksConfig, - IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IServerMessenger serverMessenger) + IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IServerMessenger serverMessenger, IRequestAccessor requestAccessor) { _runtime = runtime; _contentService = contentService; @@ -70,6 +72,7 @@ namespace Umbraco.Web.Scheduling _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); _ioHelper = ioHelper; _serverMessenger = serverMessenger; + _requestAccessor = requestAccessor; } public void Initialize() @@ -83,7 +86,7 @@ namespace Umbraco.Web.Scheduling _healthCheckRunner = new BackgroundTaskRunner("HealthCheckNotifier", _logger, _hostingEnvironment); // we will start the whole process when a successful request is made - UmbracoModule.RouteAttempt += RegisterBackgroundTasksOnce; + _requestAccessor.RouteAttempt += RegisterBackgroundTasksOnce; } public void Terminate() @@ -97,7 +100,7 @@ namespace Umbraco.Web.Scheduling { case EnsureRoutableOutcome.IsRoutable: case EnsureRoutableOutcome.NotDocumentRequest: - UmbracoModule.RouteAttempt -= RegisterBackgroundTasksOnce; + _requestAccessor.RouteAttempt -= RegisterBackgroundTasksOnce; RegisterBackgroundTasks(); break; } diff --git a/src/Umbraco.Web/Scheduling/SchedulerComposer.cs b/src/Umbraco.Infrastructure/Scheduling/SchedulerComposer.cs similarity index 100% rename from src/Umbraco.Web/Scheduling/SchedulerComposer.cs rename to src/Umbraco.Infrastructure/Scheduling/SchedulerComposer.cs diff --git a/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs b/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs index 948304e4e4..5a46a37d43 100644 --- a/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs +++ b/src/Umbraco.Infrastructure/Sync/DatabaseServerMessenger.cs @@ -26,7 +26,7 @@ namespace Umbraco.Core.Sync // but only processes instructions coming from remote servers, // thus ensuring that instructions run only once // - public class DatabaseServerMessenger : ServerMessengerBase + public class DatabaseServerMessenger : ServerMessengerBase, IDatabaseServerMessenger { private readonly IRuntimeState _runtime; private readonly ManualResetEvent _syncIdle; @@ -126,10 +126,6 @@ namespace Umbraco.Core.Sync const int weight = 10; - //TODO Why do we have interface if we expect to be exact type!!!? - // if (!(_runtime is RuntimeState runtime)) - // throw new NotSupportedException($"Unsupported IRuntimeState implementation {_runtime.GetType().FullName}, expecting {typeof(RuntimeState).FullName}."); - var registered = _runtime.MainDom.Register( () => { diff --git a/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs b/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs index 3b47cabbaf..b65254b181 100644 --- a/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs +++ b/src/Umbraco.Infrastructure/Sync/ServerMessengerBase.cs @@ -4,7 +4,6 @@ using System.Linq; using Newtonsoft.Json; using Umbraco.Composing; using Umbraco.Core.Cache; -using Umbraco.Core.Composing; using Umbraco.Core.Logging; namespace Umbraco.Core.Sync diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs index 1fdb64c62a..75affe09e7 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs @@ -1,4 +1,4 @@ -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs index 15ca2cca24..1e96e64df8 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidatorBase.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Models.PublishedContent; -using Umbraco.ModelsBuilder.Embedded.Configuration; using Umbraco.Web.Editors; using Umbraco.Web.Models.ContentEditing; diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs index 25ddc838e8..6e22313474 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/DashboardReport.cs @@ -1,5 +1,6 @@ using System.Text; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Configuration; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded.BackOffice { diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs index 9dc1ea6c20..fcd42908e7 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MediaTypeModelValidator.cs @@ -1,4 +1,4 @@ -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs index 8d0a98eeab..2e249eed4d 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/MemberTypeModelValidator.cs @@ -1,4 +1,4 @@ -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.ModelsBuilder.Embedded.BackOffice diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs index 1d9de265e9..17b694de56 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ModelsBuilderDashboardController.cs @@ -3,9 +3,10 @@ using System.Net; using System.Net.Http; using System.Runtime.Serialization; using System.Web.Hosting; +using Umbraco.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Core.Exceptions; using Umbraco.ModelsBuilder.Embedded.Building; -using Umbraco.ModelsBuilder.Embedded.Configuration; using Umbraco.Web.Editors; using Umbraco.Web.WebApi.Filters; diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs index ffd56d4312..f64e5ed1ce 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/Builder.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded.Building { @@ -18,6 +19,8 @@ namespace Umbraco.ModelsBuilder.Embedded.Building internal abstract class Builder { + + private readonly IList _typeModels; protected Dictionary ModelsMap { get; } = new Dictionary(); @@ -209,7 +212,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Building // use configured else fallback to default return string.IsNullOrWhiteSpace(Config.ModelsNamespace) - ? ModelsBuilderConfig.DefaultModelsNamespace + ? Constants.ModelsBuilder.DefaultModelsNamespace : Config.ModelsNamespace; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs index 8a3bc5a5b5..192f049930 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs @@ -1,6 +1,6 @@ using System.IO; using System.Text; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded.Building { diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs index d1190a0374..4c796f3c7b 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded.Building { diff --git a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs index d856cae1e7..769cca7317 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComponent.cs @@ -4,13 +4,14 @@ using System.Reflection; using System.Web; using System.Web.Mvc; using System.Web.Routing; +using Umbraco.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Core.Composing; using Umbraco.Core.IO; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; using Umbraco.Core.Strings; using Umbraco.ModelsBuilder.Embedded.BackOffice; -using Umbraco.ModelsBuilder.Embedded.Configuration; using Umbraco.Web; using Umbraco.Web.JavaScript; using Umbraco.Web.Mvc; diff --git a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs index bb8a3f7e18..2914fe1b12 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs @@ -1,12 +1,11 @@ using System.Linq; using System.Reflection; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Composing; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded.Building; -using Umbraco.ModelsBuilder.Embedded.Configuration; -using Umbraco.Web; namespace Umbraco.ModelsBuilder.Embedded.Compose { @@ -20,16 +19,12 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose { var isLegacyModelsBuilderInstalled = IsLegacyModelsBuilderInstalled(); - - composition.Configs.Add(() => new ModelsBuilderConfig(composition.IOHelper)); - if (isLegacyModelsBuilderInstalled) { ComposeForLegacyModelsBuilder(composition); return; } - composition.Components().Append(); composition.Register(Lifetime.Singleton); composition.RegisterUnique(); diff --git a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs b/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs index d634547a49..d625c754c5 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs @@ -1,5 +1,4 @@ using Umbraco.Core.Configuration; -using Umbraco.ModelsBuilder.Embedded.Configuration; namespace Umbraco.ModelsBuilder.Embedded { diff --git a/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs b/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs index d4b4636563..61d39cd373 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs @@ -1,10 +1,10 @@ using System; using System.Threading; -using System.Web.Hosting; +using Umbraco.Core.Configuration; +using Umbraco.Configuration; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; using Umbraco.ModelsBuilder.Embedded.Building; -using Umbraco.ModelsBuilder.Embedded.Configuration; using Umbraco.Web.Cache; namespace Umbraco.ModelsBuilder.Embedded diff --git a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs index a692f633a5..5b498fd5f3 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Text; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded { diff --git a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs index 5425c31c77..0e93030438 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs @@ -1,5 +1,5 @@ using System.IO; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Web.Cache; namespace Umbraco.ModelsBuilder.Embedded diff --git a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs index fe28817cba..bef2fa8414 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs @@ -11,12 +11,12 @@ using System.Threading; using System.Web; using System.Web.Compilation; using System.Web.WebPages.Razor; +using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Hosting; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded.Building; -using Umbraco.ModelsBuilder.Embedded.Configuration; using File = System.IO.File; namespace Umbraco.ModelsBuilder.Embedded diff --git a/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj b/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj index 2637da8560..a03862326d 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj +++ b/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj @@ -59,10 +59,6 @@ - - - - @@ -119,6 +115,5 @@ 5.2.7 - \ No newline at end of file diff --git a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs index 910c0ca737..ad7cc72eec 100644 --- a/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs +++ b/src/Umbraco.PublishedCache.NuCache/DataSource/BTree.cs @@ -1,12 +1,13 @@ using System.Configuration; using CSharpTest.Net.Collections; using CSharpTest.Net.Serialization; +using Umbraco.Core.Configuration; namespace Umbraco.Web.PublishedCache.NuCache.DataSource { internal class BTree { - public static BPlusTree GetTree(string filepath, bool exists) + public static BPlusTree GetTree(string filepath, bool exists, INuCacheSettings settings) { var keySerializer = new PrimitiveSerializer(); var valueSerializer = new ContentNodeKitSerializer(); @@ -19,7 +20,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource CachePolicy = CachePolicy.None, // default is 4096, min 2^9 = 512, max 2^16 = 64K - FileBlockSize = GetBlockSize(), + FileBlockSize = GetBlockSize(settings), // other options? }; @@ -32,11 +33,11 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource return tree; } - private static int GetBlockSize() + private static int GetBlockSize(INuCacheSettings settings) { var blockSize = 4096; - var appSetting = ConfigurationManager.AppSettings["Umbraco.Web.PublishedCache.NuCache.BTree.BlockSize"]; + var appSetting = settings.BTreeBlockSize; if (appSetting == null) return blockSize; diff --git a/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs b/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs index 3ce60aa2b5..74295b7182 100644 --- a/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs @@ -53,6 +53,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IHostingEnvironment _hostingEnvironment; private readonly IShortStringHelper _shortStringHelper; private readonly IIOHelper _ioHelper; + private readonly INuCacheSettings _config; // volatile because we read it with no lock private volatile bool _isReady; @@ -90,7 +91,8 @@ namespace Umbraco.Web.PublishedCache.NuCache ITypeFinder typeFinder, IHostingEnvironment hostingEnvironment, IShortStringHelper shortStringHelper, - IIOHelper ioHelper) + IIOHelper ioHelper, + INuCacheSettings config) : base(publishedSnapshotAccessor, variationContextAccessor) { //if (Interlocked.Increment(ref _singletonCheck) > 1) @@ -111,6 +113,7 @@ namespace Umbraco.Web.PublishedCache.NuCache _hostingEnvironment = hostingEnvironment; _shortStringHelper = shortStringHelper; _ioHelper = ioHelper; + _config = config; // we need an Xml serializer here so that the member cache can support XPath, // for members this is done by navigating the serialized-to-xml member @@ -197,8 +200,8 @@ namespace Umbraco.Web.PublishedCache.NuCache _localMediaDbExists = File.Exists(localMediaDbPath); // if both local databases exist then GetTree will open them, else new databases will be created - _localContentDb = BTree.GetTree(localContentDbPath, _localContentDbExists); - _localMediaDb = BTree.GetTree(localMediaDbPath, _localMediaDbExists); + _localContentDb = BTree.GetTree(localContentDbPath, _localContentDbExists, _config); + _localMediaDb = BTree.GetTree(localMediaDbPath, _localMediaDbExists, _config); _logger.Info("Registered with MainDom, localContentDbExists? {LocalContentDbExists}, localMediaDbExists? {LocalMediaDbExists}", _localContentDbExists, _localMediaDbExists); } diff --git a/src/Umbraco.TestData/UmbracoTestDataController.cs b/src/Umbraco.TestData/UmbracoTestDataController.cs index dad9e72c73..09f9177982 100644 --- a/src/Umbraco.TestData/UmbracoTestDataController.cs +++ b/src/Umbraco.TestData/UmbracoTestDataController.cs @@ -33,8 +33,8 @@ namespace Umbraco.TestData private readonly PropertyEditorCollection _propertyEditors; private readonly IShortStringHelper _shortStringHelper; - public UmbracoTestDataController(IScopeProvider scopeProvider, PropertyEditorCollection propertyEditors, IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + public UmbracoTestDataController(IScopeProvider scopeProvider, PropertyEditorCollection propertyEditors, IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, IShortStringHelper shortStringHelper) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { _scopeProvider = scopeProvider; _propertyEditors = propertyEditors; diff --git a/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs b/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs index 77200be86e..3a504ad4e2 100644 --- a/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs +++ b/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Linq; using System.Reflection; using System.Web; using Moq; @@ -20,14 +21,17 @@ namespace Umbraco.Tests.Cache public class DeepCloneAppCacheTests : RuntimeAppCacheTests { private DeepCloneAppCache _provider; + private ObjectCacheAppCache _memberCache; - protected override int GetTotalItemCount => HttpRuntime.Cache.Count; + protected override int GetTotalItemCount => _memberCache.MemoryCache.Count(); public override void Setup() { base.Setup(); var typeFinder = new TypeFinder(Mock.Of()); - _provider = new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache, typeFinder)); + _memberCache = new ObjectCacheAppCache(typeFinder); + + _provider = new DeepCloneAppCache(_memberCache); } internal override IAppCache AppCache => _provider; diff --git a/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs b/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs deleted file mode 100644 index 02986e2f78..0000000000 --- a/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Diagnostics; -using System.Web; -using Moq; -using NUnit.Framework; -using Umbraco.Core.Cache; -using Umbraco.Core.Composing; -using Umbraco.Core.Logging; -using Umbraco.Web.Cache; - -namespace Umbraco.Tests.Cache -{ - [TestFixture] - public class WebCachingAppCacheTests : RuntimeAppCacheTests - { - private WebCachingAppCache _appCache; - - protected override int GetTotalItemCount => HttpRuntime.Cache.Count; - - public override void Setup() - { - base.Setup(); - var typeFinder = new TypeFinder(Mock.Of()); - _appCache = new WebCachingAppCache(HttpRuntime.Cache, typeFinder); - } - - internal override IAppCache AppCache => _appCache; - - internal override IAppPolicyCache AppPolicyCache => _appCache; - - [Test] - public void DoesNotCacheExceptions() - { - string value; - Assert.Throws(() => { value = (string)_appCache.Get("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_appCache.Get("key", () => GetValue(2)); }); - - // does not throw - value = (string)_appCache.Get("key", () => GetValue(3)); - Assert.AreEqual("succ3", value); - - // cache - value = (string)_appCache.Get("key", () => GetValue(4)); - Assert.AreEqual("succ3", value); - } - - private static string GetValue(int i) - { - Debug.Print("get" + i); - if (i < 3) - throw new Exception("fail"); - return "succ" + i; - } - } -} diff --git a/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs b/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs index 56d9d46e7d..b3f644ae43 100644 --- a/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs +++ b/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs @@ -4,10 +4,10 @@ using System.Linq; using System.Text; using Moq; using NUnit.Framework; +using Umbraco.Core.Configuration; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded; using Umbraco.ModelsBuilder.Embedded.Building; -using Umbraco.ModelsBuilder.Embedded.Configuration; namespace Umbraco.Tests.ModelsBuilder { diff --git a/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs b/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs index ff49bb3f97..4a9e8704ec 100644 --- a/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs +++ b/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs @@ -1,6 +1,7 @@ using System.Configuration; using NUnit.Framework; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Configuration; +using Umbraco.Core; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.ModelsBuilder @@ -26,7 +27,7 @@ namespace Umbraco.Tests.ModelsBuilder public void DefaultModelsNamespace() { var config = new ModelsBuilderConfig(TestHelper.IOHelper); - Assert.AreEqual(ModelsBuilderConfig.DefaultModelsNamespace, config.ModelsNamespace); + Assert.AreEqual(Constants.ModelsBuilder.DefaultModelsNamespace, config.ModelsNamespace); } [TestCase("c:/path/to/root", "~/dir/models", false, "c:\\path\\to\\root\\dir\\models")] diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs index 1f153a0a5e..de12fcf7aa 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs @@ -144,6 +144,7 @@ namespace Umbraco.Tests.PublishedContent _source = new TestDataSource(kits); var typeFinder = new TypeFinder(Mock.Of()); + var settings = Mock.Of(); // at last, create the complete NuCache snapshot service! @@ -169,7 +170,8 @@ namespace Umbraco.Tests.PublishedContent typeFinder, hostingEnvironment, new MockShortStringHelper(), - TestHelper.IOHelper); + TestHelper.IOHelper, + settings); // invariant is the current default _variationAccesor.VariationContext = new VariationContext(); diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs index b0f0eb7722..08da25ba9a 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs @@ -185,6 +185,7 @@ namespace Umbraco.Tests.PublishedContent _variationAccesor = new TestVariationContextAccessor(); var typeFinder = new TypeFinder(Mock.Of()); + var settings = Mock.Of(); // at last, create the complete NuCache snapshot service! var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; @@ -209,7 +210,8 @@ namespace Umbraco.Tests.PublishedContent typeFinder, TestHelper.GetHostingEnvironment(), new MockShortStringHelper(), - TestHelper.IOHelper); + TestHelper.IOHelper, + settings); // invariant is the current default _variationAccesor.VariationContext = new VariationContext(); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs index 875117afbc..227a7c26e3 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs @@ -1,10 +1,8 @@ -using Moq; -using NUnit.Framework; +using NUnit.Framework; using Umbraco.Core; -using Umbraco.Core.Composing; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Request; using Umbraco.Tests.TestHelpers; -using Umbraco.Web; using Umbraco.Web.Routing; namespace Umbraco.Tests.Routing @@ -20,7 +18,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlAsString); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByIdPath(Factory.GetInstance().WebRouting, Logger, HttpContextAccessor); + var lookup = new ContentFinderByIdPath(Factory.GetInstance().WebRouting, Logger, Factory.GetInstance()); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByPageIdQueryTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByPageIdQueryTests.cs index 20bbeb92d4..d18353eb87 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByPageIdQueryTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByPageIdQueryTests.cs @@ -1,5 +1,6 @@ using Moq; using NUnit.Framework; +using Umbraco.Core.Request; using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.Routing; @@ -20,15 +21,10 @@ namespace Umbraco.Tests.Routing var httpContext = GetHttpContextFactory(urlAsString).HttpContext; var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var mockHttpContextAccessor = new Mock(); - mockHttpContextAccessor.Setup(x => x.HttpContext).Returns(httpContext); - var lookup = new ContentFinderByPageIdQuery(mockHttpContextAccessor.Object); + var mockRequestAccessor = new Mock(); + mockRequestAccessor.Setup(x => x.GetRequestValue("umbPageID")).Returns(httpContext.Request.QueryString["umbPageID"]); - //we need to manually stub the return output of HttpContext.Request["umbPageId"] - var requestMock = Mock.Get(httpContext.Request); - - requestMock.Setup(x => x["umbPageID"]) - .Returns(httpContext.Request.QueryString["umbPageID"]); + var lookup = new ContentFinderByPageIdQuery(mockRequestAccessor.Object); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index ee9808c005..48436d6690 100644 --- a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs +++ b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs @@ -2,10 +2,8 @@ using System.Linq; using System.Web.Mvc; using System.Web.Routing; -using System.Web.Security; using Moq; using NUnit.Framework; -using NUnit.Framework.Internal; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; @@ -17,22 +15,17 @@ using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using Umbraco.Core.Strings; -using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Dictionary; using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.Persistence; using Umbraco.Core.Services; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.Testing; using Umbraco.Tests.Testing.Objects.Accessors; -using Umbraco.Web.PublishedCache; using Umbraco.Web.Runtime; -using Umbraco.Web.Security; using Current = Umbraco.Web.Composing.Current; -using Umbraco.Web.Security.Providers; using ILogger = Umbraco.Core.Logging.ILogger; namespace Umbraco.Tests.Routing @@ -141,10 +134,9 @@ namespace Umbraco.Tests.Routing var url = "~/dummy-page"; var template = CreateTemplate(templateName); var route = RouteTable.Routes["Umbraco_default"]; - var routeData = new RouteData() {Route = route}; + var routeData = new RouteData() { Route = route }; var umbracoContext = GetUmbracoContext("~/dummy-page", template.Id, routeData, true); var httpContext = GetHttpContextFactory(url, routeData).HttpContext; - var httpContextAccessor = TestHelper.GetHttpContextAccessor(httpContext); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.PublishedContent = umbracoContext.Content.GetById(1172); @@ -156,12 +148,12 @@ namespace Umbraco.Tests.Routing var handler = new RenderRouteHandler(umbracoContext, new TestControllerFactory(umbracoContextAccessor, Mock.Of(), context => { + return new CustomDocumentController(Factory.GetInstance(), umbracoContextAccessor, Factory.GetInstance(), Factory.GetInstance(), - Factory.GetInstance(), - new UmbracoHelper(Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of())); + Factory.GetInstance()); }), ShortStringHelper); handler.GetHandlerForRoute(httpContext.Request.RequestContext, frequest); @@ -198,8 +190,8 @@ namespace Umbraco.Tests.Routing /// public class CustomDocumentController : RenderMvcController { - public CustomDocumentController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) - : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, umbracoHelper) + public CustomDocumentController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger) + : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger) { } diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 9cf6b3d773..783beafb2e 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -86,6 +86,7 @@ namespace Umbraco.Tests.Scoping var hostingEnvironment = TestHelper.GetHostingEnvironment(); var typeFinder = new TypeFinder(Mock.Of()); + var settings = Mock.Of(); return new PublishedSnapshotService( options, @@ -107,7 +108,8 @@ namespace Umbraco.Tests.Scoping typeFinder, hostingEnvironment, new MockShortStringHelper(), - IOHelper); + IOHelper, + settings); } protected IUmbracoContext GetUmbracoContextNu(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null) diff --git a/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs b/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs index 1a485ec546..1b6b632a10 100644 --- a/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs +++ b/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs @@ -59,6 +59,7 @@ namespace Umbraco.Tests.Services var hostingEnvironment = Mock.Of(); var typeFinder = new TypeFinder(Mock.Of()); + var settings = Mock.Of(); return new PublishedSnapshotService( options, @@ -80,7 +81,8 @@ namespace Umbraco.Tests.Services typeFinder, hostingEnvironment, new MockShortStringHelper(), - IOHelper); + IOHelper, + settings); } public class LocalServerMessenger : ServerMessengerBase diff --git a/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs b/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs index e8b4a993c4..b09620103b 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseWebTest.cs @@ -10,7 +10,9 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Request; using Umbraco.Core.Services; +using Umbraco.Core.Services.Implement; using Umbraco.Core.Strings; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers.Stubs; @@ -19,6 +21,7 @@ using Umbraco.Web; using Umbraco.Web.Composing; using Umbraco.Web.Models.PublishedContent; using Umbraco.Web.Routing; +using Umbraco.Web.Security; namespace Umbraco.Tests.TestHelpers { @@ -97,12 +100,16 @@ namespace Umbraco.Tests.TestHelpers contentFinders ?? new ContentFinderCollection(Enumerable.Empty()), new TestLastChanceFinder(), new TestVariationContextAccessor(), - container?.TryGetInstance() ?? ServiceContext.CreatePartial(), new ProfilingLogger(Mock.Of(), Mock.Of()), container?.TryGetInstance() ?? Current.Factory.GetInstance(), - Mock.Of(), - Mock.Of() - ); + Mock.Of(), + Mock.Of(), + container?.GetInstance() ?? Current.Factory.GetInstance(), + container?.GetInstance()?? Current.Factory.GetInstance(), + container?.GetInstance()?? Current.Factory.GetInstance(), + container?.GetInstance() ?? Current.Factory.GetInstance(), + container?.GetInstance() ?? Current.Factory.GetInstance() + ); } } } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivator.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivator.cs index 6b67377202..d3cc51b38d 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivator.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivator.cs @@ -7,16 +7,16 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting { public class TestControllerActivator : TestControllerActivatorBase { - private readonly Func _factory; + private readonly Func _factory; - public TestControllerActivator(Func factory) + public TestControllerActivator(Func factory) { _factory = factory; } - protected override ApiController CreateController(Type controllerType, HttpRequestMessage msg, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + protected override ApiController CreateController(Type controllerType, HttpRequestMessage msg, IUmbracoContextAccessor umbracoContextAccessor) { - return _factory(msg, umbracoContextAccessor, helper); + return _factory(msg, umbracoContextAccessor); } } } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 611ba086f5..35197e13e0 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -154,15 +154,9 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(UrlInfo.Url("/hello/world/1234")); - var umbHelper = new UmbracoHelper(Mock.Of(), - Mock.Of(), - Mock.Of(), - Mock.Of(), - Mock.Of()); - - return CreateController(controllerType, request, umbracoContextAccessor, umbHelper); + return CreateController(controllerType, request, umbracoContextAccessor); } - protected abstract ApiController CreateController(Type controllerType, HttpRequestMessage msg, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper); + protected abstract ApiController CreateController(Type controllerType, HttpRequestMessage msg, IUmbracoContextAccessor umbracoContextAccessor); } } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestRunner.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestRunner.cs index 9f9f933d72..34b649d3bb 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestRunner.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestRunner.cs @@ -15,9 +15,9 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting { public class TestRunner { - private readonly Func _controllerFactory; + private readonly Func _controllerFactory; - public TestRunner(Func controllerFactory) + public TestRunner(Func controllerFactory) { _controllerFactory = controllerFactory; } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestStartup.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestStartup.cs index 0827a1f786..f038112b0b 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestStartup.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestStartup.cs @@ -16,10 +16,10 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting /// public class TestStartup { - private readonly Func _controllerFactory; + private readonly Func _controllerFactory; private readonly Action _initialize; - public TestStartup(Action initialize, Func controllerFactory) + public TestStartup(Action initialize, Func controllerFactory) { _controllerFactory = controllerFactory; _initialize = initialize; diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index c604e1a5d6..439c9b17f2 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -66,7 +66,6 @@ namespace Umbraco.Tests.Testing.TestingTests // ReSharper disable once UnusedVariable var helper = new UmbracoHelper(Mock.Of(), - Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of()); @@ -106,11 +105,9 @@ namespace Umbraco.Tests.Testing.TestingTests var memberTypeService = Mock.Of(); var membershipProvider = new MembersMembershipProvider(memberService, memberTypeService, Mock.Of(), TestHelper.GetHostingEnvironment(), TestHelper.GetIpResolver()); var membershipHelper = new MembershipHelper(Mock.Of(), Mock.Of(), membershipProvider, Mock.Of(), memberService, memberTypeService, Mock.Of(), AppCaches.Disabled, logger, ShortStringHelper, Mock.Of()); - var umbracoHelper = new UmbracoHelper(Mock.Of(), Mock.Of(), Mock.Of(), - Mock.Of(), Mock.Of()); var umbracoMapper = new UmbracoMapper(new MapDefinitionCollection(new[] { Mock.Of() })); - var umbracoApiController = new FakeUmbracoApiController(Mock.Of(), Mock.Of(), Mock.Of(), ServiceContext.CreatePartial(), AppCaches.NoCache, logger, Mock.Of(), umbracoHelper, umbracoMapper, Mock.Of()); + var umbracoApiController = new FakeUmbracoApiController(Mock.Of(), Mock.Of(), Mock.Of(), ServiceContext.CreatePartial(), AppCaches.NoCache, logger, Mock.Of(), umbracoMapper, Mock.Of()); Assert.Pass(); } @@ -118,7 +115,7 @@ namespace Umbraco.Tests.Testing.TestingTests internal class FakeUmbracoApiController : UmbracoApiController { - public FakeUmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) { } + public FakeUmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { } } } diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index c87b92f1c9..de0db554f3 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Web.Routing; +using System.Web.Security; using System.Xml.Linq; using Examine; using Moq; @@ -51,12 +52,15 @@ using Umbraco.Web.Templates; using Umbraco.Web.PropertyEditors; using Umbraco.Core.Dictionary; using Umbraco.Core.Models; -using Umbraco.Core.Models.Identity; +using Umbraco.Core.Request; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Net; +using Umbraco.Tests.LegacyXmlPublishedCache; +using Umbraco.Web.AspNet; using Umbraco.Web.Install; using Umbraco.Web.Security; +using Umbraco.Web.Security.Providers; using Umbraco.Web.Trees; using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Tests.Testing @@ -203,6 +207,18 @@ namespace Umbraco.Tests.Testing Composition.RegisterUnique(ipResolver); Composition.RegisterUnique(); Composition.RegisterUnique(TestHelper.ShortStringHelper); + Composition.RegisterUnique(); + Composition.RegisterUnique(); + + + var memberService = Mock.Of(); + var memberTypeService = Mock.Of(); + var membershipProvider = new MembersMembershipProvider(memberService, memberTypeService, Mock.Of(), TestHelper.GetHostingEnvironment(), TestHelper.GetIpResolver()); + var membershipHelper = new MembershipHelper(Mock.Of(), Mock.Of(), membershipProvider, Mock.Of(), memberService, memberTypeService, Mock.Of(), AppCaches.Disabled, logger, ShortStringHelper, Mock.Of()); + + Composition.RegisterUnique(membershipHelper); + + TestObjects = new TestObjects(register); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 9815c94728..56d36981b3 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -322,7 +322,6 @@ - diff --git a/src/Umbraco.Tests/Web/Controllers/AuthenticationControllerTests.cs b/src/Umbraco.Tests/Web/Controllers/AuthenticationControllerTests.cs index a176067541..9ecedee056 100644 --- a/src/Umbraco.Tests/Web/Controllers/AuthenticationControllerTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/AuthenticationControllerTests.cs @@ -61,7 +61,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async System.Threading.Tasks.Task GetCurrentUser_Fips() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { //setup some mocks var userServiceMock = Mock.Get(ServiceContext.UserService); @@ -87,7 +87,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), diff --git a/src/Umbraco.Tests/Web/Controllers/ContentControllerTests.cs b/src/Umbraco.Tests/Web/Controllers/ContentControllerTests.cs index 2ed2ff568f..e3c2a89593 100644 --- a/src/Umbraco.Tests/Web/Controllers/ContentControllerTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/ContentControllerTests.cs @@ -252,7 +252,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async Task PostSave_Validate_Existing_Content() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var contentServiceMock = Mock.Get(ServiceContext.ContentService); contentServiceMock.Setup(x => x.GetById(123)).Returns(() => null); //do not find it @@ -269,7 +269,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance()); @@ -293,7 +292,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async Task PostSave_Validate_At_Least_One_Variant_Flagged_For_Saving() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var propertyEditorCollection = new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty())); var controller = new ContentController( @@ -306,7 +305,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance()); @@ -335,7 +333,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async Task PostSave_Validate_Properties_Exist() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var contentServiceMock = Mock.Get(ServiceContext.ContentService); contentServiceMock.Setup(x => x.GetById(123)).Returns(() => GetMockedContent()); @@ -351,7 +349,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance()); @@ -383,7 +380,7 @@ namespace Umbraco.Tests.Web.Controllers { var content = GetMockedContent(); - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var contentServiceMock = Mock.Get(ServiceContext.ContentService); contentServiceMock.Setup(x => x.GetById(123)).Returns(() => content); @@ -401,7 +398,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance()); @@ -425,7 +421,7 @@ namespace Umbraco.Tests.Web.Controllers { var content = GetMockedContent(); - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var contentServiceMock = Mock.Get(ServiceContext.ContentService); contentServiceMock.Setup(x => x.GetById(123)).Returns(() => content); @@ -443,7 +439,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance() @@ -474,7 +469,7 @@ namespace Umbraco.Tests.Web.Controllers { var content = GetMockedContent(); - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var contentServiceMock = Mock.Get(ServiceContext.ContentService); contentServiceMock.Setup(x => x.GetById(123)).Returns(() => content); @@ -492,7 +487,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, ShortStringHelper, Factory.GetInstance(), Factory.GetInstance() diff --git a/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs b/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs index b0665bbfc1..23131b04e6 100644 --- a/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/PluginControllerAreaTests.cs @@ -54,7 +54,7 @@ namespace Umbraco.Tests.Web.Controllers public class Plugin1Controller : PluginController { public Plugin1Controller(IUmbracoContextAccessor umbracoContextAccessor) - : base(umbracoContextAccessor, null, null, null, null, null, null) + : base(umbracoContextAccessor, null, null, null, null, null) { } } @@ -63,7 +63,7 @@ namespace Umbraco.Tests.Web.Controllers public class Plugin2Controller : PluginController { public Plugin2Controller(IUmbracoContextAccessor umbracoContextAccessor) - : base(umbracoContextAccessor, null, null, null, null, null, null) + : base(umbracoContextAccessor, null, null, null, null, null) { } } @@ -72,7 +72,7 @@ namespace Umbraco.Tests.Web.Controllers public class Plugin3Controller : PluginController { public Plugin3Controller(IUmbracoContextAccessor umbracoContextAccessor) - : base(umbracoContextAccessor, null, null, null, null, null, null) + : base(umbracoContextAccessor, null, null, null, null, null) { } } @@ -80,7 +80,7 @@ namespace Umbraco.Tests.Web.Controllers public class Plugin4Controller : PluginController { public Plugin4Controller(IUmbracoContextAccessor umbracoContextAccessor) - : base(umbracoContextAccessor, null, null, null, null, null, null) + : base(umbracoContextAccessor, null, null, null, null, null) { } } diff --git a/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs b/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs index 0b0fa8f157..d914ef2c39 100644 --- a/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async System.Threading.Tasks.Task Save_User() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var userServiceMock = Mock.Get(ServiceContext.UserService); @@ -86,7 +86,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, Factory.GetInstance(), ShortStringHelper, Factory.GetInstance(), @@ -149,7 +148,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async System.Threading.Tasks.Task GetPagedUsers_Empty() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { var usersController = new UsersController( Factory.GetInstance(), @@ -159,7 +158,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, Factory.GetInstance(), ShortStringHelper, Factory.GetInstance(), @@ -183,7 +181,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] public async System.Threading.Tasks.Task GetPagedUsers_10() { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { //setup some mocks var userServiceMock = Mock.Get(ServiceContext.UserService); @@ -202,7 +200,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, Factory.GetInstance(), ShortStringHelper, Factory.GetInstance(), @@ -266,7 +263,7 @@ namespace Umbraco.Tests.Web.Controllers Action> verification, object routeDefaults = null, string url = null) { - ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper) + ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor) { //setup some mocks var userServiceMock = Mock.Get(ServiceContext.UserService); @@ -280,7 +277,6 @@ namespace Umbraco.Tests.Web.Controllers Factory.GetInstance(), Factory.GetInstance(), Factory.GetInstance(), - helper, Factory.GetInstance(), ShortStringHelper, Factory.GetInstance(), diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index fd222086aa..73d447d3b2 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -5,6 +5,7 @@ using System.Web.Routing; using System.Web.Security; using Moq; using NUnit.Framework; +using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Dictionary; using Umbraco.Core.Logging; @@ -26,6 +27,7 @@ namespace Umbraco.Tests.Web.Mvc [UmbracoTest(WithApplication = true)] public class SurfaceControllerTests : UmbracoTestBase { + public override void SetUp() { base.SetUp(); @@ -55,7 +57,7 @@ namespace Umbraco.Tests.Web.Mvc var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var ctrl = new TestSurfaceController(umbracoContextAccessor); + var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of()); var result = ctrl.Index(); @@ -85,7 +87,7 @@ namespace Umbraco.Tests.Web.Mvc var umbracoContextAccessor = new TestUmbracoContextAccessor(umbCtx); - var ctrl = new TestSurfaceController(umbracoContextAccessor); + var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of()); Assert.IsNotNull(ctrl.UmbracoContext); } @@ -118,14 +120,9 @@ namespace Umbraco.Tests.Web.Mvc var umbracoContextAccessor = new TestUmbracoContextAccessor(umbracoContext); - var helper = new UmbracoHelper( - content.Object, - Mock.Of(), - Mock.Of(), - Mock.Of(), - Mock.Of(query => query.Content(2) == content.Object)); + var publishedContentQuery = Mock.Of(query => query.Content(2) == content.Object); - var ctrl = new TestSurfaceController(umbracoContextAccessor, helper); + var ctrl = new TestSurfaceController(umbracoContextAccessor,publishedContentQuery); var result = ctrl.GetContent(2) as PublishedContentResult; Assert.IsNotNull(result); @@ -171,7 +168,7 @@ namespace Umbraco.Tests.Web.Mvc var routeData = new RouteData(); routeData.DataTokens.Add(Core.Constants.Web.UmbracoRouteDefinitionDataToken, routeDefinition); - var ctrl = new TestSurfaceController(umbracoContextAccessor, new UmbracoHelper()); + var ctrl = new TestSurfaceController(umbracoContextAccessor, Mock.Of()); ctrl.ControllerContext = new ControllerContext(Mock.Of(), routeData, ctrl); var result = ctrl.GetContentFromCurrentPage() as PublishedContentResult; @@ -181,9 +178,12 @@ namespace Umbraco.Tests.Web.Mvc public class TestSurfaceController : SurfaceController { - public TestSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper = null) - : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, null, helper) + private readonly IPublishedContentQuery _publishedContentQuery; + + public TestSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IPublishedContentQuery publishedContentQuery) + : base(umbracoContextAccessor, null, ServiceContext.CreatePartial(), AppCaches.Disabled, null, null) { + _publishedContentQuery = publishedContentQuery; } public ActionResult Index() @@ -194,7 +194,7 @@ namespace Umbraco.Tests.Web.Mvc public ActionResult GetContent(int id) { - var content = Umbraco.Content(id); + var content = _publishedContentQuery.Content(id); return new PublishedContentResult(content); } diff --git a/src/Umbraco.Tests/Web/UmbracoHelperTests.cs b/src/Umbraco.Tests/Web/UmbracoHelperTests.cs index ccb42e478a..b479961896 100644 --- a/src/Umbraco.Tests/Web/UmbracoHelperTests.cs +++ b/src/Umbraco.Tests/Web/UmbracoHelperTests.cs @@ -24,234 +24,6 @@ namespace Umbraco.Tests.Web Current.Reset(); } - - - // ------- Int32 conversion tests - [Test] - public static void Converting_Boxed_34_To_An_Int_Returns_34() - { - // Arrange - const int sample = 34; - - // Act - bool success = UmbracoHelper.ConvertIdObjectToInt( - sample, - out int result - ); - - // Assert - Assert.IsTrue(success); - Assert.That(result, Is.EqualTo(34)); - } - - [Test] - public static void Converting_String_54_To_An_Int_Returns_54() - { - // Arrange - const string sample = "54"; - - // Act - bool success = UmbracoHelper.ConvertIdObjectToInt( - sample, - out int result - ); - - // Assert - Assert.IsTrue(success); - Assert.That(result, Is.EqualTo(54)); - } - - [Test] - public static void Converting_Hello_To_An_Int_Returns_False() - { - // Arrange - const string sample = "Hello"; - - // Act - bool success = UmbracoHelper.ConvertIdObjectToInt( - sample, - out int result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.EqualTo(0)); - } - - [Test] - public static void Converting_Unsupported_Object_To_An_Int_Returns_False() - { - // Arrange - var clearlyWillNotConvertToInt = new StringBuilder(0); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToInt( - clearlyWillNotConvertToInt, - out int result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.EqualTo(0)); - } - - // ------- GUID conversion tests - [Test] - public static void Converting_Boxed_Guid_To_A_Guid_Returns_Original_Guid_Value() - { - // Arrange - Guid sample = Guid.NewGuid(); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToGuid( - sample, - out Guid result - ); - - // Assert - Assert.IsTrue(success); - Assert.That(result, Is.EqualTo(sample)); - } - - [Test] - public static void Converting_String_Guid_To_A_Guid_Returns_Original_Guid_Value() - { - // Arrange - Guid sample = Guid.NewGuid(); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToGuid( - sample.ToString(), - out Guid result - ); - - // Assert - Assert.IsTrue(success); - Assert.That(result, Is.EqualTo(sample)); - } - - [Test] - public static void Converting_Hello_To_A_Guid_Returns_False() - { - // Arrange - const string sample = "Hello"; - - // Act - bool success = UmbracoHelper.ConvertIdObjectToGuid( - sample, - out Guid result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.EqualTo(new Guid("00000000-0000-0000-0000-000000000000"))); - } - - [Test] - public static void Converting_Unsupported_Object_To_A_Guid_Returns_False() - { - // Arrange - var clearlyWillNotConvertToGuid = new StringBuilder(0); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToGuid( - clearlyWillNotConvertToGuid, - out Guid result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.EqualTo(new Guid("00000000-0000-0000-0000-000000000000"))); - } - - // ------- UDI Conversion Tests - /// - /// This requires PluginManager.Current to be initialised before running. - /// - [Test] - public static void Converting_Boxed_Udi_To_A_Udi_Returns_Original_Udi_Value() - { - // Arrange - UdiParser.ResetUdiTypes(); - Udi sample = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.NewGuid()); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToUdi( - sample, - out Udi result - ); - - // Assert - Assert.IsTrue(success); - Assert.That(result, Is.EqualTo(sample)); - } - - /// - /// This requires PluginManager.Current to be initialised before running. - /// - [Test] - public void Converting_String_Udi_To_A_Udi_Returns_Original_Udi_Value() - { - // Arrange - SetUpDependencyContainer(); - UdiParser.ResetUdiTypes(); - Udi sample = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.NewGuid()); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToUdi( - sample.ToString(), - out Udi result - ); - - // Assert - Assert.IsTrue(success, "Conversion of UDI failed."); - Assert.That(result, Is.EqualTo(sample)); - } - - /// - /// This requires PluginManager.Current to be initialised before running. - /// - [Test] - public void Converting_Hello_To_A_Udi_Returns_False() - { - // Arrange - SetUpDependencyContainer(); - UdiParser.ResetUdiTypes(); - const string sample = "Hello"; - - // Act - bool success = UmbracoHelper.ConvertIdObjectToUdi( - sample, - out Udi result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.Null); - } - - /// - /// This requires PluginManager.Current to be initialised before running. - /// - [Test] - public static void Converting_Unsupported_Object_To_A_Udi_Returns_False() - { - // Arrange - UdiParser.ResetUdiTypes(); - - var clearlyWillNotConvertToGuid = new StringBuilder(0); - - // Act - bool success = UmbracoHelper.ConvertIdObjectToUdi( - clearlyWillNotConvertToGuid, - out Udi result - ); - - // Assert - Assert.IsFalse(success); - Assert.That(result, Is.Null); - } - private void SetUpDependencyContainer() { // FIXME: bad in a unit test - but Udi has a static ctor that wants it?! diff --git a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/Gallery.cshtml b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/Gallery.cshtml index 8bcb535bd6..9462b3b638 100755 --- a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/Gallery.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/Gallery.cshtml @@ -26,7 +26,7 @@
@foreach (var mediaId in mediaIds.Split(',')) { - var media = Umbraco.Media(mediaId); + var media = Current.PublishedContentQuery.Media(mediaId); @* a single image *@ if (media.IsDocumentType("Image")) diff --git a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListChildPagesFromChangeableSource.cshtml b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListChildPagesFromChangeableSource.cshtml index 46c8de695c..ec41d45c0c 100755 --- a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListChildPagesFromChangeableSource.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListChildPagesFromChangeableSource.cshtml @@ -1,4 +1,5 @@ @using Umbraco.Web +@using Umbraco.Web.Composing @inherits Umbraco.Web.Macros.PartialViewMacroPage @* @@ -18,7 +19,7 @@ @if (startNodeId != null) { @* Get the starting page *@ - var startNode = Umbraco.Content(startNodeId); + var startNode = Current.PublishedContentQuery.Content(startNodeId); var selection = startNode.Children.Where(x => x.IsVisible()).ToArray(); if (selection.Length > 0) diff --git a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListImagesFromMediaFolder.cshtml b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListImagesFromMediaFolder.cshtml index 7a561cf94d..386bc824df 100755 --- a/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListImagesFromMediaFolder.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/PartialViewMacros/Templates/ListImagesFromMediaFolder.cshtml @@ -1,4 +1,5 @@ @using Umbraco.Web +@using Umbraco.Web.Composing @inherits Umbraco.Web.Macros.PartialViewMacroPage @* @@ -18,7 +19,7 @@ @if (mediaId != null) { @* Get the media item associated with the id passed in *@ - var media = Umbraco.Media(mediaId); + var media = Current.PublishedContentQuery.Media(mediaId); var selection = media.Children.ToArray(); if (selection.Length > 0) diff --git a/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml b/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml index 11033aa785..e41185d74b 100644 --- a/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml @@ -48,7 +48,7 @@ redirectUrl = Url.Action("AuthorizeUpgrade", "BackOffice") }); } - @Html.BareMinimumServerVariablesScript(Url, externalLoginUrl, Model.Features, Model.GlobalSettings, Model.UmbracoVersion, Model.UmbracoSettingsSection, Model.IOHelper, Model.TreeCollection, Model.HttpContextAccessor, Model.HostingEnvironment) + @Html.BareMinimumServerVariablesScript(Url, externalLoginUrl, Model.Features, Model.GlobalSettings, Model.UmbracoVersion, Model.UmbracoSettingsSection, Model.IOHelper, Model.TreeCollection, Model.HttpContextAccessor, Model.HostingEnvironment, Model.RuntimeSettings)