From 7daee53c64f4fbb42ef59fd39d2be3c57cc97bf5 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Fri, 28 Feb 2020 11:15:25 +0100 Subject: [PATCH 01/10] Isolated more web usages - Membership and Request stuff - Moved a few more files --- src/Umbraco.Core/Cookie/ICookieManager.cs | 1 + src/Umbraco.Core/Request/IRequestAccessor.cs | 8 + .../Routing/ContentFinderByIdPath.cs | 15 +- .../Routing/ContentFinderByPageIdQuery.cs | 12 +- .../Routing/PublishedRouter.cs | 155 +++++++++++------- .../Security/IMemberUserKeyProvider.cs | 7 + .../Security/IPublicAccessChecker.cs | 7 + .../Security/PublicAccessStatus.cs | 11 ++ src/Umbraco.Core/Session/ISessionManager.cs | 8 + .../PostMigrations/ClearCsrfCookies.cs | 1 - .../Routing/RedirectTrackingComponent.cs | 11 +- .../Routing/RedirectTrackingComposer.cs | 0 .../Routing/ContentFinderByIdTests.cs | 8 +- .../ContentFinderByPageIdQueryTests.cs | 12 +- src/Umbraco.Tests/TestHelpers/BaseWebTest.cs | 15 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 18 +- .../config/imageprocessor/processing.config | 38 +---- .../AspNet/AspNetRequestAccessor.cs | 24 +++ .../AspNet/AspNetSessionIdResolver.cs | 11 -- .../AspNet/AspNetSessionManager.cs | 26 +++ src/Umbraco.Web/Macros/MacroRenderer.cs | 49 +++--- .../Macros/MemberUserKeyProvider.cs | 17 ++ src/Umbraco.Web/Runtime/WebInitialComposer.cs | 20 ++- .../Security/PublicAccessChecker.cs | 54 ++++++ src/Umbraco.Web/Umbraco.Web.csproj | 12 +- src/Umbraco.Web/UmbracoApplicationBase.cs | 3 +- 26 files changed, 369 insertions(+), 174 deletions(-) create mode 100644 src/Umbraco.Core/Request/IRequestAccessor.cs rename src/{Umbraco.Web => Umbraco.Core}/Routing/ContentFinderByIdPath.cs (88%) rename src/{Umbraco.Web => Umbraco.Core}/Routing/ContentFinderByPageIdQuery.cs (69%) rename src/{Umbraco.Web => Umbraco.Core}/Routing/PublishedRouter.cs (84%) create mode 100644 src/Umbraco.Core/Security/IMemberUserKeyProvider.cs create mode 100644 src/Umbraco.Core/Security/IPublicAccessChecker.cs create mode 100644 src/Umbraco.Core/Security/PublicAccessStatus.cs create mode 100644 src/Umbraco.Core/Session/ISessionManager.cs rename src/{Umbraco.Web => Umbraco.Infrastructure}/Routing/RedirectTrackingComponent.cs (93%) rename src/{Umbraco.Web => Umbraco.Infrastructure}/Routing/RedirectTrackingComposer.cs (100%) create mode 100644 src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs delete mode 100644 src/Umbraco.Web/AspNet/AspNetSessionIdResolver.cs create mode 100644 src/Umbraco.Web/AspNet/AspNetSessionManager.cs mode change 100755 => 100644 src/Umbraco.Web/Macros/MacroRenderer.cs create mode 100644 src/Umbraco.Web/Macros/MemberUserKeyProvider.cs create mode 100644 src/Umbraco.Web/Security/PublicAccessChecker.cs 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..52d532de26 --- /dev/null +++ b/src/Umbraco.Core/Request/IRequestAccessor.cs @@ -0,0 +1,8 @@ +namespace Umbraco.Core.Request +{ + public interface IRequestAccessor + { + string GetRequestValue(string name); + string GetQueryStringValue(string culture); + } +} 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 84% rename from src/Umbraco.Web/Routing/PublishedRouter.cs rename to src/Umbraco.Core/Routing/PublishedRouter.cs index 1a6048e4ec..90d0d8876c 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,59 +566,66 @@ 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 + // { + // // 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 + // { + // _logger.Debug("Current member has access"); + // } + // } } else { @@ -615,6 +633,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 +661,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 +698,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 +760,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 +779,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 +788,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.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.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.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/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/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.Web.UI/config/imageprocessor/processing.config b/src/Umbraco.Web.UI/config/imageprocessor/processing.config index 34c9fd96c4..dddcddb0bd 100644 --- a/src/Umbraco.Web.UI/config/imageprocessor/processing.config +++ b/src/Umbraco.Web.UI/config/imageprocessor/processing.config @@ -1,38 +1,10 @@  - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + @@ -63,4 +35,4 @@ - \ No newline at end of file + diff --git a/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs new file mode 100644 index 0000000000..d2675b0dc1 --- /dev/null +++ b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs @@ -0,0 +1,24 @@ +using Umbraco.Core.Request; + +namespace Umbraco.Web.AspNet +{ + public class AspNetRequestAccessor : IRequestAccessor + { + private readonly IHttpContextAccessor _httpContextAccessor; + + public AspNetRequestAccessor(IHttpContextAccessor httpContextAccessor) + { + _httpContextAccessor = httpContextAccessor; + } + + public string GetRequestValue(string name) + { + return _httpContextAccessor.GetRequiredHttpContext().Request[name]; + } + + public string GetQueryStringValue(string name) + { + return _httpContextAccessor.GetRequiredHttpContext().Request.QueryString[name]; + } + } +} diff --git a/src/Umbraco.Web/AspNet/AspNetSessionIdResolver.cs b/src/Umbraco.Web/AspNet/AspNetSessionIdResolver.cs deleted file mode 100644 index 1b22ebaa60..0000000000 --- a/src/Umbraco.Web/AspNet/AspNetSessionIdResolver.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Web; -using Umbraco.Core; -using Umbraco.Net; - -namespace Umbraco.Web -{ - internal class AspNetSessionIdResolver : ISessionIdResolver - { - public string SessionId => HttpContext.Current?.Session?.SessionID; - } -} diff --git a/src/Umbraco.Web/AspNet/AspNetSessionManager.cs b/src/Umbraco.Web/AspNet/AspNetSessionManager.cs new file mode 100644 index 0000000000..bf7b1c05c3 --- /dev/null +++ b/src/Umbraco.Web/AspNet/AspNetSessionManager.cs @@ -0,0 +1,26 @@ +using System.Web; +using Umbraco.Core.Session; +using Umbraco.Net; + +namespace Umbraco.Web.AspNet +{ + public class AspNetSessionManager: ISessionManager, ISessionIdResolver + { + + public AspNetSessionManager() + { + } + + public object GetSessionValue(string sessionName) + { + return HttpContext.Current.Session[sessionName]; + } + + public void SetSessionValue(string sessionName, object value) + { + HttpContext.Current.Session[sessionName] = value; + } + + public string SessionId => HttpContext.Current?.Session?.SessionID; + } +} diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs old mode 100755 new mode 100644 index 85861a1496..8518293241 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; @@ -12,10 +11,11 @@ using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Macros; -using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.Request; +using Umbraco.Core.Security; using Umbraco.Core.Services; -using Umbraco.Web.Security; +using Umbraco.Core.Session; namespace Umbraco.Web.Macros { @@ -29,10 +29,23 @@ namespace Umbraco.Web.Macros private readonly IMacroService _macroService; private readonly IIOHelper _ioHelper; private readonly ICookieManager _cookieManager; - private readonly IUserService _userService; - private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IMemberUserKeyProvider _memberUserKeyProvider; + private readonly ISessionManager _sessionManager; + private readonly IRequestAccessor _requestAccessor; - public MacroRenderer(IProfilingLogger plogger, IUmbracoContextAccessor umbracoContextAccessor, IContentSection contentSection, ILocalizedTextService textService, AppCaches appCaches, IMacroService macroService, IUserService userService, IHttpContextAccessor httpContextAccessor, IIOHelper ioHelper, ICookieManager cookieManager) + + public MacroRenderer( + IProfilingLogger plogger, + IUmbracoContextAccessor umbracoContextAccessor, + IContentSection contentSection, + ILocalizedTextService textService, + AppCaches appCaches, + IMacroService macroService, + IIOHelper ioHelper, + ICookieManager cookieManager, + IMemberUserKeyProvider memberUserKeyProvider, + ISessionManager sessionManager, + IRequestAccessor requestAccessor) { _plogger = plogger ?? throw new ArgumentNullException(nameof(plogger)); _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); @@ -42,8 +55,9 @@ namespace Umbraco.Web.Macros _macroService = macroService ?? throw new ArgumentNullException(nameof(macroService)); _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); _cookieManager = cookieManager; - _userService = userService ?? throw new ArgumentNullException(nameof(userService)); - _httpContextAccessor = httpContextAccessor; + _memberUserKeyProvider = memberUserKeyProvider; + _sessionManager = sessionManager; + _requestAccessor = requestAccessor; } #region MacroContent cache @@ -63,12 +77,9 @@ namespace Umbraco.Web.Macros { object key = 0; - if (_httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false) + if (_umbracoContextAccessor.UmbracoContext.Security.IsAuthenticated()) { - //ugh, membershipproviders :( - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - var member = MembershipProviderExtensions.GetCurrentUser(provider); - key = member?.ProviderUserKey ?? 0; + key = _memberUserKeyProvider.GetMemberProviderUserKey() ?? 0; } id.AppendFormat("m{0}-", key); @@ -127,10 +138,8 @@ namespace Umbraco.Web.Macros // do not cache if it should cache by member and there's not member if (model.CacheByMember) { - var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); - var member = MembershipProviderExtensions.GetCurrentUser(provider); - var key = member?.ProviderUserKey; - if (key == null) return; + var key = _memberUserKeyProvider.GetMemberProviderUserKey(); + if (key is null) return; } // remember when we cache the content @@ -364,8 +373,6 @@ namespace Umbraco.Web.Macros return attributeValue; } - var context = _httpContextAccessor.HttpContext; - foreach (var token in tokens) { var isToken = token.Length > 4 && token[0] == '[' && token[token.Length - 1] == ']' && validTypes.Contains(token[1]); @@ -383,10 +390,10 @@ namespace Umbraco.Web.Macros switch (type) { case '@': - attributeValue = context?.Request[name]; + attributeValue = _requestAccessor.GetRequestValue(name); break; case '%': - attributeValue = context?.Session[name]?.ToString(); + attributeValue = _sessionManager.GetSessionValue(name)?.ToString(); if (string.IsNullOrEmpty(attributeValue)) attributeValue = _cookieManager.GetCookieValue(name); break; diff --git a/src/Umbraco.Web/Macros/MemberUserKeyProvider.cs b/src/Umbraco.Web/Macros/MemberUserKeyProvider.cs new file mode 100644 index 0000000000..cb57943bad --- /dev/null +++ b/src/Umbraco.Web/Macros/MemberUserKeyProvider.cs @@ -0,0 +1,17 @@ +using Umbraco.Core.Security; +using Umbraco.Web.Security; + +namespace Umbraco.Web.Macros +{ + internal class MemberUserKeyProvider : IMemberUserKeyProvider + { + public object GetMemberProviderUserKey() + { + //ugh, membershipproviders :( + var provider = MembershipProviderExtensions.GetMembersMembershipProvider(); + var member = MembershipProviderExtensions.GetCurrentUser(provider); + + return member?.ProviderUserKey; + } + } +} diff --git a/src/Umbraco.Web/Runtime/WebInitialComposer.cs b/src/Umbraco.Web/Runtime/WebInitialComposer.cs index 35aae084de..420e4b5daa 100644 --- a/src/Umbraco.Web/Runtime/WebInitialComposer.cs +++ b/src/Umbraco.Web/Runtime/WebInitialComposer.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Web; using System.Web.Security; using Examine; using Microsoft.AspNet.SignalR; @@ -7,13 +6,11 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Cookie; -using Umbraco.Core.Dashboards; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; using Umbraco.Core.Hosting; using Umbraco.Core.Install; using Umbraco.Core.Migrations.PostMigrations; -using Umbraco.Core.Models.Identity; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors.ValueConverters; using Umbraco.Core.Runtime; @@ -49,6 +46,9 @@ using Current = Umbraco.Web.Composing.Current; using Umbraco.Web.PropertyEditors; using Umbraco.Examine; using Umbraco.Core.Models; +using Umbraco.Core.Request; +using Umbraco.Core.Session; +using Umbraco.Web.AspNet; using Umbraco.Web.Models; namespace Umbraco.Web.Runtime @@ -64,7 +64,14 @@ namespace Umbraco.Web.Runtime composition.Register(); composition.Register(); - composition.Register(); + + + composition.Register(Lifetime.Singleton); + composition.Register(factory => factory.GetInstance(), Lifetime.Singleton); + composition.Register(factory => factory.GetInstance(), Lifetime.Singleton); + + composition.Register(); + composition.Register(); composition.Register(); composition.Register(); @@ -73,6 +80,7 @@ namespace Umbraco.Web.Runtime composition.RegisterUnique(); // required for hybrid accessors composition.RegisterUnique(); + composition.ComposeWebMappingProfiles(); //register the install components @@ -85,6 +93,8 @@ namespace Umbraco.Web.Runtime composition.Register(factory => Roles.Enabled ? Roles.Provider : new MembersRoleProvider(factory.GetInstance())); composition.Register(Lifetime.Request); composition.Register(factory => factory.GetInstance().PublishedSnapshot.Members); + composition.RegisterUnique(); + composition.RegisterUnique(); // register accessors for cultures composition.RegisterUnique(); @@ -115,6 +125,7 @@ namespace Umbraco.Web.Runtime composition.RegisterUnique(); composition.RegisterUnique(); + composition.RegisterUnique(); composition.RegisterUnique(); @@ -125,6 +136,7 @@ namespace Umbraco.Web.Runtime // register the umbraco helper - this is Transient! very important! // also, if not level.Run, we cannot really use the helper (during upgrade...) // so inject a "void" helper (not exactly pretty but...) + if (composition.RuntimeState.Level == RuntimeLevel.Run) if (composition.RuntimeState.Level == RuntimeLevel.Run) composition.Register(factory => { diff --git a/src/Umbraco.Web/Security/PublicAccessChecker.cs b/src/Umbraco.Web/Security/PublicAccessChecker.cs new file mode 100644 index 0000000000..1ea22586e5 --- /dev/null +++ b/src/Umbraco.Web/Security/PublicAccessChecker.cs @@ -0,0 +1,54 @@ +using System; +using Umbraco.Core; +using Umbraco.Core.Services; + +namespace Umbraco.Web.Security +{ + public class PublicAccessChecker : IPublicAccessChecker + { + //TODO: This is lazy to avoid circular dependency. We don't care right now because all membership is going to be changed. + private readonly Lazy _membershipHelper; + private readonly IPublicAccessService _publicAccessService; + private readonly IContentService _contentService; + + public PublicAccessChecker(Lazy membershipHelper, IPublicAccessService publicAccessService, IContentService contentService) + { + _membershipHelper = membershipHelper; + _publicAccessService = publicAccessService; + _contentService = contentService; + } + + public PublicAccessStatus HasMemberAccessToContent(int publishedContentId) + { + var membershipHelper = _membershipHelper.Value; + + if (membershipHelper.IsLoggedIn() == false) + { + return PublicAccessStatus.NotLoggedIn; + } + + var username = membershipHelper.CurrentUserName; + var userRoles = membershipHelper.GetCurrentUserRoles(); + + if (_publicAccessService.HasAccess(publishedContentId, _contentService, username, userRoles) == false) + { + return PublicAccessStatus.AccessDenied; + } + + var member = membershipHelper.GetCurrentMember(); + + if (member.HasProperty(Constants.Conventions.Member.IsApproved) == false) + { + return PublicAccessStatus.NotApproved; + } + + if (member.HasProperty(Constants.Conventions.Member.IsLockedOut) && + member.Value(Constants.Conventions.Member.IsApproved)) + { + return PublicAccessStatus.LockedOut; + } + + return PublicAccessStatus.AccessAccepted; + } + } +} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 27f372753a..8c06da4894 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -134,6 +134,8 @@ + + @@ -166,6 +168,8 @@ + + @@ -185,7 +189,6 @@ - @@ -200,6 +203,7 @@ + @@ -214,7 +218,6 @@ - @@ -274,7 +277,6 @@ - @@ -323,7 +325,6 @@ - @@ -529,8 +530,6 @@ - - @@ -556,7 +555,6 @@ - Code diff --git a/src/Umbraco.Web/UmbracoApplicationBase.cs b/src/Umbraco.Web/UmbracoApplicationBase.cs index 12925604db..1111d028f8 100644 --- a/src/Umbraco.Web/UmbracoApplicationBase.cs +++ b/src/Umbraco.Web/UmbracoApplicationBase.cs @@ -11,6 +11,7 @@ using Umbraco.Core.Hosting; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Logging.Serilog; +using Umbraco.Web.AspNet; using Umbraco.Web.Hosting; using Current = Umbraco.Web.Composing.Current; @@ -39,7 +40,7 @@ namespace Umbraco.Web var ioHelper = new IOHelper(hostingEnvironment); var configs = configFactory.Create(ioHelper); - var logger = SerilogLogger.CreateWithDefaultConfiguration(hostingEnvironment, new AspNetSessionIdResolver(), () => _factory?.GetInstance(), coreDebug, ioHelper, new FrameworkMarchal()); + var logger = SerilogLogger.CreateWithDefaultConfiguration(hostingEnvironment, new AspNetSessionManager(), () => _factory?.GetInstance(), coreDebug, ioHelper, new FrameworkMarchal()); var backOfficeInfo = new AspNetBackOfficeInfo(configs.Global(), ioHelper, configs.Settings(), logger); var profiler = new LogProfiler(logger); Umbraco.Composing.Current.Initialize(logger, configs, ioHelper, hostingEnvironment, backOfficeInfo, profiler); From e9f703436517d44edcb8cdd9c024209026206a81 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Tue, 3 Mar 2020 07:29:51 +0100 Subject: [PATCH 02/10] Moved compoenents and composers --- src/Umbraco.Core/Request/IRequestAccessor.cs | 5 + .../Sync/IBatchedDatabaseServerMessenger.cs | 4 +- .../Sync/IDatabaseServerMessenger.cs | 7 + .../UmbracoApiControllerTypeCollection.cs | 0 .../BatchedDatabaseServerMessenger.cs | 25 +- ...aseServerRegistrarAndMessengerComponent.cs | 27 ++- .../Scheduling/SchedulerComponent.cs | 8 +- .../Scheduling/SchedulerComposer.cs | 0 .../Sync/DatabaseServerMessenger.cs | 6 +- .../Sync/ServerMessengerBase.cs | 1 - .../Cache/DeepCloneAppCacheTests.cs | 8 +- .../Cache/WebCachingAppCacheTests.cs | 55 ----- src/Umbraco.Tests/Umbraco.Tests.csproj | 1 - .../AspNet/AspNetRequestAccessor.cs | 19 ++ src/Umbraco.Web/Cache/WebCachingAppCache.cs | 213 ------------------ src/Umbraco.Web/HtmlHelperRenderExtensions.cs | 2 +- src/Umbraco.Web/Macros/MacroRenderer.cs | 5 +- .../Models/Identity/BackOfficeIdentityUser.cs | 1 - src/Umbraco.Web/Models/LoginStatusModel.cs | 23 +- .../Models/Mapping/CommonTreeNodeMapper.cs | 13 +- .../Models/Mapping/MemberMapDefinition.cs | 3 +- src/Umbraco.Web/Models/ProfileModel.cs | 5 +- src/Umbraco.Web/Models/RegisterModel.cs | 15 +- .../Mvc/MemberAuthorizeAttribute.cs | 4 +- src/Umbraco.Web/Runtime/WebInitialComposer.cs | 2 +- src/Umbraco.Web/Runtime/WebRuntime.cs | 5 +- src/Umbraco.Web/Security/EmailService.cs | 5 +- .../Security/SessionIdValidator.cs | 2 +- src/Umbraco.Web/Templates/TemplateRenderer.cs | 10 +- src/Umbraco.Web/Umbraco.Web.csproj | 6 - .../WebApi/MemberAuthorizeAttribute.cs | 2 +- 31 files changed, 105 insertions(+), 377 deletions(-) create mode 100644 src/Umbraco.Core/Sync/IDatabaseServerMessenger.cs rename src/{Umbraco.Web/WebApi => Umbraco.Core}/UmbracoApiControllerTypeCollection.cs (100%) rename src/{Umbraco.Web => Umbraco.Infrastructure}/BatchedDatabaseServerMessenger.cs (87%) rename src/{Umbraco.Web => Umbraco.Infrastructure}/Compose/DatabaseServerRegistrarAndMessengerComponent.cs (91%) rename src/{Umbraco.Web => Umbraco.Infrastructure}/Scheduling/SchedulerComponent.cs (96%) rename src/{Umbraco.Web => Umbraco.Infrastructure}/Scheduling/SchedulerComposer.cs (100%) delete mode 100644 src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs delete mode 100644 src/Umbraco.Web/Cache/WebCachingAppCache.cs diff --git a/src/Umbraco.Core/Request/IRequestAccessor.cs b/src/Umbraco.Core/Request/IRequestAccessor.cs index 52d532de26..63a8de6b1e 100644 --- a/src/Umbraco.Core/Request/IRequestAccessor.cs +++ b/src/Umbraco.Core/Request/IRequestAccessor.cs @@ -1,8 +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.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.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.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..2008737d33 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,6 @@ namespace Umbraco.Web.Scheduling { case EnsureRoutableOutcome.IsRoutable: case EnsureRoutableOutcome.NotDocumentRequest: - UmbracoModule.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.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/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.Web/AspNet/AspNetRequestAccessor.cs b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs index d2675b0dc1..72bde75dc8 100644 --- a/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs +++ b/src/Umbraco.Web/AspNet/AspNetRequestAccessor.cs @@ -1,4 +1,6 @@ +using System; using Umbraco.Core.Request; +using Umbraco.Web.Routing; namespace Umbraco.Web.AspNet { @@ -9,8 +11,13 @@ namespace Umbraco.Web.AspNet public AspNetRequestAccessor(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; + + UmbracoModule.EndRequest += OnEndRequest; + UmbracoModule.RouteAttempt += OnRouteAttempt; } + + public string GetRequestValue(string name) { return _httpContextAccessor.GetRequiredHttpContext().Request[name]; @@ -20,5 +27,17 @@ namespace Umbraco.Web.AspNet { return _httpContextAccessor.GetRequiredHttpContext().Request.QueryString[name]; } + + private void OnEndRequest(object sender, UmbracoRequestEventArgs args) + { + EndRequest?.Invoke(sender, args); + } + + private void OnRouteAttempt(object sender, RoutableAttemptEventArgs args) + { + RouteAttempt?.Invoke(sender, args); + } + public event EventHandler EndRequest; + public event EventHandler RouteAttempt; } } diff --git a/src/Umbraco.Web/Cache/WebCachingAppCache.cs b/src/Umbraco.Web/Cache/WebCachingAppCache.cs deleted file mode 100644 index 087d393d3c..0000000000 --- a/src/Umbraco.Web/Cache/WebCachingAppCache.cs +++ /dev/null @@ -1,213 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Web.Caching; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Composing; - -namespace Umbraco.Web.Cache -{ - /// - /// Implements on top of a . - /// - /// The underlying cache is expected to be HttpRuntime.Cache. - internal class WebCachingAppCache : FastDictionaryAppCacheBase, IAppPolicyCache - { - // locker object that supports upgradeable read locking - // does not need to support recursion if we implement the cache correctly and ensure - // that methods cannot be reentrant, ie we do NOT create values while holding a lock. - private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); - - private readonly System.Web.Caching.Cache _cache; - - /// - /// Initializes a new instance of the class. - /// - public WebCachingAppCache(System.Web.Caching.Cache cache, ITypeFinder typeFinder) : base(typeFinder) - { - _cache = cache; - } - - /// - public override object Get(string key, Func factory) - { - return Get(key, factory, null, dependentFiles: null); - } - - /// - public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - return GetImpl(key, factory, timeout, isSliding, dependency); - } - - /// - public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - InsertImpl(key, factory, timeout, isSliding, dependency); - } - - #region Dictionary - - protected override IEnumerable GetDictionaryEntries() - { - const string prefix = CacheItemPrefix + "-"; - return _cache.Cast() - .Where(x => x.Key is string && ((string)x.Key).StartsWith(prefix)); - } - - protected override void RemoveEntry(string key) - { - _cache.Remove(key); - } - - protected override object GetEntry(string key) - { - return _cache.Get(key); - } - - #endregion - - #region Lock - - protected override void EnterReadLock() - { - _locker.EnterReadLock(); - } - - protected override void EnterWriteLock() - { - _locker.EnterWriteLock(); - } - - protected override void ExitReadLock() - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - - protected override void ExitWriteLock() - { - if (_locker.IsWriteLockHeld) - _locker.ExitWriteLock(); - } - - #endregion - - private object GetImpl(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheDependency dependency = null) - { - key = GetCacheKey(key); - - // NOTE - because we don't know what getCacheItem does, how long it will take and whether it will hang, - // getCacheItem should run OUTSIDE of the global application lock else we run into lock contention and - // nasty performance issues. - - // So.... we insert a Lazy in the cache while holding the global application lock, and then rely - // on the Lazy lock to ensure that getCacheItem runs once and everybody waits on it, while the global - // application lock has been released. - - // NOTE - // The Lazy value creation may produce a null value. - // Must make sure (for backward compatibility) that we pretend they are not in the cache. - // So if we find an entry in the cache that already has its value created and is null, - // pretend it was not there. If value is not already created, wait... and return null, that's - // what prior code did. - - // NOTE - // The Lazy value creation may throw. - - // So... the null value _will_ be in the cache but never returned - - Lazy result; - - // Fast! - // Only one thread can enter an UpgradeableReadLock at a time, but it does not prevent other - // threads to enter a ReadLock in the meantime -- only upgrading to WriteLock will prevent all - // reads. We first try with a normal ReadLock for maximum concurrency and take the penalty of - // having to re-lock in case there's no value. Would need to benchmark to figure out whether - // it's worth it, though... - try - { - _locker.EnterReadLock(); - result = _cache.Get(key) as Lazy; // null if key not found - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - var value = result == null ? null : SafeLazy.GetSafeLazyValue(result); - if (value != null) return value; - - using (var lck = new UpgradeableReadLock(_locker)) - { - result = _cache.Get(key) as Lazy; // null if key not found - - // cannot create value within the lock, so if result.IsValueCreated is false, just - // do nothing here - means that if creation throws, a race condition could cause - // more than one thread to reach the return statement below and throw - accepted. - - if (result == null || SafeLazy.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null - { - result = SafeLazy.GetSafeLazy(factory); - var absolute = isSliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : (timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value)); - var sliding = isSliding == false ? System.Web.Caching.Cache.NoSlidingExpiration : (timeout ?? System.Web.Caching.Cache.NoSlidingExpiration); - - lck.UpgradeToWriteLock(); - //NOTE: 'Insert' on System.Web.Caching.Cache actually does an add or update! - _cache.Insert(key, result, dependency, absolute, sliding, CacheItemPriority.Normal, null); - } - } - - // using GetSafeLazy and GetSafeLazyValue ensures that we don't cache - // exceptions (but try again and again) and silently eat them - however at - // some point we have to report them - so need to re-throw here - - // this does not throw anymore - //return result.Value; - - value = result.Value; // will not throw (safe lazy) - if (value is SafeLazy.ExceptionHolder eh) eh.Exception.Throw(); // throw once! - return value; - } - - private void InsertImpl(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheDependency dependency = null) - { - // NOTE - here also we must insert a Lazy but we can evaluate it right now - // and make sure we don't store a null value. - - var result = SafeLazy.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache - if (value == null) return; // do not store null values (backward compat) - - cacheKey = GetCacheKey(cacheKey); - - var absolute = isSliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : (timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value)); - var sliding = isSliding == false ? System.Web.Caching.Cache.NoSlidingExpiration : (timeout ?? System.Web.Caching.Cache.NoSlidingExpiration); - - try - { - _locker.EnterWriteLock(); - //NOTE: 'Insert' on System.Web.Caching.Cache actually does an add or update! - _cache.Insert(cacheKey, result, dependency, absolute, sliding, CacheItemPriority.Normal, null); - } - finally - { - if (_locker.IsWriteLockHeld) - _locker.ExitWriteLock(); - } - } - } -} diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index 796a3a0c4a..f8b121f60c 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -96,7 +96,7 @@ namespace Umbraco.Web } if (cacheByMember) { - var helper = Current.Factory.GetInstance(); + var helper = Current.MembershipHelper; var currentMember = helper.GetCurrentMember(); cacheKey.AppendFormat("m{0}-", currentMember?.Id ?? 0); } diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index 462748fae0..253013d8c4 100644 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -32,6 +32,7 @@ namespace Umbraco.Web.Macros private readonly IMemberUserKeyProvider _memberUserKeyProvider; private readonly ISessionManager _sessionManager; private readonly IRequestAccessor _requestAccessor; + private readonly IHttpContextAccessor _httpContextAccessor; public MacroRenderer( @@ -45,7 +46,8 @@ namespace Umbraco.Web.Macros ICookieManager cookieManager, IMemberUserKeyProvider memberUserKeyProvider, ISessionManager sessionManager, - IRequestAccessor requestAccessor) + IRequestAccessor requestAccessor, + IHttpContextAccessor httpContextAccessor) { _plogger = plogger ?? throw new ArgumentNullException(nameof(plogger)); _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); @@ -58,6 +60,7 @@ namespace Umbraco.Web.Macros _memberUserKeyProvider = memberUserKeyProvider; _sessionManager = sessionManager; _requestAccessor = requestAccessor; + _httpContextAccessor = httpContextAccessor; } #region MacroContent cache diff --git a/src/Umbraco.Web/Models/Identity/BackOfficeIdentityUser.cs b/src/Umbraco.Web/Models/Identity/BackOfficeIdentityUser.cs index 8f77de67f2..21c965aa3d 100644 --- a/src/Umbraco.Web/Models/Identity/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Web/Models/Identity/BackOfficeIdentityUser.cs @@ -5,7 +5,6 @@ using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Umbraco.Core; -using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Identity; diff --git a/src/Umbraco.Web/Models/LoginStatusModel.cs b/src/Umbraco.Web/Models/LoginStatusModel.cs index e20c7f0a0b..4b699bab38 100644 --- a/src/Umbraco.Web/Models/LoginStatusModel.cs +++ b/src/Umbraco.Web/Models/LoginStatusModel.cs @@ -1,7 +1,5 @@ using System.ComponentModel.DataAnnotations; -using Umbraco.Core; -using Umbraco.Web.Security; -using Current = Umbraco.Web.Composing.Current; + namespace Umbraco.Web.Models { @@ -16,26 +14,9 @@ namespace Umbraco.Web.Models /// public static LoginStatusModel CreateModel() { - return new LoginStatusModel(false); + return new LoginStatusModel(); } - private LoginStatusModel(bool doLookup) - { - if (doLookup && Current.UmbracoContext != null) - { - var helper = Current.Factory.GetInstance(); - var model = helper.GetCurrentLoginStatus(); - if (model != null) - { - Name = model.Name; - Username = model.Username; - Email = model.Email; - IsLoggedIn = true; - } - } - } - - /// /// The name of the member /// diff --git a/src/Umbraco.Web/Models/Mapping/CommonTreeNodeMapper.cs b/src/Umbraco.Web/Models/Mapping/CommonTreeNodeMapper.cs index d1d0857abb..aed779683f 100644 --- a/src/Umbraco.Web/Models/Mapping/CommonTreeNodeMapper.cs +++ b/src/Umbraco.Web/Models/Mapping/CommonTreeNodeMapper.cs @@ -1,18 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Mvc; -using Umbraco.Core; -using Umbraco.Core.Mapping; +using System.Web.Mvc; using Umbraco.Core.Models; -using Umbraco.Core.Models.ContentEditing; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Services; -using Umbraco.Web.ContentApps; -using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; -using UserProfile = Umbraco.Web.Models.ContentEditing.UserProfile; namespace Umbraco.Web.Models.Mapping { diff --git a/src/Umbraco.Web/Models/Mapping/MemberMapDefinition.cs b/src/Umbraco.Web/Models/Mapping/MemberMapDefinition.cs index 6e16dd2d71..5fc443f692 100644 --- a/src/Umbraco.Web/Models/Mapping/MemberMapDefinition.cs +++ b/src/Umbraco.Web/Models/Mapping/MemberMapDefinition.cs @@ -1,5 +1,4 @@ -using System.Web.Mvc; -using Umbraco.Core; +using Umbraco.Core; using Umbraco.Core.Mapping; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; diff --git a/src/Umbraco.Web/Models/ProfileModel.cs b/src/Umbraco.Web/Models/ProfileModel.cs index 7b7b0ecb4a..0397f34849 100644 --- a/src/Umbraco.Web/Models/ProfileModel.cs +++ b/src/Umbraco.Web/Models/ProfileModel.cs @@ -3,9 +3,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; -using Umbraco.Web.Security; -using Umbraco.Core; -using Umbraco.Core.Composing; using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Web.Models @@ -28,7 +25,7 @@ namespace Umbraco.Web.Models MemberProperties = new List(); if (doLookup && Current.UmbracoContext != null) { - var helper = Current.Factory.GetInstance(); + var helper = Current.MembershipHelper; var model = helper.GetCurrentMemberProfileModel(); MemberProperties = model.MemberProperties; } diff --git a/src/Umbraco.Web/Models/RegisterModel.cs b/src/Umbraco.Web/Models/RegisterModel.cs index 41edea19de..1ee9307969 100644 --- a/src/Umbraco.Web/Models/RegisterModel.cs +++ b/src/Umbraco.Web/Models/RegisterModel.cs @@ -1,13 +1,8 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.ComponentModel.DataAnnotations; -using System.Web; using System.Web.Mvc; using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Web.Security; -using Current = Umbraco.Web.Composing.Current; namespace Umbraco.Web.Models { @@ -20,22 +15,16 @@ namespace Umbraco.Web.Models /// public static RegisterModel CreateModel() { - return new RegisterModel(false); + return new RegisterModel(); } - private RegisterModel(bool doLookup) + private RegisterModel() { MemberTypeAlias = Constants.Conventions.MemberTypes.DefaultAlias; UsernameIsEmail = true; MemberProperties = new List(); LoginOnSuccess = true; CreatePersistentLoginCookie = true; - if (doLookup && Current.UmbracoContext != null) - { - var helper = Current.Factory.GetInstance(); - var model = helper.CreateRegistrationModel(MemberTypeAlias); - MemberProperties = model.MemberProperties; - } } diff --git a/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs index 5f81ced3f0..a99e8c1df6 100644 --- a/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs @@ -48,9 +48,9 @@ namespace Umbraco.Web.Mvc } } - var helper = Current.Factory.GetInstance(); + var helper = Current.MembershipHelper; return helper.IsMemberAuthorized(AllowType.Split(','), AllowGroup.Split(','), members); - + } /// diff --git a/src/Umbraco.Web/Runtime/WebInitialComposer.cs b/src/Umbraco.Web/Runtime/WebInitialComposer.cs index 345d847365..632cb5a6b6 100644 --- a/src/Umbraco.Web/Runtime/WebInitialComposer.cs +++ b/src/Umbraco.Web/Runtime/WebInitialComposer.cs @@ -71,7 +71,7 @@ namespace Umbraco.Web.Runtime composition.Register(factory => factory.GetInstance(), Lifetime.Singleton); composition.Register(factory => factory.GetInstance(), Lifetime.Singleton); - composition.Register(); + composition.Register(Lifetime.Singleton); composition.Register(); composition.Register(); diff --git a/src/Umbraco.Web/Runtime/WebRuntime.cs b/src/Umbraco.Web/Runtime/WebRuntime.cs index 0fc35af2f2..7d268a7c42 100644 --- a/src/Umbraco.Web/Runtime/WebRuntime.cs +++ b/src/Umbraco.Web/Runtime/WebRuntime.cs @@ -22,7 +22,6 @@ namespace Umbraco.Web.Runtime /// On top of CoreRuntime, handles all of the web-related runtime aspects of Umbraco. public class WebRuntime : CoreRuntime { - private readonly UmbracoApplicationBase _umbracoApplication; private BuildManagerTypeFinder _typeFinder; /// @@ -42,8 +41,6 @@ namespace Umbraco.Web.Runtime IMainDom mainDom): base(configs, umbracoVersion, ioHelper, logger, profiler ,new AspNetUmbracoBootPermissionChecker(), hostingEnvironment, backOfficeInfo, dbProviderFactoryCreator, mainDom) { - _umbracoApplication = umbracoApplication; - Profiler = GetWebProfiler(); } @@ -102,7 +99,7 @@ namespace Umbraco.Web.Runtime protected override AppCaches GetAppCaches() => new AppCaches( // we need to have the dep clone runtime cache provider to ensure // all entities are cached properly (cloned in and cloned out) - new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache, TypeFinder)), + new DeepCloneAppCache(new ObjectCacheAppCache(TypeFinder)), // we need request based cache when running in web-based context new HttpRequestAppCache(() => HttpContext.Current?.Items, TypeFinder), new IsolatedCaches(type => diff --git a/src/Umbraco.Web/Security/EmailService.cs b/src/Umbraco.Web/Security/EmailService.cs index e6454544ab..aabd5a1ead 100644 --- a/src/Umbraco.Web/Security/EmailService.cs +++ b/src/Umbraco.Web/Security/EmailService.cs @@ -1,9 +1,6 @@ -using System; -using System.ComponentModel; -using System.Net.Mail; +using System.Net.Mail; using System.Threading.Tasks; using Microsoft.AspNet.Identity; -using Umbraco.Core.Configuration; namespace Umbraco.Core.Security { diff --git a/src/Umbraco.Web/Security/SessionIdValidator.cs b/src/Umbraco.Web/Security/SessionIdValidator.cs index 8f6782aac2..11fb28c197 100644 --- a/src/Umbraco.Web/Security/SessionIdValidator.cs +++ b/src/Umbraco.Web/Security/SessionIdValidator.cs @@ -10,7 +10,7 @@ using Microsoft.Owin.Security.Cookies; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; -using Umbraco.Core.Security; + using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Security diff --git a/src/Umbraco.Web/Templates/TemplateRenderer.cs b/src/Umbraco.Web/Templates/TemplateRenderer.cs index ac08258ee2..8cf310d7ee 100644 --- a/src/Umbraco.Web/Templates/TemplateRenderer.cs +++ b/src/Umbraco.Web/Templates/TemplateRenderer.cs @@ -2,16 +2,15 @@ using System; using System.Globalization; using System.IO; using System.Linq; -using System.Web; using System.Web.Mvc; using System.Web.Routing; +using Umbraco.Core; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Umbraco.Web.Routing; -using Umbraco.Core.Strings; namespace Umbraco.Web.Templates { @@ -46,10 +45,11 @@ namespace Umbraco.Web.Templates { if (writer == null) throw new ArgumentNullException(nameof(writer)); + var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // instantiate a request and process // important to use CleanedUmbracoUrl - lowercase path-only version of the current url, though this isn't going to matter // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually. - var contentRequest = _publishedRouter.CreateRequest(_umbracoContextAccessor.UmbracoContext); + var contentRequest = _publishedRouter.CreateRequest(umbracoContext); var doc = contentRequest.UmbracoContext.Content.GetById(pageId); @@ -62,7 +62,7 @@ namespace Umbraco.Web.Templates //in some cases the UmbracoContext will not have a PublishedRequest assigned to it if we are not in the //execution of a front-end rendered page. In this case set the culture to the default. //set the culture to the same as is currently rendering - if (_umbracoContextAccessor.UmbracoContext.PublishedRequest == null) + if (umbracoContext.PublishedRequest == null) { var defaultLanguage = _languageService.GetAllLanguages().FirstOrDefault(); contentRequest.Culture = defaultLanguage == null @@ -71,7 +71,7 @@ namespace Umbraco.Web.Templates } else { - contentRequest.Culture = _umbracoContextAccessor.UmbracoContext.PublishedRequest.Culture; + contentRequest.Culture = umbracoContext.PublishedRequest.Culture; } //set the doc that was found by id diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index cd0c4152a0..fad79b0296 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -139,7 +139,6 @@ - @@ -192,8 +191,6 @@ - - @@ -307,7 +304,6 @@ - @@ -344,7 +340,6 @@ - @@ -527,7 +522,6 @@ - diff --git a/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs index bc1e9a4318..6d4607cfba 100644 --- a/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs +++ b/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs @@ -46,7 +46,7 @@ namespace Umbraco.Web.WebApi } } - var helper = Current.Factory.GetInstance(); + var helper = Current.MembershipHelper; return helper.IsMemberAuthorized(AllowType.Split(','), AllowGroup.Split(','), members); } From 84f19e093a3b3b7a13b086dcea9effcbd7e1a825 Mon Sep 17 00:00:00 2001 From: Elitsa Marinovska <21998037+elit0451@users.noreply.github.com> Date: Tue, 3 Mar 2020 11:59:17 +0100 Subject: [PATCH 03/10] NetCore: Refactor internal usages of UmbracoHelper (#7744) * Removing properties related to IPublishedContentQuery, ITagQuery, ICultureDictionaryFactory, IUmbracoComponentRenderer from UmbracoHelper and using the corresponding private fields instead. Removing Media related methods * Removed UmbracoHelper from UmbracoApiControllerBase * Removed UmbracoHelper references * Inject the needed Interfaces to classes that previously used UmbracoHelper to get the same functionality * Fixed tests referencing UmbracoHelper * Adding Media methods back * Cleanup and moved UmbracoHelper from more base classes, when not used + simplified tests * Reintroduced some methods.. * Reintroduced some methods.. * Reintroducing last missing bits Co-authored-by: Bjarke Berg --- .../IPublishedContentQuery.cs | 9 + .../PublishedContentQuery.cs | 236 ++++++++----- .../UmbracoTestDataController.cs | 4 +- .../Routing/RenderRouteHandlerTests.cs | 8 +- .../TestControllerActivator.cs | 8 +- .../TestControllerActivatorBase.cs | 10 +- .../ControllerTesting/TestRunner.cs | 4 +- .../ControllerTesting/TestStartup.cs | 4 +- .../Testing/TestingTests/MockTests.cs | 9 +- .../AuthenticationControllerTests.cs | 3 +- .../Web/Controllers/ContentControllerTests.cs | 18 +- .../Controllers/PluginControllerAreaTests.cs | 8 +- .../Web/Controllers/UsersControllerTests.cs | 12 +- .../Web/Mvc/SurfaceControllerTests.cs | 26 +- src/Umbraco.Tests/Web/UmbracoHelperTests.cs | 228 ------------ .../Templates/Gallery.cshtml | 2 +- .../ListChildPagesFromChangeableSource.cshtml | 3 +- .../ListImagesFromMediaFolder.cshtml | 3 +- src/Umbraco.Web/Composing/Current.cs | 4 + .../Controllers/UmbLoginController.cs | 4 +- .../Controllers/UmbLoginStatusController.cs | 4 +- .../Controllers/UmbProfileController.cs | 4 +- .../Controllers/UmbRegisterController.cs | 4 +- .../Editors/AuthenticationController.cs | 3 +- .../Editors/BackOfficeController.cs | 3 +- .../BackOfficeNotificationsController.cs | 3 +- src/Umbraco.Web/Editors/CodeFileController.cs | 3 +- src/Umbraco.Web/Editors/ContentController.cs | 3 +- .../Editors/ContentControllerBase.cs | 3 +- .../Editors/ContentTypeController.cs | 3 +- .../Editors/ContentTypeControllerBase.cs | 3 +- .../Editors/CurrentUserController.cs | 3 +- .../Editors/DashboardController.cs | 3 +- src/Umbraco.Web/Editors/DataTypeController.cs | 3 +- .../Editors/DictionaryController.cs | 3 +- src/Umbraco.Web/Editors/EntityController.cs | 23 +- src/Umbraco.Web/Editors/LogController.cs | 3 +- .../Editors/MacroRenderingController.cs | 2 - src/Umbraco.Web/Editors/MacrosController.cs | 3 +- src/Umbraco.Web/Editors/MediaController.cs | 3 +- .../Editors/MediaTypeController.cs | 3 +- src/Umbraco.Web/Editors/MemberController.cs | 3 +- .../Editors/MemberTypeController.cs | 3 +- src/Umbraco.Web/Editors/PackageController.cs | 3 +- .../Editors/PackageInstallController.cs | 3 +- .../Editors/RelationTypeController.cs | 3 +- src/Umbraco.Web/Editors/SectionController.cs | 6 +- src/Umbraco.Web/Editors/TemplateController.cs | 3 +- .../Editors/TemplateQueryController.cs | 14 +- src/Umbraco.Web/Editors/TinyMceController.cs | 3 +- src/Umbraco.Web/Editors/TourController.cs | 3 +- .../UmbracoAuthorizedJsonController.cs | 3 +- src/Umbraco.Web/Editors/UsersController.cs | 3 +- .../EnsurePublishedContentRequestAttribute.cs | 9 +- src/Umbraco.Web/Mvc/PluginController.cs | 6 +- src/Umbraco.Web/Mvc/RenderMvcController.cs | 4 +- src/Umbraco.Web/Mvc/SurfaceController.cs | 4 +- .../Mvc/UmbracoAuthorizedController.cs | 4 +- src/Umbraco.Web/Mvc/UmbracoController.cs | 6 +- .../Profiling/WebProfilingController.cs | 3 +- .../RichTextPreValueController.cs | 3 +- .../PropertyEditors/TagsDataController.cs | 13 +- src/Umbraco.Web/Runtime/WebInitialComposer.cs | 3 +- .../Trees/ApplicationTreeController.cs | 4 +- .../Trees/ContentBlueprintTreeController.cs | 3 +- .../Trees/ContentTreeController.cs | 3 +- .../Trees/ContentTreeControllerBase.cs | 3 +- .../Trees/ContentTypeTreeController.cs | 3 +- .../Trees/DataTypeTreeController.cs | 3 +- .../Trees/DictionaryTreeController.cs | 3 +- .../Trees/FileSystemTreeController.cs | 3 +- src/Umbraco.Web/Trees/MacrosTreeController.cs | 3 +- src/Umbraco.Web/Trees/MediaTreeController.cs | 3 +- .../Trees/MediaTypeTreeController.cs | 3 +- src/Umbraco.Web/Trees/MemberTreeController.cs | 3 +- .../MemberTypeAndGroupTreeControllerBase.cs | 3 +- .../Trees/PackagesTreeController.cs | 3 +- .../Trees/RelationTypeTreeController.cs | 3 +- .../Trees/TemplatesTreeController.cs | 3 +- src/Umbraco.Web/Trees/TreeController.cs | 3 +- src/Umbraco.Web/Trees/TreeControllerBase.cs | 3 +- src/Umbraco.Web/Trees/UserTreeController.cs | 3 +- src/Umbraco.Web/UmbracoHelper.cs | 329 +++--------------- src/Umbraco.Web/UmbracoHttpHandler.cs | 10 +- src/Umbraco.Web/UmbracoWebService.cs | 10 +- .../WebApi/UmbracoApiController.cs | 4 +- .../WebApi/UmbracoApiControllerBase.cs | 9 +- .../WebApi/UmbracoAuthorizedApiController.cs | 4 +- 88 files changed, 376 insertions(+), 841 deletions(-) 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/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.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/Routing/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index 5b66d90722..80147256ad 100644 --- a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs +++ b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs @@ -144,7 +144,6 @@ namespace Umbraco.Tests.Routing 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); @@ -160,8 +159,7 @@ namespace Umbraco.Tests.Routing 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 +196,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/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/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/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 47c36177fe..a431be4998 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -116,6 +116,9 @@ namespace Umbraco.Web.Composing public static UmbracoHelper UmbracoHelper => Factory.GetInstance(); + public static IUmbracoComponentRenderer UmbracoComponentRenderer + => Factory.GetInstance(); + public static DistributedCache DistributedCache => Factory.GetInstance(); @@ -265,6 +268,7 @@ namespace Umbraco.Web.Composing public static IMenuItemCollectionFactory MenuItemCollectionFactory => Factory.GetInstance(); public static MembershipHelper MembershipHelper => Factory.GetInstance(); public static IUmbracoApplicationLifetime UmbracoApplicationLifetime => Factory.GetInstance(); + public static IPublishedContentQuery PublishedContentQuery => Factory.GetInstance(); #endregion } diff --git a/src/Umbraco.Web/Controllers/UmbLoginController.cs b/src/Umbraco.Web/Controllers/UmbLoginController.cs index dc77d3485b..cd0489433c 100644 --- a/src/Umbraco.Web/Controllers/UmbLoginController.cs +++ b/src/Umbraco.Web/Controllers/UmbLoginController.cs @@ -19,9 +19,9 @@ namespace Umbraco.Web.Controllers } public UmbLoginController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, - ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper, + ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, MembershipHelper membershipHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { _membershipHelper = membershipHelper; } diff --git a/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs b/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs index aed60af168..825dd1e904 100644 --- a/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs +++ b/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs @@ -22,8 +22,8 @@ namespace Umbraco.Web.Controllers public UmbLoginStatusController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, - IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper, MembershipHelper membershipHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + IProfilingLogger profilingLogger, MembershipHelper membershipHelper) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { _membershipHelper = membershipHelper; } diff --git a/src/Umbraco.Web/Controllers/UmbProfileController.cs b/src/Umbraco.Web/Controllers/UmbProfileController.cs index b736a3fcc7..c5a37e7629 100644 --- a/src/Umbraco.Web/Controllers/UmbProfileController.cs +++ b/src/Umbraco.Web/Controllers/UmbProfileController.cs @@ -22,8 +22,8 @@ namespace Umbraco.Web.Controllers public UmbProfileController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, - UmbracoHelper umbracoHelper, MembershipHelper membershipHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + MembershipHelper membershipHelper) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { _membershipHelper = membershipHelper; } diff --git a/src/Umbraco.Web/Controllers/UmbRegisterController.cs b/src/Umbraco.Web/Controllers/UmbRegisterController.cs index ad5fd0c900..1e83fadda6 100644 --- a/src/Umbraco.Web/Controllers/UmbRegisterController.cs +++ b/src/Umbraco.Web/Controllers/UmbRegisterController.cs @@ -22,8 +22,8 @@ namespace Umbraco.Web.Controllers public UmbRegisterController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, - IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper, MembershipHelper membershipHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + IProfilingLogger profilingLogger, MembershipHelper membershipHelper) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { _membershipHelper = membershipHelper; } diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index dbfb6f81a4..0d206f8d8d 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -57,12 +57,11 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _passwordConfiguration = passwordConfiguration ?? throw new ArgumentNullException(nameof(passwordConfiguration)); _runtimeState = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState)); diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 64cd0d1a0d..1b7482cd59 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -63,7 +63,6 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger profilingLogger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IUmbracoVersion umbracoVersion, IGridConfig gridConfig, IUmbracoSettingsSection umbracoSettingsSection, @@ -71,7 +70,7 @@ namespace Umbraco.Web.Editors TreeCollection treeCollection, IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor) - : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, umbracoHelper) + : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger) { _manifestParser = manifestParser; _features = features; diff --git a/src/Umbraco.Web/Editors/BackOfficeNotificationsController.cs b/src/Umbraco.Web/Editors/BackOfficeNotificationsController.cs index eb6b76ab46..fe9e82c580 100644 --- a/src/Umbraco.Web/Editors/BackOfficeNotificationsController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeNotificationsController.cs @@ -29,11 +29,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { } } diff --git a/src/Umbraco.Web/Editors/CodeFileController.cs b/src/Umbraco.Web/Editors/CodeFileController.cs index f127b0cd14..325b39e4f2 100644 --- a/src/Umbraco.Web/Editors/CodeFileController.cs +++ b/src/Umbraco.Web/Editors/CodeFileController.cs @@ -46,13 +46,12 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IIOHelper ioHelper, IFileSystems fileSystems, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _ioHelper = ioHelper; _fileSystems = fileSystems; diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index 0b63c94ba8..2ea1ec3a24 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -69,11 +69,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors)); _allLangs = new Lazy>(() => Services.LocalizationService.GetAllLanguages().ToDictionary(x => x.IsoCode, x => x, StringComparer.InvariantCultureIgnoreCase)); diff --git a/src/Umbraco.Web/Editors/ContentControllerBase.cs b/src/Umbraco.Web/Editors/ContentControllerBase.cs index 83d5a87323..a7949084b5 100644 --- a/src/Umbraco.Web/Editors/ContentControllerBase.cs +++ b/src/Umbraco.Web/Editors/ContentControllerBase.cs @@ -40,11 +40,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - :base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + :base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { CultureDictionary = cultureDictionary; } diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index fc7189cf6f..506eac6aac 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -63,14 +63,13 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IScopeProvider scopeProvider, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider, EditorValidatorCollection editorValidatorCollection) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) { _serializer = serializer; _globalSettings = globalSettings; diff --git a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs index bca8c28f64..85ead9924d 100644 --- a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs +++ b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs @@ -43,12 +43,11 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, EditorValidatorCollection editorValidatorCollection) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _editorValidatorCollection = editorValidatorCollection; CultureDictionary = cultureDictionary; diff --git a/src/Umbraco.Web/Editors/CurrentUserController.cs b/src/Umbraco.Web/Editors/CurrentUserController.cs index 36f39940cb..85a4f97fb6 100644 --- a/src/Umbraco.Web/Editors/CurrentUserController.cs +++ b/src/Umbraco.Web/Editors/CurrentUserController.cs @@ -46,7 +46,6 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, @@ -54,7 +53,7 @@ namespace Umbraco.Web.Editors IIOHelper ioHelper, IImageUrlGenerator imageUrlGenerator, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _mediaFileSystem = mediaFileSystem; _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); diff --git a/src/Umbraco.Web/Editors/DashboardController.cs b/src/Umbraco.Web/Editors/DashboardController.cs index 8c955b5c29..84aad2d0c0 100644 --- a/src/Umbraco.Web/Editors/DashboardController.cs +++ b/src/Umbraco.Web/Editors/DashboardController.cs @@ -50,12 +50,11 @@ namespace Umbraco.Web.Editors IProfilingLogger logger, IRuntimeState runtimeState, IDashboardService dashboardService, - UmbracoHelper umbracoHelper, IUmbracoVersion umbracoVersion, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper,publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper,publishedUrlProvider) { _dashboardService = dashboardService; _umbracoVersion = umbracoVersion; diff --git a/src/Umbraco.Web/Editors/DataTypeController.cs b/src/Umbraco.Web/Editors/DataTypeController.cs index 835bda19b6..0ab54d9f98 100644 --- a/src/Umbraco.Web/Editors/DataTypeController.cs +++ b/src/Umbraco.Web/Editors/DataTypeController.cs @@ -54,12 +54,11 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IUmbracoSettingsSection umbracoSettingsSection, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _propertyEditors = propertyEditors; _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); diff --git a/src/Umbraco.Web/Editors/DictionaryController.cs b/src/Umbraco.Web/Editors/DictionaryController.cs index 8d835b74b8..56701d35ed 100644 --- a/src/Umbraco.Web/Editors/DictionaryController.cs +++ b/src/Umbraco.Web/Editors/DictionaryController.cs @@ -43,11 +43,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index 0d72e08318..5324bf12ad 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -53,6 +53,7 @@ namespace Umbraco.Web.Editors private readonly ITreeService _treeService; private readonly UmbracoTreeSearcher _treeSearcher; private readonly SearchableTreeCollection _searchableTreeCollection; + private readonly IPublishedContentQuery _publishedContentQuery; public EntityController( IGlobalSettings globalSettings, @@ -63,17 +64,18 @@ namespace Umbraco.Web.Editors IProfilingLogger logger, IRuntimeState runtimeState, ITreeService treeService, - UmbracoHelper umbracoHelper, SearchableTreeCollection searchableTreeCollection, UmbracoTreeSearcher treeSearcher, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, - IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + IPublishedUrlProvider publishedUrlProvider, + IPublishedContentQuery publishedContentQuery) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _treeService = treeService; _searchableTreeCollection = searchableTreeCollection; _treeSearcher = treeSearcher; + _publishedContentQuery = publishedContentQuery; } /// @@ -189,7 +191,7 @@ namespace Umbraco.Web.Editors { var foundContent = GetResultForId(id, type); - return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); + return foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); } /// @@ -233,7 +235,7 @@ namespace Umbraco.Web.Editors if (!intId.Success) throw new HttpResponseException(HttpStatusCode.NotFound); UmbracoEntityTypes entityType; - switch(udi.EntityType) + switch (udi.EntityType) { case Constants.UdiEntityType.Document: entityType = UmbracoEntityTypes.Document; @@ -283,7 +285,8 @@ namespace Umbraco.Web.Editors var ancestors = GetResultForAncestors(id, type); //if content, skip the first node for replicating NiceUrl defaults - if(type == UmbracoEntityTypes.Document) { + if (type == UmbracoEntityTypes.Document) + { ancestors = ancestors.Skip(1); } @@ -313,7 +316,7 @@ namespace Umbraco.Web.Editors var q = ParseXPathQuery(query, nodeContextId); - var node = Umbraco.ContentSingleAtXPath(q); + var node = _publishedContentQuery.ContentSingleAtXPath(q); if (node == null) return null; @@ -332,7 +335,7 @@ namespace Umbraco.Web.Editors var ent = Services.EntityService.Get(nodeid); return ent.Path.Split(',').Reverse(); }, - publishedContentExists: i => Umbraco.Content(i) != null); + publishedContentExists: i => _publishedContentQuery.Content(i) != null); } [HttpGet] @@ -690,7 +693,7 @@ namespace Umbraco.Web.Editors case UmbracoEntityTypes.Media: return Security.CurrentUser.CalculateMediaStartNodeIds(Services.EntityService); default: - return Array.Empty(); + return Array.Empty(); } } @@ -1108,7 +1111,7 @@ namespace Umbraco.Web.Editors case UmbracoEntityTypes.Language: - if (!postFilter.IsNullOrWhiteSpace() ) + if (!postFilter.IsNullOrWhiteSpace()) throw new NotSupportedException("Filtering on languages is not currently supported"); return Services.LocalizationService.GetAllLanguages().Select(MapEntities()); diff --git a/src/Umbraco.Web/Editors/LogController.cs b/src/Umbraco.Web/Editors/LogController.cs index 7bcc0baa01..b502802775 100644 --- a/src/Umbraco.Web/Editors/LogController.cs +++ b/src/Umbraco.Web/Editors/LogController.cs @@ -35,13 +35,12 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IImageUrlGenerator imageUrlGenerator, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _mediaFileSystem = mediaFileSystem; _imageUrlGenerator = imageUrlGenerator; diff --git a/src/Umbraco.Web/Editors/MacroRenderingController.cs b/src/Umbraco.Web/Editors/MacroRenderingController.cs index 06cd15dcb4..43b544cb1f 100644 --- a/src/Umbraco.Web/Editors/MacroRenderingController.cs +++ b/src/Umbraco.Web/Editors/MacroRenderingController.cs @@ -48,7 +48,6 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IUmbracoComponentRenderer componentRenderer, @@ -63,7 +62,6 @@ namespace Umbraco.Web.Editors appCaches, logger, runtimeState, - umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 0ac75df477..babeb921fa 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -47,13 +47,12 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, ParameterEditorCollection parameterEditorCollection, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _parameterEditorCollection = parameterEditorCollection; _ioHelper = ioHelper; diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index 328a1be238..8351f5a029 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -63,14 +63,13 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors)); _mediaFileSystem = mediaFileSystem; diff --git a/src/Umbraco.Web/Editors/MediaTypeController.cs b/src/Umbraco.Web/Editors/MediaTypeController.cs index f4c8f89e28..e6130ca1a9 100644 --- a/src/Umbraco.Web/Editors/MediaTypeController.cs +++ b/src/Umbraco.Web/Editors/MediaTypeController.cs @@ -51,13 +51,12 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IEntityService entityService, IPublishedUrlProvider publishedUrlProvider, EditorValidatorCollection editorValidatorCollection) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) { _shortStringHelper = shortStringHelper; _entityService = entityService ?? throw new ArgumentNullException(nameof(entityService)); diff --git a/src/Umbraco.Web/Editors/MemberController.cs b/src/Umbraco.Web/Editors/MemberController.cs index 9493047a56..55a3e29c5c 100644 --- a/src/Umbraco.Web/Editors/MemberController.cs +++ b/src/Umbraco.Web/Editors/MemberController.cs @@ -57,11 +57,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _passwordConfig = passwordConfig ?? throw new ArgumentNullException(nameof(passwordConfig)); _propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors)); diff --git a/src/Umbraco.Web/Editors/MemberTypeController.cs b/src/Umbraco.Web/Editors/MemberTypeController.cs index fd071d5e5c..63ec9c62c7 100644 --- a/src/Umbraco.Web/Editors/MemberTypeController.cs +++ b/src/Umbraco.Web/Editors/MemberTypeController.cs @@ -39,12 +39,11 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, EditorValidatorCollection editorValidatorCollection) - : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) + : base(cultureDictionary, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider, editorValidatorCollection) { } diff --git a/src/Umbraco.Web/Editors/PackageController.cs b/src/Umbraco.Web/Editors/PackageController.cs index a43bae566f..6dc913237d 100644 --- a/src/Umbraco.Web/Editors/PackageController.cs +++ b/src/Umbraco.Web/Editors/PackageController.cs @@ -43,12 +43,11 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _ioHelper = ioHelper; } diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index ed37bc9fbd..672b47f1eb 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -50,14 +50,13 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, IUmbracoVersion umbracoVersion, UmbracoMapper umbracoMapper, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider, IUmbracoApplicationLifetime umbracoApplicationLifetime) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _umbracoVersion = umbracoVersion; _ioHelper = ioHelper; diff --git a/src/Umbraco.Web/Editors/RelationTypeController.cs b/src/Umbraco.Web/Editors/RelationTypeController.cs index 26d9f60cf9..b5b983c9ff 100644 --- a/src/Umbraco.Web/Editors/RelationTypeController.cs +++ b/src/Umbraco.Web/Editors/RelationTypeController.cs @@ -38,11 +38,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/Editors/SectionController.cs b/src/Umbraco.Web/Editors/SectionController.cs index 88da2a1166..f352d9154f 100644 --- a/src/Umbraco.Web/Editors/SectionController.cs +++ b/src/Umbraco.Web/Editors/SectionController.cs @@ -29,8 +29,8 @@ namespace Umbraco.Web.Editors private readonly ITreeService _treeService; public SectionController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - IDashboardService dashboardService, ISectionService sectionService, ITreeService treeService, UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + IDashboardService dashboardService, ISectionService sectionService, ITreeService treeService, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _dashboardService = dashboardService; _sectionService = sectionService; @@ -45,7 +45,7 @@ namespace Umbraco.Web.Editors // this is a bit nasty since we'll be proxying via the app tree controller but we sort of have to do that // since tree's by nature are controllers and require request contextual data - var appTreeController = new ApplicationTreeController(GlobalSettings, UmbracoContextAccessor, SqlContext, Services, AppCaches, Logger, RuntimeState, _treeService, _sectionService, Umbraco, Mapper, PublishedUrlProvider) + var appTreeController = new ApplicationTreeController(GlobalSettings, UmbracoContextAccessor, SqlContext, Services, AppCaches, Logger, RuntimeState, _treeService, _sectionService, Mapper, PublishedUrlProvider) { ControllerContext = ControllerContext }; diff --git a/src/Umbraco.Web/Editors/TemplateController.cs b/src/Umbraco.Web/Editors/TemplateController.cs index fe86cabd01..a02536e2bb 100644 --- a/src/Umbraco.Web/Editors/TemplateController.cs +++ b/src/Umbraco.Web/Editors/TemplateController.cs @@ -34,11 +34,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/Editors/TemplateQueryController.cs b/src/Umbraco.Web/Editors/TemplateQueryController.cs index ed8023cc8d..df7f8a0d96 100644 --- a/src/Umbraco.Web/Editors/TemplateQueryController.cs +++ b/src/Umbraco.Web/Editors/TemplateQueryController.cs @@ -27,6 +27,7 @@ namespace Umbraco.Web.Editors public class TemplateQueryController : UmbracoAuthorizedJsonController { private readonly IVariationContextAccessor _variationContextAccessor; + private readonly IPublishedContentQuery _publishedContentQuery; public TemplateQueryController( IGlobalSettings globalSettings, @@ -36,14 +37,15 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IVariationContextAccessor variationContextAccessor, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, - IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + IPublishedUrlProvider publishedUrlProvider, + IPublishedContentQuery publishedContentQuery) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _variationContextAccessor = variationContextAccessor; + _publishedContentQuery = publishedContentQuery; } private IEnumerable Terms => new List @@ -79,7 +81,7 @@ namespace Umbraco.Web.Editors if (model == null) { - contents = Umbraco.ContentAtRoot().FirstOrDefault().Children(_variationContextAccessor); + contents = _publishedContentQuery.ContentAtRoot().FirstOrDefault().Children(_variationContextAccessor); queryExpression.Append("Umbraco.ContentAtRoot().FirstOrDefault().Children()"); } else @@ -110,7 +112,7 @@ namespace Umbraco.Web.Editors IPublishedContent sourceDocument; if (model.Source != null && model.Source.Id > 0) { - sourceDocument = Umbraco.Content(model.Source.Id); + sourceDocument = _publishedContentQuery.Content(model.Source.Id); if (sourceDocument == null) queryExpression.AppendFormat("Umbraco.Content({0})", model.Source.Id); @@ -119,7 +121,7 @@ namespace Umbraco.Web.Editors } else { - sourceDocument = Umbraco.ContentAtRoot().FirstOrDefault(); + sourceDocument = _publishedContentQuery.ContentAtRoot().FirstOrDefault(); queryExpression.Append("Umbraco.ContentAtRoot().FirstOrDefault()"); } diff --git a/src/Umbraco.Web/Editors/TinyMceController.cs b/src/Umbraco.Web/Editors/TinyMceController.cs index fdb67df1bf..e83a6676fe 100644 --- a/src/Umbraco.Web/Editors/TinyMceController.cs +++ b/src/Umbraco.Web/Editors/TinyMceController.cs @@ -42,13 +42,12 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IShortStringHelper shortStringHelper, IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _shortStringHelper = shortStringHelper ?? throw new ArgumentNullException(nameof(shortStringHelper)); _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); diff --git a/src/Umbraco.Web/Editors/TourController.cs b/src/Umbraco.Web/Editors/TourController.cs index c3b9732807..6b586ed162 100644 --- a/src/Umbraco.Web/Editors/TourController.cs +++ b/src/Umbraco.Web/Editors/TourController.cs @@ -36,14 +36,13 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, TourFilterCollection filters, IUmbracoSettingsSection umbracoSettingsSection, IIOHelper ioHelper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _filters = filters; _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); diff --git a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs index d55a901525..64aba378f4 100644 --- a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs +++ b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs @@ -38,11 +38,10 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { ShortStringHelper = shortStringHelper ?? throw new ArgumentNullException(nameof(shortStringHelper)); } diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index 3390677a08..0aa63a1e16 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -59,7 +59,6 @@ namespace Umbraco.Web.Editors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, @@ -67,7 +66,7 @@ namespace Umbraco.Web.Editors IIOHelper ioHelper, IImageUrlGenerator imageUrlGenerator, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _mediaFileSystem = mediaFileSystem; _umbracoSettingsSection = umbracoSettingsSection ?? throw new ArgumentNullException(nameof(umbracoSettingsSection)); diff --git a/src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs b/src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs index 2de0accd74..feeec0a1ba 100644 --- a/src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs +++ b/src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs @@ -24,7 +24,7 @@ namespace Umbraco.Web.Mvc private readonly string _dataTokenName; private IUmbracoContextAccessor _umbracoContextAccessor; private readonly int? _contentId; - private UmbracoHelper _helper; + private IPublishedContentQuery _publishedContentQuery; /// /// Constructor - can be used for testing @@ -74,10 +74,7 @@ namespace Umbraco.Web.Mvc // TODO: try lazy property injection? private IPublishedRouter PublishedRouter => Current.Factory.GetInstance(); - /// - /// Exposes an UmbracoHelper - /// - protected UmbracoHelper Umbraco => _helper ?? (_helper = Current.Factory.GetInstance()); + private IPublishedContentQuery PublishedContentQuery => _publishedContentQuery ?? (_publishedContentQuery = Current.Factory.GetInstance()); public override void OnActionExecuted(ActionExecutedContext filterContext) { @@ -103,7 +100,7 @@ namespace Umbraco.Web.Mvc { if (_contentId.HasValue) { - var content = Umbraco.Content(_contentId); + var content = PublishedContentQuery.Content(_contentId.Value); if (content == null) { throw new InvalidOperationException("Could not resolve content with id " + _contentId); diff --git a/src/Umbraco.Web/Mvc/PluginController.cs b/src/Umbraco.Web/Mvc/PluginController.cs index bd5d01995d..9f34de174b 100644 --- a/src/Umbraco.Web/Mvc/PluginController.cs +++ b/src/Umbraco.Web/Mvc/PluginController.cs @@ -76,13 +76,12 @@ namespace Umbraco.Web.Mvc Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), - Current.Factory.GetInstance() + Current.Factory.GetInstance() ) { } - protected PluginController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) + protected PluginController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger) { UmbracoContextAccessor = umbracoContextAccessor; DatabaseFactory = databaseFactory; @@ -90,7 +89,6 @@ namespace Umbraco.Web.Mvc AppCaches = appCaches; Logger = logger; ProfilingLogger = profilingLogger; - Umbraco = umbracoHelper; } /// diff --git a/src/Umbraco.Web/Mvc/RenderMvcController.cs b/src/Umbraco.Web/Mvc/RenderMvcController.cs index 005a2da495..7286f52c64 100644 --- a/src/Umbraco.Web/Mvc/RenderMvcController.cs +++ b/src/Umbraco.Web/Mvc/RenderMvcController.cs @@ -25,8 +25,8 @@ namespace Umbraco.Web.Mvc ActionInvoker = new RenderActionInvoker(); } - public RenderMvcController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) - : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, umbracoHelper) + public RenderMvcController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger) + : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger) { ActionInvoker = new RenderActionInvoker(); } diff --git a/src/Umbraco.Web/Mvc/SurfaceController.cs b/src/Umbraco.Web/Mvc/SurfaceController.cs index c03d59058c..877a3c31d8 100644 --- a/src/Umbraco.Web/Mvc/SurfaceController.cs +++ b/src/Umbraco.Web/Mvc/SurfaceController.cs @@ -20,8 +20,8 @@ namespace Umbraco.Web.Mvc protected SurfaceController() { } - protected SurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) - : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) + protected SurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger) { } /// diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs index ebdd83cf20..0724cd138d 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs @@ -21,8 +21,8 @@ namespace Umbraco.Web.Mvc { } - protected UmbracoAuthorizedController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) - : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, umbracoHelper) + protected UmbracoAuthorizedController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger) + : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger) { } } diff --git a/src/Umbraco.Web/Mvc/UmbracoController.cs b/src/Umbraco.Web/Mvc/UmbracoController.cs index 4455ef18c8..9cfd93ba9d 100644 --- a/src/Umbraco.Web/Mvc/UmbracoController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoController.cs @@ -73,13 +73,12 @@ namespace Umbraco.Web.Mvc Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), - Current.Factory.GetInstance() + Current.Factory.GetInstance() ) { } - protected UmbracoController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) + protected UmbracoController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger) { GlobalSettings = globalSettings; UmbracoContextAccessor = umbracoContextAccessor; @@ -87,7 +86,6 @@ namespace Umbraco.Web.Mvc AppCaches = appCaches; Logger = profilingLogger; ProfilingLogger = profilingLogger; - Umbraco = umbracoHelper; } } } diff --git a/src/Umbraco.Web/Profiling/WebProfilingController.cs b/src/Umbraco.Web/Profiling/WebProfilingController.cs index 7bc28f28ea..b37a7eefb8 100644 --- a/src/Umbraco.Web/Profiling/WebProfilingController.cs +++ b/src/Umbraco.Web/Profiling/WebProfilingController.cs @@ -28,11 +28,10 @@ namespace Umbraco.Web.Profiling AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _runtimeState = runtimeState; } diff --git a/src/Umbraco.Web/PropertyEditors/RichTextPreValueController.cs b/src/Umbraco.Web/PropertyEditors/RichTextPreValueController.cs index 5d7ca9bdb0..e7ed10c8bf 100644 --- a/src/Umbraco.Web/PropertyEditors/RichTextPreValueController.cs +++ b/src/Umbraco.Web/PropertyEditors/RichTextPreValueController.cs @@ -33,13 +33,12 @@ namespace Umbraco.Web.PropertyEditors AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, IShortStringHelper shortStringHelper, IIOHelper ioHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider ) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, shortStringHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, shortStringHelper, umbracoMapper, publishedUrlProvider) { _ioHelper = ioHelper; } diff --git a/src/Umbraco.Web/PropertyEditors/TagsDataController.cs b/src/Umbraco.Web/PropertyEditors/TagsDataController.cs index 7d699077c3..9cb00090e3 100644 --- a/src/Umbraco.Web/PropertyEditors/TagsDataController.cs +++ b/src/Umbraco.Web/PropertyEditors/TagsDataController.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Web.Models; @@ -17,6 +18,12 @@ namespace Umbraco.Web.PropertyEditors [PluginController("UmbracoApi")] public class TagsDataController : UmbracoAuthorizedApiController { + private readonly ITagQuery _tagQuery; + + public TagsDataController(ITagQuery tagQuery) + { + _tagQuery = tagQuery ?? throw new ArgumentNullException(nameof(tagQuery)); + } /// /// Returns all tags matching tagGroup, culture and an optional query /// @@ -28,9 +35,9 @@ namespace Umbraco.Web.PropertyEditors { if (culture == string.Empty) culture = null; - var result = Umbraco.TagQuery.GetAllTags(tagGroup, culture); + var result = _tagQuery.GetAllTags(tagGroup, culture); + - if (!query.IsNullOrWhiteSpace()) { //TODO: add the query to TagQuery + the tag service, this is ugly but all we can do for now. diff --git a/src/Umbraco.Web/Runtime/WebInitialComposer.cs b/src/Umbraco.Web/Runtime/WebInitialComposer.cs index e4b50a248c..0ea88d23df 100644 --- a/src/Umbraco.Web/Runtime/WebInitialComposer.cs +++ b/src/Umbraco.Web/Runtime/WebInitialComposer.cs @@ -132,8 +132,7 @@ namespace Umbraco.Web.Runtime composition.Register(factory => { var umbCtx = factory.GetInstance(); - return new UmbracoHelper(umbCtx.IsFrontEndUmbracoRequest ? umbCtx.PublishedRequest?.PublishedContent : null, - factory.GetInstance(), factory.GetInstance(), + return new UmbracoHelper(umbCtx.IsFrontEndUmbracoRequest ? umbCtx.PublishedRequest?.PublishedContent : null, factory.GetInstance(), factory.GetInstance(), factory.GetInstance()); }); else diff --git a/src/Umbraco.Web/Trees/ApplicationTreeController.cs b/src/Umbraco.Web/Trees/ApplicationTreeController.cs index 8ee39b49e5..d815f76b40 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web/Trees/ApplicationTreeController.cs @@ -38,8 +38,8 @@ namespace Umbraco.Web.Trees public ApplicationTreeController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, - IRuntimeState runtimeState, ITreeService treeService, ISectionService sectionService, UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + IRuntimeState runtimeState, ITreeService treeService, ISectionService sectionService, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeService = treeService; _sectionService = sectionService; diff --git a/src/Umbraco.Web/Trees/ContentBlueprintTreeController.cs b/src/Umbraco.Web/Trees/ContentBlueprintTreeController.cs index 843a1cef0c..2218142b90 100644 --- a/src/Umbraco.Web/Trees/ContentBlueprintTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentBlueprintTreeController.cs @@ -40,11 +40,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/ContentTreeController.cs b/src/Umbraco.Web/Trees/ContentTreeController.cs index 9b64111b85..a82d4faba6 100644 --- a/src/Umbraco.Web/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentTreeController.cs @@ -63,11 +63,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider, menuItemCollectionFactory) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider, menuItemCollectionFactory) { _treeSearcher = treeSearcher; _actions = actions; diff --git a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs index 083c4b82e8..1b347cee36 100644 --- a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs @@ -38,11 +38,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { MenuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/ContentTypeTreeController.cs b/src/Umbraco.Web/Trees/ContentTypeTreeController.cs index 4fac87e226..e04bfab9c2 100644 --- a/src/Umbraco.Web/Trees/ContentTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentTypeTreeController.cs @@ -38,11 +38,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeSearcher = treeSearcher; _menuItemCollectionFactory = menuItemCollectionFactory; diff --git a/src/Umbraco.Web/Trees/DataTypeTreeController.cs b/src/Umbraco.Web/Trees/DataTypeTreeController.cs index 100a5ffe7a..50882488f3 100644 --- a/src/Umbraco.Web/Trees/DataTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/DataTypeTreeController.cs @@ -40,11 +40,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeSearcher = treeSearcher; _menuItemCollectionFactory = menuItemCollectionFactory; diff --git a/src/Umbraco.Web/Trees/DictionaryTreeController.cs b/src/Umbraco.Web/Trees/DictionaryTreeController.cs index b8d16062ba..8c60532c76 100644 --- a/src/Umbraco.Web/Trees/DictionaryTreeController.cs +++ b/src/Umbraco.Web/Trees/DictionaryTreeController.cs @@ -38,11 +38,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/FileSystemTreeController.cs b/src/Umbraco.Web/Trees/FileSystemTreeController.cs index e4bfbc53f7..eb13daea29 100644 --- a/src/Umbraco.Web/Trees/FileSystemTreeController.cs +++ b/src/Umbraco.Web/Trees/FileSystemTreeController.cs @@ -33,11 +33,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { MenuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/MacrosTreeController.cs b/src/Umbraco.Web/Trees/MacrosTreeController.cs index 5c03e11c37..217298a7eb 100644 --- a/src/Umbraco.Web/Trees/MacrosTreeController.cs +++ b/src/Umbraco.Web/Trees/MacrosTreeController.cs @@ -32,11 +32,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/MediaTreeController.cs b/src/Umbraco.Web/Trees/MediaTreeController.cs index 0ac33734ff..37f0c8dead 100644 --- a/src/Umbraco.Web/Trees/MediaTreeController.cs +++ b/src/Umbraco.Web/Trees/MediaTreeController.cs @@ -50,11 +50,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider, menuItemCollectionFactory) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider, menuItemCollectionFactory) { _treeSearcher = treeSearcher; } diff --git a/src/Umbraco.Web/Trees/MediaTypeTreeController.cs b/src/Umbraco.Web/Trees/MediaTypeTreeController.cs index c366791d2b..4677b251f3 100644 --- a/src/Umbraco.Web/Trees/MediaTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/MediaTypeTreeController.cs @@ -38,12 +38,11 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory, IMediaTypeService mediaTypeService) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeSearcher = treeSearcher; _menuItemCollectionFactory = menuItemCollectionFactory; diff --git a/src/Umbraco.Web/Trees/MemberTreeController.cs b/src/Umbraco.Web/Trees/MemberTreeController.cs index ad77c837f6..b4efc27b24 100644 --- a/src/Umbraco.Web/Trees/MemberTreeController.cs +++ b/src/Umbraco.Web/Trees/MemberTreeController.cs @@ -52,12 +52,11 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, UmbracoTreeSearcher treeSearcher, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeSearcher = treeSearcher; _menuItemCollectionFactory = menuItemCollectionFactory; diff --git a/src/Umbraco.Web/Trees/MemberTypeAndGroupTreeControllerBase.cs b/src/Umbraco.Web/Trees/MemberTypeAndGroupTreeControllerBase.cs index e54b200fea..258a2aea5f 100644 --- a/src/Umbraco.Web/Trees/MemberTypeAndGroupTreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/MemberTypeAndGroupTreeControllerBase.cs @@ -33,11 +33,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { MenuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/PackagesTreeController.cs b/src/Umbraco.Web/Trees/PackagesTreeController.cs index 5608196109..022e33750a 100644 --- a/src/Umbraco.Web/Trees/PackagesTreeController.cs +++ b/src/Umbraco.Web/Trees/PackagesTreeController.cs @@ -30,11 +30,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/RelationTypeTreeController.cs b/src/Umbraco.Web/Trees/RelationTypeTreeController.cs index 5601af0da3..dc849a3154 100644 --- a/src/Umbraco.Web/Trees/RelationTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/RelationTypeTreeController.cs @@ -30,11 +30,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/Trees/TemplatesTreeController.cs b/src/Umbraco.Web/Trees/TemplatesTreeController.cs index 647683e5c5..4745b4b172 100644 --- a/src/Umbraco.Web/Trees/TemplatesTreeController.cs +++ b/src/Umbraco.Web/Trees/TemplatesTreeController.cs @@ -40,11 +40,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeSearcher = treeSearcher; _menuItemCollectionFactory = menuItemCollectionFactory; diff --git a/src/Umbraco.Web/Trees/TreeController.cs b/src/Umbraco.Web/Trees/TreeController.cs index 7185cbaf13..e76b45e623 100644 --- a/src/Umbraco.Web/Trees/TreeController.cs +++ b/src/Umbraco.Web/Trees/TreeController.cs @@ -28,10 +28,9 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _treeAttribute = GetTreeAttribute(); } diff --git a/src/Umbraco.Web/Trees/TreeControllerBase.cs b/src/Umbraco.Web/Trees/TreeControllerBase.cs index b6e71c058a..49f7eea845 100644 --- a/src/Umbraco.Web/Trees/TreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/TreeControllerBase.cs @@ -42,10 +42,9 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { } diff --git a/src/Umbraco.Web/Trees/UserTreeController.cs b/src/Umbraco.Web/Trees/UserTreeController.cs index 648e9ef29c..4d97be511d 100644 --- a/src/Umbraco.Web/Trees/UserTreeController.cs +++ b/src/Umbraco.Web/Trees/UserTreeController.cs @@ -30,11 +30,10 @@ namespace Umbraco.Web.Trees AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, - UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider, IMenuItemCollectionFactory menuItemCollectionFactory) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper, umbracoMapper, publishedUrlProvider) + : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoMapper, publishedUrlProvider) { _menuItemCollectionFactory = menuItemCollectionFactory; } diff --git a/src/Umbraco.Web/UmbracoHelper.cs b/src/Umbraco.Web/UmbracoHelper.cs index 679fbb789c..764647988a 100644 --- a/src/Umbraco.Web/UmbracoHelper.cs +++ b/src/Umbraco.Web/UmbracoHelper.cs @@ -21,7 +21,6 @@ namespace Umbraco.Web public class UmbracoHelper { private readonly IPublishedContentQuery _publishedContentQuery; - private readonly ITagQuery _tagQuery; private readonly IUmbracoComponentRenderer _componentRenderer; private readonly ICultureDictionaryFactory _cultureDictionaryFactory; @@ -34,19 +33,15 @@ namespace Umbraco.Web /// Initializes a new instance of . /// /// The item assigned to the helper. - /// /// /// /// - /// /// Sets the current page to the context's published content request's content item. public UmbracoHelper(IPublishedContent currentPage, - ITagQuery tagQuery, ICultureDictionaryFactory cultureDictionary, IUmbracoComponentRenderer componentRenderer, IPublishedContentQuery publishedContentQuery) { - _tagQuery = tagQuery ?? throw new ArgumentNullException(nameof(tagQuery)); _cultureDictionaryFactory = cultureDictionary ?? throw new ArgumentNullException(nameof(cultureDictionary)); _componentRenderer = componentRenderer ?? throw new ArgumentNullException(nameof(componentRenderer)); _publishedContentQuery = publishedContentQuery ?? throw new ArgumentNullException(nameof(publishedContentQuery)); @@ -62,21 +57,6 @@ namespace Umbraco.Web #endregion - // ensures that we can return the specified value - T Ensure(T o) where T : class => o ?? throw new InvalidOperationException("This UmbracoHelper instance has not been initialized."); - - private IUmbracoComponentRenderer ComponentRenderer => Ensure(_componentRenderer); - private ICultureDictionaryFactory CultureDictionaryFactory => Ensure(_cultureDictionaryFactory); - - /// - /// Gets the tag context. - /// - public ITagQuery TagQuery => Ensure(_tagQuery); - - /// - /// Gets the query context. - /// - public IPublishedContentQuery ContentQuery => Ensure(_publishedContentQuery); /// /// Gets (or sets) the current item assigned to the UmbracoHelper. @@ -122,7 +102,7 @@ namespace Umbraco.Web /// public IHtmlString RenderTemplate(int contentId, int? altTemplateId = null) { - return ComponentRenderer.RenderTemplate(contentId, altTemplateId); + return _componentRenderer.RenderTemplate(contentId, altTemplateId); } #region RenderMacro @@ -134,7 +114,7 @@ namespace Umbraco.Web /// public IHtmlString RenderMacro(string alias) { - return ComponentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, null); + return _componentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, null); } /// @@ -145,7 +125,7 @@ namespace Umbraco.Web /// public IHtmlString RenderMacro(string alias, object parameters) { - return ComponentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, parameters?.ToDictionary()); + return _componentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, parameters?.ToDictionary()); } /// @@ -156,7 +136,7 @@ namespace Umbraco.Web /// public IHtmlString RenderMacro(string alias, IDictionary parameters) { - return ComponentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, parameters); + return _componentRenderer.RenderMacro(AssignedContentItem?.Id ?? 0, alias, parameters); } #endregion @@ -192,8 +172,7 @@ namespace Umbraco.Web /// /// Returns the ICultureDictionary for access to dictionary items /// - public ICultureDictionary CultureDictionary => _cultureDictionary - ?? (_cultureDictionary = CultureDictionaryFactory.CreateDictionary()); + public ICultureDictionary CultureDictionary => _cultureDictionary ??= _cultureDictionaryFactory.CreateDictionary(); #endregion @@ -211,15 +190,11 @@ namespace Umbraco.Web return ContentForObject(id); } - private IPublishedContent ContentForObject(object id) + private IPublishedContent ContentForObject(object id) => _publishedContentQuery.Content(id); + + public IPublishedContent ContentSingleAtXPath(string xpath, params XPathVariable[] vars) { - if (ConvertIdObjectToInt(id, out var intId)) - return ContentQuery.Content(intId); - if (ConvertIdObjectToGuid(id, out var guidId)) - return ContentQuery.Content(guidId); - if (ConvertIdObjectToUdi(id, out var udiId)) - return ContentQuery.Content(udiId); - return null; + return _publishedContentQuery.ContentSingleAtXPath(xpath, vars); } /// @@ -227,40 +202,23 @@ namespace Umbraco.Web /// /// The unique identifier of the content item. /// The content, or null of the content item is not in the cache. - public IPublishedContent Content(int id) - { - return ContentQuery.Content(id); - } + public IPublishedContent Content(int id) => _publishedContentQuery.Content(id); /// /// Gets a content item from the cache. /// /// The key of the content item. /// The content, or null of the content item is not in the cache. - public IPublishedContent Content(Guid id) - { - return ContentQuery.Content(id); - } + public IPublishedContent Content(Guid id) => _publishedContentQuery.Content(id); /// /// Gets a content item from the cache. /// /// The unique identifier, or the key, of the content item. /// The content, or null of the content item is not in the cache. - public IPublishedContent Content(string id) - { - return ContentForObject(id); - } + public IPublishedContent Content(string id) => _publishedContentQuery.Content(id); - public IPublishedContent Content(Udi id) - { - return ContentQuery.Content(id); - } - - public IPublishedContent ContentSingleAtXPath(string xpath, params XPathVariable[] vars) - { - return ContentQuery.ContentSingleAtXPath(xpath, vars); - } + public IPublishedContent Content(Udi id) => _publishedContentQuery.Content(id); /// /// Gets content items from the cache. @@ -268,10 +226,7 @@ namespace Umbraco.Web /// The unique identifiers, or the keys, of the content items. /// The content items that were found in the cache. /// Does not support mixing identifiers and keys. - public IEnumerable Content(params object[] ids) - { - return ContentForObjects(ids); - } + public IEnumerable Content(params object[] ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -279,10 +234,7 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(params Udi[] ids) - { - return ids.Select(id => ContentQuery.Content(id)).WhereNotNull(); - } + public IEnumerable Content(params Udi[] ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -290,40 +242,23 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(params GuidUdi[] ids) - { - return ids.Select(id => ContentQuery.Content(id)); - } + public IEnumerable Content(params GuidUdi[] ids) => _publishedContentQuery.Content(ids); - private IEnumerable ContentForObjects(IEnumerable ids) - { - var idsA = ids.ToArray(); - if (ConvertIdsObjectToInts(idsA, out var intIds)) - return ContentQuery.Content(intIds); - if (ConvertIdsObjectToGuids(idsA, out var guidIds)) - return ContentQuery.Content(guidIds); - return Enumerable.Empty(); - } + private IEnumerable ContentForObjects(IEnumerable ids) => _publishedContentQuery.Content(ids); /// /// Gets content items from the cache. /// /// The unique identifiers of the content items. /// The content items that were found in the cache. - public IEnumerable Content(params int[] ids) - { - return ContentQuery.Content(ids); - } + public IEnumerable Content(params int[] ids) => _publishedContentQuery.Content(ids); /// /// Gets content items from the cache. /// /// The keys of the content items. /// The content items that were found in the cache. - public IEnumerable Content(params Guid[] ids) - { - return ContentQuery.Content(ids); - } + public IEnumerable Content(params Guid[] ids) => _publishedContentQuery.Content(ids); /// /// Gets content items from the cache. @@ -331,10 +266,7 @@ namespace Umbraco.Web /// The unique identifiers, or the keys, of the content items. /// The content items that were found in the cache. /// Does not support mixing identifiers and keys. - public IEnumerable Content(params string[] ids) - { - return ContentForObjects(ids); - } + public IEnumerable Content(params string[] ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -342,20 +274,7 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(IEnumerable ids) - { - return ContentForObjects(ids); - } - /// - /// Gets the contents corresponding to the identifiers. - /// - /// The content identifiers. - /// The existing contents corresponding to the identifiers. - /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(IEnumerable ids) - { - return ids.Select(id => ContentQuery.Content(id)).WhereNotNull(); - } + public IEnumerable Content(IEnumerable ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -363,10 +282,7 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(IEnumerable ids) - { - return ids.Select(id => ContentQuery.Content(id)); - } + public IEnumerable Content(IEnumerable ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -374,10 +290,7 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(IEnumerable ids) - { - return ContentForObjects(ids); - } + public IEnumerable Content(IEnumerable ids) => _publishedContentQuery.Content(ids); /// /// Gets the contents corresponding to the identifiers. @@ -385,124 +298,40 @@ namespace Umbraco.Web /// The content identifiers. /// The existing contents corresponding to the identifiers. /// If an identifier does not match an existing content, it will be missing in the returned value. - public IEnumerable Content(IEnumerable ids) - { - return ContentQuery.Content(ids); - } + public IEnumerable Content(IEnumerable ids) => _publishedContentQuery.Content(ids); + + /// + /// Gets the contents corresponding to the identifiers. + /// + /// The content identifiers. + /// The existing contents corresponding to the identifiers. + /// If an identifier does not match an existing content, it will be missing in the returned value. + public IEnumerable Content(IEnumerable ids) => _publishedContentQuery.Content(ids); public IEnumerable ContentAtXPath(string xpath, params XPathVariable[] vars) { - return ContentQuery.ContentAtXPath(xpath, vars); + return _publishedContentQuery.ContentAtXPath(xpath, vars); } public IEnumerable ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars) { - return ContentQuery.ContentAtXPath(xpath, vars); + return _publishedContentQuery.ContentAtXPath(xpath, vars); } public IEnumerable ContentAtRoot() { - return ContentQuery.ContentAtRoot(); + return _publishedContentQuery.ContentAtRoot(); } - internal 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; - } - } - - internal 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 ConvertIdsObjectToInts(IEnumerable ids, out IEnumerable intIds) - { - var list = new List(); - intIds = null; - foreach (var id in ids) - { - if (ConvertIdObjectToInt(id, out var intId)) - list.Add(intId); - else - return false; // if one of them is not an int, fail - } - intIds = list; - return true; - } - - private static bool ConvertIdsObjectToGuids(IEnumerable ids, out IEnumerable guidIds) - { - var list = new List(); - guidIds = null; - foreach (var id in ids) - { - Guid guidId; - if (ConvertIdObjectToGuid(id, out guidId)) - list.Add(guidId); - else - return false; // if one of them is not a guid, fail - } - guidIds = list; - return true; - } - - /// Had to change to internal for testing. - internal 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 Media - public IPublishedContent Media(Udi id) - { - var guidUdi = id as GuidUdi; - return guidUdi == null ? null : Media(guidUdi.Guid); - } + public IPublishedContent Media(Udi id) => _publishedContentQuery.Media(id); - public IPublishedContent Media(Guid id) - { - return ContentQuery.Media(id); - } + public IPublishedContent Media(Guid id) => _publishedContentQuery.Media(id); /// /// Overloaded method accepting an 'object' type @@ -519,26 +348,11 @@ namespace Umbraco.Web return MediaForObject(id); } - private IPublishedContent MediaForObject(object id) - { - if (ConvertIdObjectToInt(id, out var intId)) - return ContentQuery.Media(intId); - if (ConvertIdObjectToGuid(id, out var guidId)) - return ContentQuery.Media(guidId); - if (ConvertIdObjectToUdi(id, out var udiId)) - return ContentQuery.Media(udiId); - return null; - } + private IPublishedContent MediaForObject(object id) => _publishedContentQuery.Media(id); - public IPublishedContent Media(int id) - { - return ContentQuery.Media(id); - } + public IPublishedContent Media(int id) => _publishedContentQuery.Media(id); - public IPublishedContent Media(string id) - { - return MediaForObject(id); - } + public IPublishedContent Media(string id) => _publishedContentQuery.Media(id); /// /// Gets the medias corresponding to the identifiers. @@ -546,20 +360,9 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(params object[] ids) - { - return MediaForObjects(ids); - } + public IEnumerable Media(params object[] ids) => _publishedContentQuery.Media(ids); - private IEnumerable MediaForObjects(IEnumerable ids) - { - var idsA = ids.ToArray(); - if (ConvertIdsObjectToInts(idsA, out var intIds)) - return ContentQuery.Media(intIds); - if (ConvertIdsObjectToGuids(idsA, out var guidIds)) - return ContentQuery.Media(guidIds); - return Enumerable.Empty(); - } + private IEnumerable MediaForObjects(IEnumerable ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -567,10 +370,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(params int[] ids) - { - return ContentQuery.Media(ids); - } + public IEnumerable Media(params int[] ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -578,10 +378,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(params string[] ids) - { - return MediaForObjects(ids); - } + public IEnumerable Media(params string[] ids) => _publishedContentQuery.Media(ids); /// @@ -590,10 +387,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(params Udi[] ids) - { - return ids.Select(id => ContentQuery.Media(id)).WhereNotNull(); - } + public IEnumerable Media(params Udi[] ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -601,10 +395,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(params GuidUdi[] ids) - { - return ids.Select(id => ContentQuery.Media(id)); - } + public IEnumerable Media(params GuidUdi[] ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -612,10 +403,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(IEnumerable ids) - { - return MediaForObjects(ids); - } + public IEnumerable Media(IEnumerable ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -623,10 +411,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(IEnumerable ids) - { - return ContentQuery.Media(ids); - } + public IEnumerable Media(IEnumerable ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -634,10 +419,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(IEnumerable ids) - { - return ids.Select(id => ContentQuery.Media(id)).WhereNotNull(); - } + public IEnumerable Media(IEnumerable ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -645,10 +427,7 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(IEnumerable ids) - { - return ids.Select(id => ContentQuery.Media(id)); - } + public IEnumerable Media(IEnumerable ids) => _publishedContentQuery.Media(ids); /// /// Gets the medias corresponding to the identifiers. @@ -656,17 +435,15 @@ namespace Umbraco.Web /// The media identifiers. /// The existing medias corresponding to the identifiers. /// If an identifier does not match an existing media, it will be missing in the returned value. - public IEnumerable Media(IEnumerable ids) - { - return MediaForObjects(ids); - } + public IEnumerable Media(IEnumerable ids) => _publishedContentQuery.Media(ids); public IEnumerable MediaAtRoot() { - return ContentQuery.MediaAtRoot(); + return _publishedContentQuery.MediaAtRoot(); } #endregion + internal static bool DecryptAndValidateEncryptedRouteString(string ufprt, out IDictionary parts) { string decryptedString; diff --git a/src/Umbraco.Web/UmbracoHttpHandler.cs b/src/Umbraco.Web/UmbracoHttpHandler.cs index 27a3255edd..eb219f82d2 100644 --- a/src/Umbraco.Web/UmbracoHttpHandler.cs +++ b/src/Umbraco.Web/UmbracoHttpHandler.cs @@ -14,16 +14,15 @@ namespace Umbraco.Web private UrlHelper _url; protected UmbracoHttpHandler() - : this(Current.UmbracoContextAccessor, Current.UmbracoHelper, Current.Services, Current.ProfilingLogger) + : this(Current.UmbracoContextAccessor, Current.Services, Current.ProfilingLogger) { } - protected UmbracoHttpHandler(IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper umbracoHelper, ServiceContext service, IProfilingLogger plogger) + protected UmbracoHttpHandler(IUmbracoContextAccessor umbracoContextAccessor,ServiceContext service, IProfilingLogger plogger) { UmbracoContextAccessor = umbracoContextAccessor; Logger = plogger; ProfilingLogger = plogger; Services = service; - Umbraco = umbracoHelper; } public abstract void ProcessRequest(HttpContext context); @@ -45,11 +44,6 @@ namespace Umbraco.Web /// public IUmbracoContextAccessor UmbracoContextAccessor { get; } - /// - /// Gets the Umbraco helper. - /// - public UmbracoHelper Umbraco { get; } - /// /// Gets the services context. /// diff --git a/src/Umbraco.Web/UmbracoWebService.cs b/src/Umbraco.Web/UmbracoWebService.cs index 3b35dbd6c7..916ab5ad8e 100644 --- a/src/Umbraco.Web/UmbracoWebService.cs +++ b/src/Umbraco.Web/UmbracoWebService.cs @@ -21,18 +21,17 @@ namespace Umbraco.Web { private UrlHelper _url; - protected UmbracoWebService(IProfilingLogger profilingLogger, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper umbraco, ServiceContext services, IGlobalSettings globalSettings) + protected UmbracoWebService(IProfilingLogger profilingLogger, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, IGlobalSettings globalSettings) { Logger = profilingLogger; ProfilingLogger = profilingLogger; UmbracoContextAccessor = umbracoContextAccessor; - Umbraco = umbraco; Services = services; GlobalSettings = globalSettings; } protected UmbracoWebService() - : this(Current.ProfilingLogger, Current.UmbracoContextAccessor, Current.UmbracoHelper, Current.Services, Current.Configs.Global()) + : this(Current.ProfilingLogger, Current.UmbracoContextAccessor, Current.Services, Current.Configs.Global()) { } @@ -56,11 +55,6 @@ namespace Umbraco.Web /// public IUmbracoContextAccessor UmbracoContextAccessor { get; } - /// - /// Gets the Umbraco helper. - /// - public UmbracoHelper Umbraco { get; } - /// /// Gets the services context. /// diff --git a/src/Umbraco.Web/WebApi/UmbracoApiController.cs b/src/Umbraco.Web/WebApi/UmbracoApiController.cs index 1541389a4f..a832b4e823 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiController.cs @@ -20,8 +20,8 @@ namespace Umbraco.Web.WebApi { } - protected UmbracoApiController(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) + protected UmbracoApiController(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.Web/WebApi/UmbracoApiControllerBase.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs index 0d0b64b085..9f52e52864 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs @@ -45,7 +45,6 @@ namespace Umbraco.Web.WebApi Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance() ) @@ -54,7 +53,7 @@ namespace Umbraco.Web.WebApi /// /// Initializes a new instance of the class with all its dependencies. /// - protected UmbracoApiControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) + protected UmbracoApiControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoMapper umbracoMapper, IPublishedUrlProvider publishedUrlProvider) { UmbracoContextAccessor = umbracoContextAccessor; GlobalSettings = globalSettings; @@ -63,7 +62,6 @@ namespace Umbraco.Web.WebApi AppCaches = appCaches; Logger = logger; RuntimeState = runtimeState; - Umbraco = umbracoHelper; Mapper = umbracoMapper; PublishedUrlProvider = publishedUrlProvider; } @@ -120,11 +118,6 @@ namespace Umbraco.Web.WebApi /// protected Uri ApplicationUrl => RuntimeState.ApplicationUrl; - /// - /// Gets the Umbraco helper. - /// - public UmbracoHelper Umbraco { get; } - /// /// Gets the mapper. /// diff --git a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs index ff24a2a6f5..57487e29fd 100644 --- a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs @@ -37,8 +37,8 @@ namespace Umbraco.Web.WebApi { } - protected UmbracoAuthorizedApiController(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) + protected UmbracoAuthorizedApiController(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) { } From a4003ad7992599624ec410486ce2caa8831d0ad1 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Tue, 3 Mar 2020 12:09:15 +0100 Subject: [PATCH 04/10] Clean up --- src/Umbraco.Core/Routing/PublishedRouter.cs | 31 --------------------- 1 file changed, 31 deletions(-) diff --git a/src/Umbraco.Core/Routing/PublishedRouter.cs b/src/Umbraco.Core/Routing/PublishedRouter.cs index 90d0d8876c..f521c3a95a 100644 --- a/src/Umbraco.Core/Routing/PublishedRouter.cs +++ b/src/Umbraco.Core/Routing/PublishedRouter.cs @@ -595,37 +595,6 @@ namespace Umbraco.Web.Routing _logger.Debug("Current member has access"); break; } - - // - // 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 - // { - // _logger.Debug("Current member has access"); - // } - // } } else { From 01362d0dd0674abf167f3969ed3470f8fad84a8f Mon Sep 17 00:00:00 2001 From: cyberdot Date: Tue, 3 Mar 2020 11:18:54 +0000 Subject: [PATCH 05/10] NetCore: Abstract ConfigurationManager references --- .../IActiveDirectorySettings.cs | 7 +++++ .../IExceptionFilterSettings.cs | 7 +++++ .../IIndexCreatorSettings.cs | 7 +++++ .../IModelsBuilderConfig.cs | 2 +- src/Umbraco.Abstractions/INuCacheSettings.cs | 7 +++++ src/Umbraco.Abstractions/IRuntimeSettings.cs | 8 +++++ .../ITypeFinderSettings.cs | 7 +++++ .../ModelsMode.cs | 2 +- .../Umbraco.Abstractions.csproj | 7 +++++ .../ActiveDirectorySettings.cs | 15 ++++++++++ .../ExceptionFilterSettings.cs | 18 ++++++++++++ src/Umbraco.Configuration/GlobalSettings.cs | 4 +++ .../IndexCreatorSettings.cs | 15 ++++++++++ .../ModelsBuilderConfig.cs | 13 ++++++--- .../ModelsModeExtensions.cs | 4 ++- src/Umbraco.Configuration/NuCacheSettings.cs | 14 +++++++++ src/Umbraco.Configuration/RuntimeSettings.cs | 29 +++++++++++++++++++ .../TypeFinderSettings.cs | 17 +++++++++++ .../Umbraco.Configuration.csproj | 1 + .../Configuration/IGlobalSettings.cs | 1 + .../UmbracoSettings/ITypeFinderConfig.cs | 4 +-- .../LuceneIndexCreator.cs | 9 ++++-- .../Umbraco.Examine.Lucene.csproj | 1 + .../UmbracoIndexesCreator.cs | 4 ++- .../CompositionExtensions/Configuration.cs | 12 +++++++- .../Umbraco.Infrastructure.csproj | 2 ++ .../BackOffice/ContentTypeModelValidator.cs | 2 +- .../ContentTypeModelValidatorBase.cs | 2 +- .../BackOffice/DashboardReport.cs | 3 +- .../BackOffice/MediaTypeModelValidator.cs | 2 +- .../BackOffice/MemberTypeModelValidator.cs | 2 +- .../ModelsBuilderDashboardController.cs | 3 +- .../Building/Builder.cs | 3 +- .../Building/ModelsGenerator.cs | 2 +- .../Building/TextBuilder.cs | 2 +- .../Compose/ModelsBuilderComponent.cs | 3 +- .../Compose/ModelsBuilderComposer.cs | 4 +-- .../ConfigsExtensions.cs | 4 +-- .../LiveModelsProvider.cs | 4 +-- .../ModelsGenerationError.cs | 2 +- .../OutOfDateModelsStatus.cs | 2 +- .../PureLiveModelFactory.cs | 2 +- .../Umbraco.ModelsBuilder.Embedded.csproj | 16 ++++++---- .../DataSource/BTree.cs | 9 +++--- .../PublishedSnapshotService.cs | 10 +++++-- .../Umbraco.PublishedCache.NuCache.csproj | 1 + .../ModelsBuilder/BuilderTests.cs | 2 +- .../ModelsBuilder/ConfigTests.cs | 2 +- .../PublishedContent/NuCacheChildrenTests.cs | 5 +++- .../PublishedContent/NuCacheTests.cs | 5 +++- .../Routing/RenderRouteHandlerTests.cs | 21 +++++--------- .../Scoping/ScopedNuCacheTests.cs | 5 +++- .../ContentTypeServiceVariantsTests.cs | 5 +++- src/Umbraco.Tests/Umbraco.Tests.csproj | 4 +++ .../Umbraco/Views/Default.cshtml | 2 +- .../Composing/BuildManagerTypeFinder.cs | 20 +++++++++---- .../Editors/BackOfficeController.cs | 14 +++++---- src/Umbraco.Web/Editors/BackOfficeModel.cs | 7 +++-- .../Editors/BackOfficePreviewModel.cs | 5 ++-- .../Editors/BackOfficeServerVariables.cs | 25 +++++++++++----- src/Umbraco.Web/Editors/PreviewController.cs | 8 +++-- .../HtmlHelperBackOfficeExtensions.cs | 5 ++-- .../Mvc/ModelBindingExceptionFilter.cs | 5 +++- .../Runtime/WebInitialComponent.cs | 13 +++++---- src/Umbraco.Web/Runtime/WebRuntime.cs | 7 +++-- ...eDirectoryBackOfficeUserPasswordChecker.cs | 15 +++++----- src/Umbraco.Web/Umbraco.Web.csproj | 4 +++ src/Umbraco.Web/UmbracoApplication.cs | 9 ++---- src/umbraco.sln | 12 ++++++-- 69 files changed, 374 insertions(+), 121 deletions(-) create mode 100644 src/Umbraco.Abstractions/IActiveDirectorySettings.cs create mode 100644 src/Umbraco.Abstractions/IExceptionFilterSettings.cs create mode 100644 src/Umbraco.Abstractions/IIndexCreatorSettings.cs rename src/{Umbraco.ModelsBuilder.Embedded/Configuration => Umbraco.Abstractions}/IModelsBuilderConfig.cs (87%) create mode 100644 src/Umbraco.Abstractions/INuCacheSettings.cs create mode 100644 src/Umbraco.Abstractions/IRuntimeSettings.cs create mode 100644 src/Umbraco.Abstractions/ITypeFinderSettings.cs rename src/{Umbraco.ModelsBuilder.Embedded/Configuration => Umbraco.Abstractions}/ModelsMode.cs (95%) create mode 100644 src/Umbraco.Abstractions/Umbraco.Abstractions.csproj create mode 100644 src/Umbraco.Configuration/ActiveDirectorySettings.cs create mode 100644 src/Umbraco.Configuration/ExceptionFilterSettings.cs create mode 100644 src/Umbraco.Configuration/IndexCreatorSettings.cs rename src/{Umbraco.ModelsBuilder.Embedded/Configuration => Umbraco.Configuration}/ModelsBuilderConfig.cs (96%) rename src/{Umbraco.ModelsBuilder.Embedded/Configuration => Umbraco.Configuration}/ModelsModeExtensions.cs (94%) create mode 100644 src/Umbraco.Configuration/NuCacheSettings.cs create mode 100644 src/Umbraco.Configuration/RuntimeSettings.cs create mode 100644 src/Umbraco.Configuration/TypeFinderSettings.cs diff --git a/src/Umbraco.Abstractions/IActiveDirectorySettings.cs b/src/Umbraco.Abstractions/IActiveDirectorySettings.cs new file mode 100644 index 0000000000..df0b8c723a --- /dev/null +++ b/src/Umbraco.Abstractions/IActiveDirectorySettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Abstractions +{ + public interface IActiveDirectorySettings + { + string ActiveDirectoryDomain { get; } + } +} diff --git a/src/Umbraco.Abstractions/IExceptionFilterSettings.cs b/src/Umbraco.Abstractions/IExceptionFilterSettings.cs new file mode 100644 index 0000000000..f36a8d4d18 --- /dev/null +++ b/src/Umbraco.Abstractions/IExceptionFilterSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Abstractions +{ + public interface IExceptionFilterSettings + { + bool Disabled { get; } + } +} diff --git a/src/Umbraco.Abstractions/IIndexCreatorSettings.cs b/src/Umbraco.Abstractions/IIndexCreatorSettings.cs new file mode 100644 index 0000000000..dbeb018736 --- /dev/null +++ b/src/Umbraco.Abstractions/IIndexCreatorSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Abstractions +{ + public interface IIndexCreatorSettings + { + string LuceneDirectoryFactory { get; } + } +} diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs b/src/Umbraco.Abstractions/IModelsBuilderConfig.cs similarity index 87% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs rename to src/Umbraco.Abstractions/IModelsBuilderConfig.cs index 7e96aec60e..5d6540e6cf 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/IModelsBuilderConfig.cs +++ b/src/Umbraco.Abstractions/IModelsBuilderConfig.cs @@ -1,4 +1,4 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Abstractions { public interface IModelsBuilderConfig { diff --git a/src/Umbraco.Abstractions/INuCacheSettings.cs b/src/Umbraco.Abstractions/INuCacheSettings.cs new file mode 100644 index 0000000000..f2a622da40 --- /dev/null +++ b/src/Umbraco.Abstractions/INuCacheSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Abstractions +{ + public interface INuCacheSettings + { + string BTreeBlockSize { get; } + } +} diff --git a/src/Umbraco.Abstractions/IRuntimeSettings.cs b/src/Umbraco.Abstractions/IRuntimeSettings.cs new file mode 100644 index 0000000000..1a6e1ae26a --- /dev/null +++ b/src/Umbraco.Abstractions/IRuntimeSettings.cs @@ -0,0 +1,8 @@ +namespace Umbraco.Abstractions +{ + public interface IRuntimeSettings + { + int? MaxQueryStringLength { get; } + int? MaxRequestLength { get; } + } +} diff --git a/src/Umbraco.Abstractions/ITypeFinderSettings.cs b/src/Umbraco.Abstractions/ITypeFinderSettings.cs new file mode 100644 index 0000000000..82d7922b9b --- /dev/null +++ b/src/Umbraco.Abstractions/ITypeFinderSettings.cs @@ -0,0 +1,7 @@ +namespace Umbraco.Abstractions +{ + public interface ITypeFinderSettings + { + string AssembliesAcceptingLoadExceptions { get; } + } +} diff --git a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs b/src/Umbraco.Abstractions/ModelsMode.cs similarity index 95% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs rename to src/Umbraco.Abstractions/ModelsMode.cs index e0286fdab1..3ab646897b 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsMode.cs +++ b/src/Umbraco.Abstractions/ModelsMode.cs @@ -1,4 +1,4 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Abstractions { /// /// Defines the models generation modes. diff --git a/src/Umbraco.Abstractions/Umbraco.Abstractions.csproj b/src/Umbraco.Abstractions/Umbraco.Abstractions.csproj new file mode 100644 index 0000000000..dbdcea46b6 --- /dev/null +++ b/src/Umbraco.Abstractions/Umbraco.Abstractions.csproj @@ -0,0 +1,7 @@ + + + + netstandard2.0 + + + diff --git a/src/Umbraco.Configuration/ActiveDirectorySettings.cs b/src/Umbraco.Configuration/ActiveDirectorySettings.cs new file mode 100644 index 0000000000..9498b4e8a2 --- /dev/null +++ b/src/Umbraco.Configuration/ActiveDirectorySettings.cs @@ -0,0 +1,15 @@ +using System.Configuration; +using Umbraco.Abstractions; + +namespace Umbraco.Configuration +{ + public class ActiveDirectory : IActiveDirectorySettings + { + public ActiveDirectory() + { + ActiveDirectoryDomain = ConfigurationManager.AppSettings["ActiveDirectoryDomain"]; + } + + public string ActiveDirectoryDomain { get; } + } +} diff --git a/src/Umbraco.Configuration/ExceptionFilterSettings.cs b/src/Umbraco.Configuration/ExceptionFilterSettings.cs new file mode 100644 index 0000000000..74d70281d9 --- /dev/null +++ b/src/Umbraco.Configuration/ExceptionFilterSettings.cs @@ -0,0 +1,18 @@ +using System.Configuration; +using Umbraco.Abstractions; + +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..242d62e8ce --- /dev/null +++ b/src/Umbraco.Configuration/IndexCreatorSettings.cs @@ -0,0 +1,15 @@ +using System.Configuration; +using Umbraco.Abstractions; + +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 96% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsBuilderConfig.cs rename to src/Umbraco.Configuration/ModelsBuilderConfig.cs index d0137ed2b2..d4e898ea2e 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.Abstractions; using Umbraco.Core; using Umbraco.Core.IO; -namespace Umbraco.ModelsBuilder.Embedded.Configuration +namespace Umbraco.Configuration { /// /// Represents the models builder configuration. @@ -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.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs b/src/Umbraco.Configuration/ModelsModeExtensions.cs similarity index 94% rename from src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs rename to src/Umbraco.Configuration/ModelsModeExtensions.cs index be638729ea..f6e718bc82 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Configuration/ModelsModeExtensions.cs +++ b/src/Umbraco.Configuration/ModelsModeExtensions.cs @@ -1,4 +1,6 @@ -namespace Umbraco.ModelsBuilder.Embedded.Configuration +using Umbraco.Abstractions; + +namespace Umbraco.Configuration { /// /// Provides extensions for the enumeration. diff --git a/src/Umbraco.Configuration/NuCacheSettings.cs b/src/Umbraco.Configuration/NuCacheSettings.cs new file mode 100644 index 0000000000..00d82c4e90 --- /dev/null +++ b/src/Umbraco.Configuration/NuCacheSettings.cs @@ -0,0 +1,14 @@ +using System.Configuration; +using Umbraco.Abstractions; + +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..cfaf32f45a --- /dev/null +++ b/src/Umbraco.Configuration/RuntimeSettings.cs @@ -0,0 +1,29 @@ +using System.Configuration; +using Umbraco.Abstractions; + +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..9c6341a726 --- /dev/null +++ b/src/Umbraco.Configuration/TypeFinderSettings.cs @@ -0,0 +1,17 @@ +using System.Configuration; +using Umbraco.Abstractions; +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.Configuration/Umbraco.Configuration.csproj b/src/Umbraco.Configuration/Umbraco.Configuration.csproj index 57fca1dfd6..2283672828 100644 --- a/src/Umbraco.Configuration/Umbraco.Configuration.csproj +++ b/src/Umbraco.Configuration/Umbraco.Configuration.csproj @@ -26,6 +26,7 @@ + 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/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.Examine.Lucene/LuceneIndexCreator.cs b/src/Umbraco.Examine.Lucene/LuceneIndexCreator.cs index ccc0248868..ce9abb1ad5 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.Abstractions; 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/Umbraco.Examine.Lucene.csproj b/src/Umbraco.Examine.Lucene/Umbraco.Examine.Lucene.csproj index 932d6d318b..83c63ac3e8 100644 --- a/src/Umbraco.Examine.Lucene/Umbraco.Examine.Lucene.csproj +++ b/src/Umbraco.Examine.Lucene/Umbraco.Examine.Lucene.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs b/src/Umbraco.Examine.Lucene/UmbracoIndexesCreator.cs index 173300a472..8b7e9583e5 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.Abstractions; 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.Infrastructure/Composing/CompositionExtensions/Configuration.cs b/src/Umbraco.Infrastructure/Composing/CompositionExtensions/Configuration.cs index 7169b93cb4..e14c73b5b7 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.Abstractions; +using Umbraco.Configuration; +using Umbraco.Core.Configuration.UmbracoSettings; namespace Umbraco.Core.Composing.CompositionExtensions { @@ -16,6 +18,14 @@ namespace Umbraco.Core.Composing.CompositionExtensions composition.RegisterUnique(factory => factory.GetInstance().RequestHandler); composition.RegisterUnique(factory => factory.GetInstance().Security); + composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); + return composition; } } diff --git a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj index 1db36a9c09..2da35392a0 100644 --- a/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj +++ b/src/Umbraco.Infrastructure/Umbraco.Infrastructure.csproj @@ -62,6 +62,8 @@ + + diff --git a/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs b/src/Umbraco.ModelsBuilder.Embedded/BackOffice/ContentTypeModelValidator.cs index 1fdb64c62a..387b71df5f 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.Abstractions; 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..6cae8d5d4b 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.Abstractions; 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..5e249425cc 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.Abstractions; +using Umbraco.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..9ff43be5ae 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.Abstractions; 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..e1f1c930b3 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.Abstractions; 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..1b4ec2ef08 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.Abstractions; +using Umbraco.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..e9ab4a5a14 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.Abstractions; +using Umbraco.Configuration; namespace Umbraco.ModelsBuilder.Embedded.Building { diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs index 8a3bc5a5b5..fdfffad578 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.Abstractions; 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..f8f1cb73bc 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.Abstractions; 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..d43f5e7b34 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.Abstractions; +using Umbraco.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..d0296996ea 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs @@ -1,12 +1,12 @@ using System.Linq; using System.Reflection; +using Umbraco.Abstractions; +using Umbraco.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 { diff --git a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs b/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs index d634547a49..df12f56dd9 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/ConfigsExtensions.cs @@ -1,5 +1,5 @@ -using Umbraco.Core.Configuration; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Abstractions; +using Umbraco.Core.Configuration; namespace Umbraco.ModelsBuilder.Embedded { diff --git a/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs b/src/Umbraco.ModelsBuilder.Embedded/LiveModelsProvider.cs index d4b4636563..16106f1384 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.Abstractions; +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..ed0e59b43f 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.Abstractions; namespace Umbraco.ModelsBuilder.Embedded { diff --git a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs index 5425c31c77..da08a5a07a 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.Abstractions; 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..7c426ae584 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.Abstractions; 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 83667bdbd8..f1514d9618 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj +++ b/src/Umbraco.ModelsBuilder.Embedded/Umbraco.ModelsBuilder.Embedded.csproj @@ -59,10 +59,6 @@ - - - - @@ -101,6 +97,14 @@ + + {D369E986-00D5-4F49-9B2D-E7A8F0C9EEDD} + Umbraco.Abstractions + + + {FBE7C065-DAC0-4025-A78B-63B24D3AB00B} + Umbraco.Configuration + {29aa69d9-b597-4395-8d42-43b1263c240a} Umbraco.Core @@ -123,6 +127,8 @@ 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..5bbe6020a9 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.Abstractions; 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 68b7ee596a..c0de66989a 100644 --- a/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.PublishedCache.NuCache/PublishedSnapshotService.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading; using CSharpTest.Net.Collections; using Newtonsoft.Json; +using Umbraco.Abstractions; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; @@ -53,6 +54,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 +92,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 +114,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 +201,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.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj b/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj index 75eeca268b..81fd3f9383 100644 --- a/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj +++ b/src/Umbraco.PublishedCache.NuCache/Umbraco.PublishedCache.NuCache.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs b/src/Umbraco.Tests/ModelsBuilder/BuilderTests.cs index 56d9d46e7d..f4afc1cb34 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.Abstractions; 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..8d6c0b4c6a 100644 --- a/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs +++ b/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs @@ -1,6 +1,6 @@ using System.Configuration; using NUnit.Framework; -using Umbraco.ModelsBuilder.Embedded.Configuration; +using Umbraco.Configuration; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.ModelsBuilder diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs index 1f153a0a5e..03819fb041 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs @@ -4,6 +4,7 @@ using System.Data; using System.Linq; using Moq; using NUnit.Framework; +using Umbraco.Abstractions; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; @@ -144,6 +145,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 +171,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..224f5f0eb6 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs @@ -4,6 +4,7 @@ using System.Data; using System.Linq; using Moq; using NUnit.Framework; +using Umbraco.Abstractions; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Configuration; @@ -185,6 +186,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 +211,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/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index 5b66d90722..d8983d8216 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,7 +134,7 @@ 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); @@ -156,12 +149,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())); + return new CustomDocumentController(Factory.GetInstance(), + umbracoContextAccessor, + Factory.GetInstance(), + Factory.GetInstance(), + Factory.GetInstance(), + new UmbracoHelper(Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of())); }), ShortStringHelper); handler.GetHandlerForRoute(httpContext.Request.RequestContext, frequest); diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 9cf6b3d773..841ee93c50 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Web.Routing; using Moq; using NUnit.Framework; +using Umbraco.Abstractions; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; @@ -86,6 +87,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 +109,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..3bc6e4c2eb 100644 --- a/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs +++ b/src/Umbraco.Tests/Services/ContentTypeServiceVariantsTests.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading; using Moq; using NUnit.Framework; +using Umbraco.Abstractions; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; @@ -59,6 +60,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 +82,8 @@ namespace Umbraco.Tests.Services typeFinder, hostingEnvironment, new MockShortStringHelper(), - IOHelper); + IOHelper, + settings); } public class LocalServerMessenger : ServerMessengerBase diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 9815c94728..4c1727305b 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -558,6 +558,10 @@ + + {D369E986-00D5-4F49-9B2D-E7A8F0C9EEDD} + Umbraco.Abstractions + {fbe7c065-dac0-4025-a78b-63b24d3ab00b} Umbraco.Configuration diff --git a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml index 1bdb7fae1b..59427b43c0 100644 --- a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml @@ -110,7 +110,7 @@ on-login="hideLoginScreen()"> - @Html.BareMinimumServerVariablesScript(Url, Url.Action("ExternalLogin", "BackOffice", new { area = ViewData.GetUmbracoPath() }), Model.Features, Model.GlobalSettings, Model.UmbracoVersion, Model.UmbracoSettingsSection, Model.IOHelper, Model.TreeCollection, Model.HttpContextAccessor, Model.HostingEnvironment) + @Html.BareMinimumServerVariablesScript(Url, Url.Action("ExternalLogin", "BackOffice", new { area = ViewData.GetUmbracoPath() }), Model.Features, Model.GlobalSettings, Model.UmbracoVersion, Model.UmbracoSettingsSection, Model.IOHelper, Model.TreeCollection, Model.HttpContextAccessor, Model.HostingEnvironment, Model.RuntimeSettings)