From 818e9f8b4cb8b2374b6efcb4e66cdc76c98cc2ec Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Thu, 15 Nov 2018 15:28:35 +0100 Subject: [PATCH 01/70] 3417 - don't use legacy action for create method --- src/Umbraco.Web/Trees/MacrosTreeController.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Umbraco.Web/Trees/MacrosTreeController.cs b/src/Umbraco.Web/Trees/MacrosTreeController.cs index 3f925eef8d..0649378aaa 100644 --- a/src/Umbraco.Web/Trees/MacrosTreeController.cs +++ b/src/Umbraco.Web/Trees/MacrosTreeController.cs @@ -59,11 +59,8 @@ namespace Umbraco.Web.Trees if (id == Constants.System.Root.ToInvariantString()) { //Create the normal create action - menu.Items.Add(Services.TextService, opensDialog: true) - //Since we haven't implemented anything for macros in angular, this needs to be converted to - //use the legacy format - .ConvertLegacyMenuItem(null, "initmacros", queryStrings.GetValue("application")); - + menu.Items.Add(Services.TextService); + //refresh action menu.Items.Add(new RefreshNode(Services.TextService, true)); From 8304ada5287f416b9495aa638dbe45523c31351d Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 11:39:33 +0100 Subject: [PATCH 02/70] #3417 added create view --- src/Umbraco.Web.UI.Client/src/views/macros/create.html | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/create.html diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/create.html b/src/Umbraco.Web.UI.Client/src/views/macros/create.html new file mode 100644 index 0000000000..337ebfdaa5 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/create.html @@ -0,0 +1,3 @@ +
+

Create view

+
From bb6848dd0372110be227bc9918c3ff45afc7b3ba Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 11:44:23 +0100 Subject: [PATCH 03/70] #3417 renamed existing macrocontroller to macro rendering controller --- src/Umbraco.Web/Editors/BackOfficeServerVariables.cs | 2 +- .../{MacroController.cs => MacroRenderingController.cs} | 4 ++-- src/Umbraco.Web/Umbraco.Web.csproj | 2 +- src/Umbraco.Web/umbraco.presentation/page.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) rename src/Umbraco.Web/Editors/{MacroController.cs => MacroRenderingController.cs} (97%) diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index 5bc01fa534..aab5f13479 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -169,7 +169,7 @@ namespace Umbraco.Web.Editors controller => controller.GetAllowedChildren(0)) }, { - "macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( + "macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( controller => controller.GetMacroParameters(0)) }, { diff --git a/src/Umbraco.Web/Editors/MacroController.cs b/src/Umbraco.Web/Editors/MacroRenderingController.cs similarity index 97% rename from src/Umbraco.Web/Editors/MacroController.cs rename to src/Umbraco.Web/Editors/MacroRenderingController.cs index 3c576befb9..e585f28c09 100644 --- a/src/Umbraco.Web/Editors/MacroController.cs +++ b/src/Umbraco.Web/Editors/MacroRenderingController.cs @@ -27,11 +27,11 @@ namespace Umbraco.Web.Editors /// Session, we don't want it to throw null reference exceptions. /// [PluginController("UmbracoApi")] - public class MacroController : UmbracoAuthorizedJsonController, IRequiresSessionState + public class MacroRenderingController : UmbracoAuthorizedJsonController, IRequiresSessionState { private readonly IVariationContextAccessor _variationContextAccessor; - public MacroController(IVariationContextAccessor variationContextAccessor) + public MacroRenderingController(IVariationContextAccessor variationContextAccessor) { _variationContextAccessor = variationContextAccessor; } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 17c2a54d81..16fbd6aa29 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -751,7 +751,7 @@ - + diff --git a/src/Umbraco.Web/umbraco.presentation/page.cs b/src/Umbraco.Web/umbraco.presentation/page.cs index 219e2101be..a2ccc1e094 100644 --- a/src/Umbraco.Web/umbraco.presentation/page.cs +++ b/src/Umbraco.Web/umbraco.presentation/page.cs @@ -102,7 +102,7 @@ namespace umbraco /// Initializes a new instance of the page for a content. /// /// The content. - /// This is for usage only. + /// This is for usage only. internal page(IContent content, IVariationContextAccessor variationContextAccessor) : this(new PagePublishedContent(content, variationContextAccessor)) { } From e1906113b969d728f6671aac15ee0e0749c545ac Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 12:31:58 +0100 Subject: [PATCH 04/70] #3417 added macro api controller and create method --- src/Umbraco.Web/Editors/MacrosController.cs | 64 +++++++++++++++++++++ src/Umbraco.Web/Umbraco.Web.csproj | 1 + 2 files changed, 65 insertions(+) create mode 100644 src/Umbraco.Web/Editors/MacrosController.cs diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs new file mode 100644 index 0000000000..0adada0a2b --- /dev/null +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -0,0 +1,64 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Web.Http; + +using Umbraco.Core; +using Umbraco.Core.Logging; +using Umbraco.Core.Models; +using Umbraco.Web.Mvc; +using Umbraco.Web.WebApi; +using Umbraco.Web.WebApi.Filters; + +using Constants = Umbraco.Core.Constants; + +namespace Umbraco.Web.Editors +{ + /// + /// The API controller used for editing dictionary items + /// + [PluginController("UmbracoApi")] + [UmbracoTreeAuthorize(Constants.Trees.Macros)] + public class MacrosController : BackOfficeNotificationsController + { + /// + /// Creates a new macro + /// + /// + /// The name. + /// + /// + /// The . + /// + [HttpPost] + public HttpResponseMessage Create(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return Request + .CreateNotificationValidationErrorResponse("Name can not be empty;"); + + var alias = name.ToSafeAlias(); + + var existingMacro = this.Services.MacroService.GetByAlias(alias); + + if (existingMacro != null) + { + return Request.CreateNotificationValidationErrorResponse("Macro with this name already exists"); + } + + try + { + var macro = new Macro { Alias = alias, Name = name }; + + this.Services.MacroService.Save(macro, this.Security.CurrentUser.Id); + + return Request.CreateResponse(HttpStatusCode.OK, macro.Id); + } + catch (Exception exception) + { + this.Logger.Error(exception, "Error creating macro"); + return Request.CreateNotificationValidationErrorResponse("Error creating dictionary item"); + } + } + } +} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 16fbd6aa29..7186835ba8 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -117,6 +117,7 @@ + From c61b5f947dae03e456e1ef0ba976153768f7476b Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 13:49:03 +0100 Subject: [PATCH 05/70] #3417 renamed server variable --- .../src/common/resources/macro.resource.js | 6 +++--- src/Umbraco.Web/Editors/BackOfficeServerVariables.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index dde887776e..07ad58bb78 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -24,7 +24,7 @@ function macroResource($q, $http, umbRequestHelper) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( - "macroApiBaseUrl", + "macroRenderingApiBaseUrl", "GetMacroParameters", [{ macroId: macroId }])), 'Failed to retrieve macro parameters for macro with id ' + macroId); @@ -48,7 +48,7 @@ function macroResource($q, $http, umbRequestHelper) { return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( - "macroApiBaseUrl", + "macroRenderingApiBaseUrl", "GetMacroResultAsHtmlForEditor"), { macroAlias: macroAlias, pageId: pageId, @@ -67,7 +67,7 @@ function macroResource($q, $http, umbRequestHelper) { return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( - "macroApiBaseUrl", + "macroRenderingApiBaseUrl", "CreatePartialViewMacroWithFile"), { virtualPath: virtualPath, filename: filename diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index aab5f13479..1550161ff0 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -169,7 +169,7 @@ namespace Umbraco.Web.Editors controller => controller.GetAllowedChildren(0)) }, { - "macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( + "macroRenderingApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( controller => controller.GetMacroParameters(0)) }, { From 03ce92212420d89f5a54f93631e8b35d796bee5c Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 17:10:53 +0100 Subject: [PATCH 06/70] #3417 register new api url in server variables --- src/Umbraco.Web/Editors/BackOfficeServerVariables.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index 1550161ff0..52cfc1bdec 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -172,6 +172,10 @@ namespace Umbraco.Web.Editors "macroRenderingApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( controller => controller.GetMacroParameters(0)) }, + { + "macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( + controller => controller.Create(null)) + }, { "authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( controller => controller.PostLogin(null)) From d7af9d9fca9ec0760dfa88fb7a710fe5359a4e36 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 4 Jan 2019 17:36:42 +0100 Subject: [PATCH 07/70] #3417 added method to macro resource to create a macro --- .../src/common/resources/macro.resource.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index 07ad58bb78..d0c6af2497 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -76,6 +76,19 @@ function macroResource($q, $http, umbRequestHelper) { 'Failed to create macro "' + filename + '"' ); + }, + + createMacro: function(name) { + return umbRequestHelper.resourcePromise( + $http.post( + umbRequestHelper.getApiUrl( + "macroApiBaseUrl", + "Create"), { + name : name, + } + ), + 'Failed to create macro "' + name + '"' + ); } }; } From 2ca7bb0cf3751077a35af9a61995df171e7274e9 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Mon, 7 Jan 2019 08:28:50 +0100 Subject: [PATCH 08/70] #3417 implemented create dialog for macros --- .../src/common/resources/macro.resource.js | 4 +- .../src/views/macros/create.html | 20 ++++++++- .../views/macros/macros.create.controller.js | 44 +++++++++++++++++++ src/Umbraco.Web/Editors/MacrosController.cs | 2 +- 4 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/macros.create.controller.js diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index d0c6af2497..9f22465757 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -83,9 +83,7 @@ function macroResource($q, $http, umbRequestHelper) { $http.post( umbRequestHelper.getApiUrl( "macroApiBaseUrl", - "Create"), { - name : name, - } + "Create?name=" + name) ), 'Failed to create macro "' + name + '"' ); diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/create.html b/src/Umbraco.Web.UI.Client/src/views/macros/create.html index 337ebfdaa5..a72cd373b2 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/create.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/create.html @@ -1,3 +1,19 @@ -
-

Create view

+
+ +
+
Create an item under {{currentNode.name}}
+
+ +
+
+ + + + + + +
+
diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.create.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.create.controller.js new file mode 100644 index 0000000000..1745b7b7f6 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.create.controller.js @@ -0,0 +1,44 @@ +/** + * @ngdoc controller + * @name Umbraco.Editors.Macros.CreateController + * @function + * + * @description + * The controller for creating macro items + */ +function MacrosCreateController($scope, $location, macroResource, navigationService, notificationsService, formHelper, appState) { + var vm = this; + + vm.itemKey = ""; + + function createItem() { + + var node = $scope.currentNode; + + macroResource.createMacro(vm.itemKey).then(function (data) { + navigationService.hideMenu(); + + // set new item as active in tree + var currPath = node.path ? node.path : "-1"; + navigationService.syncTree({ tree: "macros", path: currPath + "," + data, forceReload: true, activate: true }); + + // reset form state + formHelper.resetForm({ scope: $scope }); + + // navigate to edit view + var currentSection = appState.getSectionState("currentSection"); + $location.path("/" + currentSection + "/macros/edit/" + data); + + + }, function (err) { + if (err.data && err.data.message) { + notificationsService.error(err.data.message); + navigationService.hideMenu(); + } + }); + } + + vm.createItem = createItem; +} + +angular.module("umbraco").controller("Umbraco.Editors.Macros.CreateController", MacrosCreateController); diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 0adada0a2b..f1d949231e 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.Editors try { - var macro = new Macro { Alias = alias, Name = name }; + var macro = new Macro { Alias = alias, Name = name, MacroSource = string.Empty}; this.Services.MacroService.Save(macro, this.Security.CurrentUser.Id); From edd2adc8a00db041b2ee7f073969ea0b5c58bdb9 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Mon, 7 Jan 2019 08:31:06 +0100 Subject: [PATCH 09/70] #3417 changed path of macro tree item to use angular view instead of webform --- src/Umbraco.Web/Trees/MacrosTreeController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Umbraco.Web/Trees/MacrosTreeController.cs b/src/Umbraco.Web/Trees/MacrosTreeController.cs index 0649378aaa..f16cfe09d4 100644 --- a/src/Umbraco.Web/Trees/MacrosTreeController.cs +++ b/src/Umbraco.Web/Trees/MacrosTreeController.cs @@ -42,10 +42,7 @@ namespace Umbraco.Web.Trees queryStrings, macro.Name, "icon-settings-alt", - false, - //TODO: Rebuild the macro editor in angular, then we dont need to have this at all (which is just a path to the legacy editor) - "/" + queryStrings.GetValue("application") + "/framed/" + - Uri.EscapeDataString("/umbraco/developer/macros/editMacro.aspx?macroID=" + macro.Id))); + false)); } } From b9d779e921a116dd86a04df25ff7ce3252a3269b Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Tue, 8 Jan 2019 08:34:46 +0100 Subject: [PATCH 10/70] #3417 prototyped the UI for settings of the macro --- .../src/views/macros/edit.html | 31 +++++++ .../views/macros/macros.edit.controller.js | 87 +++++++++++++++++++ .../src/views/macros/views/parameters.html | 3 + .../src/views/macros/views/settings.html | 33 +++++++ 4 files changed, 154 insertions(+) create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/edit.html create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/edit.html b/src/Umbraco.Web.UI.Client/src/views/macros/edit.html new file mode 100644 index 0000000000..911dcf0c9e --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/edit.html @@ -0,0 +1,31 @@ +
+ + +
+ + + + + + + + + + + + + + + + +
+
diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js new file mode 100644 index 0000000000..ef65c77e1d --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js @@ -0,0 +1,87 @@ +/** + * @ngdoc controller + * @name Umbraco.Editors.Macros.EditController + * @function + * + * @description + * The controller for editing macros. + */ +function MacrosEditController($scope, $routeParams, macroResource, editorState, navigationService, dateHelper, userService, entityResource, formHelper, contentEditingHelper, localizationService) { + + var vm = this; + + vm.page = {}; + vm.page.loading = false; + vm.page.saveButtonState = "init"; + vm.page.menu = {} + + vm.save = saveMacro; + vm.toggle = toggleValue; + + init(); + + function init() { + vm.page.loading = true; + + + vm.page.navigation = [ + { + "name": "Settings", + "alias": "settings", + "icon": "icon-settings", + "view": "views/macros/views/settings.html", + "active": true + }, + { + "name": "Parameters", + "alias": "parameters", + "icon": "icon-list", + "view": "views/macros/views/parameters.html" + } + ]; + + vm.macro = { + "name": "Test macro", + "alias": "testMacro", + "id": 1, + "key": "unique key goes here", + "useInEditor": true, + "renderInEditor": false, + "cachePeriod": 2400, + "cacheByPage": true, + "cacheByUser": false, + "view" : "Second" + } + + vm.views = ['First', 'Second', 'Third']; + + vm.page.loading = false; + } + + function toggleValue(key) { + vm.macro[key] = !vm.macro[key]; + } + + function saveMacro() { + vm.page.saveButtonState = "busy"; + + if (formHelper.submitForm({ scope: $scope, statusMessage: "Saving..." })) { + console.log(vm.macro); + //relationTypeResource.save(vm.relationType).then(function (data) { + // formHelper.resetForm({ scope: $scope, notifications: data.notifications }); + // bindRelationType(data); + // vm.page.saveButtonState = "success"; + //}, function (error) { + // contentEditingHelper.handleSaveError({ + // redirectOnFailure: false, + // err: error + // }); + + // notificationsService.error(error.data.message); + // vm.page.saveButtonState = "error"; + //}); + } + } +} + +angular.module("umbraco").controller("Umbraco.Editors.Macros.EditController", MacrosEditController); diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html b/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html new file mode 100644 index 0000000000..6a10d4f80b --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html @@ -0,0 +1,3 @@ + + + diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html new file mode 100644 index 0000000000..51e83a9134 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 29390a3624bb275d829da5d12af0eeb424b3fb75 Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 11 Jan 2019 15:15:59 +0100 Subject: [PATCH 11/70] Fixes string to int conversion error --- .../PropertyEditors/MultiNodePickerConfigurationTreeSource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationTreeSource.cs b/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationTreeSource.cs index ffedf6c7dc..65115afc63 100644 --- a/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationTreeSource.cs +++ b/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationTreeSource.cs @@ -15,6 +15,6 @@ namespace Umbraco.Web.PropertyEditors public string StartNodeQuery {get;set;} [JsonProperty("id")] - public int? StartNodeId {get;set;} + public string StartNodeId {get;set;} } } From 8f41fe8d3840cccb5235ba632a6d69a2f8efbcc4 Mon Sep 17 00:00:00 2001 From: Robert Date: Fri, 11 Jan 2019 15:17:29 +0100 Subject: [PATCH 12/70] Fixes MNTP only being able to open contentPicker --- .../contentpicker/contentpicker.controller.js | 45 ++++++++++++------- .../contentpicker/contentpicker.html | 2 +- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js index af3ce50609..e084d7116a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js @@ -52,18 +52,18 @@ function contentPickerController($scope, entityResource, editorState, iconHelper } function startWatch() { - + //due to the way angular-sortable works, it needs to update a model, we don't want it to update renderModel since renderModel //is updated based on changes to model.value so if we bound angular-sortable to that and put a watch on it we'd end up in a //infinite loop. Instead we have a custom array model for angular-sortable and we'll watch that which we'll use to sync the model.value //which in turn will sync the renderModel. - $scope.$watchCollection("sortableModel", function(newVal, oldVal) { + $scope.$watchCollection("sortableModel", function (newVal, oldVal) { $scope.model.value = newVal.join(); }); //if the underlying model changes, update the view model, this ensures that the view is always consistent with the underlying //model if it changes (i.e. based on server updates, or if used in split view, etc...) - $scope.$watch("model.value", function(newVal, oldVal) { + $scope.$watch("model.value", function (newVal, oldVal) { if (newVal !== oldVal) { syncRenderModel(); } @@ -195,25 +195,38 @@ function contentPickerController($scope, entityResource, editorState, iconHelper } //dialog - $scope.openContentPicker = function () { - $scope.contentPicker = dialogOptions; + $scope.openCurrentPicker = function () { + $scope.currentPicker = dialogOptions; - $scope.contentPicker.submit = function (model) { + $scope.currentPicker.submit = function (model) { if (angular.isArray(model.selection)) { _.each(model.selection, function (item, i) { $scope.add(item); }); - angularHelper.getCurrentForm($scope).$setDirty(); + angularHelper.getCurrentForm($scope).$setDirty(); } angularHelper.getCurrentForm($scope).$setDirty(); editorService.close(); } - $scope.contentPicker.close = function () { + $scope.currentPicker.close = function () { editorService.close(); } - editorService.contentPicker($scope.contentPicker); + //open the correct editor based on the entity type + switch (entityType) { + case "Document": + editorService.contentPicker($scope.currentPicker); + break; + case "Media": + editorService.mediaPicker($scope.currentPicker); + break; + case "Member": + editorService.memberGroupPicker($scope.currentPicker); + break; + + default: + } }; @@ -256,7 +269,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper $scope.model.value = null; }; - $scope.openContentEditor = function (node)  { + $scope.openContentEditor = function (node) { var contentEditor = { id: node.id, submit: function (model) { @@ -296,7 +309,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper if (valueIds.length > 0) { //need to determine which items we already have loaded - var renderModelIds = _.map($scope.renderModel, function(d) { + var renderModelIds = _.map($scope.renderModel, function (d) { return $scope.model.config.idType === "udi" ? d.udi : d.id; }); @@ -313,11 +326,11 @@ function contentPickerController($scope, entityResource, editorState, iconHelper var missingIds = _.difference(valueIds, renderModelIds); if (missingIds.length > 0) { - return entityResource.getByIds(missingIds, entityType).then(function(data) { + return entityResource.getByIds(missingIds, entityType).then(function (data) { _.each(valueIds, - function(id, i) { - var entity = _.find(data, function(d) { + function (id, i) { + var entity = _.find(data, function (d) { return $scope.model.config.idType === "udi" ? (d.udi == id) : (d.id == id); }); @@ -330,7 +343,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper if (doValidation) { validate(); } - + setSortingState($scope.renderModel); return $q.when(true); }); @@ -342,7 +355,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper $scope.renderModel = []; for (var k = 0; k < valueIds.length; k++) { var id = valueIds[k]; - var found = _.find(current, function(d) { + var found = _.find(current, function (d) { return $scope.model.config.idType === "udi" ? (d.udi == id) : (d.id == id); }); if (found) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.html index 2f1303077c..a589cf8947 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.html @@ -22,7 +22,7 @@ Add From 2ce3249c5e99fc27656f2af84b014bec937ea412 Mon Sep 17 00:00:00 2001 From: Robert Date: Mon, 14 Jan 2019 13:23:00 +0100 Subject: [PATCH 13/70] Renaming variable to allow MNTP media selection --- .../src/common/services/tinymce.service.js | 2 +- .../linkpicker/linkpicker.controller.js | 2 +- .../mediapicker/mediapicker.controller.js | 24 +++++++++---------- .../prevalueeditors/imagepicker.controller.js | 2 +- .../grid/editors/media.controller.js | 2 +- .../markdowneditor.controller.js | 2 +- .../mediapicker/mediapicker.controller.js | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js b/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js index 3fc11f8225..97d939bac1 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js @@ -1316,7 +1316,7 @@ function tinyMceService($rootScope, $q, imageHelper, $locale, $http, $timeout, s startNodeId: userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0], startNodeIsVirtual: userData.startMediaIds.length !== 1, submit: function (model) { - self.insertMediaInEditor(args.editor, model.selectedImages[0]); + self.insertMediaInEditor(args.editor, model.selection[0]); editorService.close(); }, close: function () { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js index 81dfcfd5d3..4faa5fd03a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js @@ -118,7 +118,7 @@ angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", startNodeId: userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0], startNodeIsVirtual: userData.startMediaIds.length !== 1, submit: function (model) { - var media = model.selectedImages[0]; + var media = model.selection[0]; $scope.model.target.id = media.id; $scope.model.target.udi = media.udi; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js index a274c25287..7b3d13937f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js @@ -41,7 +41,7 @@ angular.module("umbraco") $scope.maxFileSize = umbracoSettings.maxFileSize + "KB"; - $scope.model.selectedImages = []; + $scope.model.selection = []; $scope.acceptedMediatypes = []; mediaTypeHelper.getAllowedImagetypes($scope.startNodeId) @@ -145,7 +145,7 @@ angular.module("umbraco") $scope.gotoFolder = function(folder) { if (!$scope.multiPicker) { - deselectAllImages($scope.model.selectedImages); + deselectAllImages($scope.model.selection); } if (!folder) { @@ -212,19 +212,19 @@ angular.module("umbraco") function selectImage(image) { if (image.selected) { - for (var i = 0; $scope.model.selectedImages.length > i; i++) { - var imageInSelection = $scope.model.selectedImages[i]; + for (var i = 0; $scope.model.selection.length > i; i++) { + var imageInSelection = $scope.model.selection[i]; if (image.key === imageInSelection.key) { image.selected = false; - $scope.model.selectedImages.splice(i, 1); + $scope.model.selection.splice(i, 1); } } } else { if (!$scope.multiPicker) { - deselectAllImages($scope.model.selectedImages); + deselectAllImages($scope.model.selection); } image.selected = true; - $scope.model.selectedImages.push(image); + $scope.model.selection.push(image); } } @@ -238,7 +238,7 @@ angular.module("umbraco") $scope.onUploadComplete = function(files) { $scope.gotoFolder($scope.currentFolder).then(function() { - if (files.length === 1 && $scope.model.selectedImages.length === 0) { + if (files.length === 1 && $scope.model.selection.length === 0) { var image = $scope.images[$scope.images.length - 1]; $scope.target = image; $scope.target.url = mediaHelper.resolveFile(image); @@ -275,7 +275,7 @@ angular.module("umbraco") $scope.mediaPickerDetailsOverlay.show = true; $scope.mediaPickerDetailsOverlay.submit = function(model) { - $scope.model.selectedImages.push($scope.target); + $scope.model.selection.push($scope.target); $scope.model.submit($scope.model); $scope.mediaPickerDetailsOverlay.show = false; @@ -384,11 +384,11 @@ angular.module("umbraco") var folderImage = $scope.images[folderImageIndex]; var imageIsSelected = false; - if ($scope.model && angular.isArray($scope.model.selectedImages)) { + if ($scope.model && angular.isArray($scope.model.selection)) { for (var selectedImageIndex = 0; - selectedImageIndex < $scope.model.selectedImages.length; + selectedImageIndex < $scope.model.selection.length; selectedImageIndex++) { - var selectedImage = $scope.model.selectedImages[selectedImageIndex]; + var selectedImage = $scope.model.selection[selectedImageIndex]; if (folderImage.key === selectedImage.key) { imageIsSelected = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/imagepicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/imagepicker.controller.js index 6e7071a7e4..fc3da3510e 100644 --- a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/imagepicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/imagepicker.controller.js @@ -7,7 +7,7 @@ function imageFilePickerController($scope) { onlyImages: true, show: true, submit: function (model) { - $scope.model.value = model.selectedImages[0].image; + $scope.model.value = model.selection[0].image; $scope.mediaPickerOverlay.show = false; $scope.mediaPickerOverlay = null; }, diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js index c240d6b37d..e267133cf4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js @@ -27,7 +27,7 @@ angular.module("umbraco") disableFolderSelect: true, onlyImages: true, submit: function(model) { - var selectedImage = model.selectedImages[0]; + var selectedImage = model.selection[0]; $scope.control.value = { focalPoint: selectedImage.focalPoint, diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/markdowneditor/markdowneditor.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/markdowneditor/markdowneditor.controller.js index b3c014f54a..67a5630909 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/markdowneditor/markdowneditor.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/markdowneditor/markdowneditor.controller.js @@ -16,7 +16,7 @@ function MarkdownEditorController($scope, $element, assetsService, editorService var mediaPicker = { disableFolderSelect: true, submit: function(model) { - var selectedImagePath = model.selectedImages[0].image; + var selectedImagePath = model.selection[0].image; callback(selectedImagePath); editorService.close(); }, diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js index 361354c524..bac8eb903a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js @@ -176,7 +176,7 @@ angular.module('umbraco').controller("Umbraco.PropertyEditors.MediaPickerControl editorService.close(); - _.each(model.selectedImages, function (media, i) { + _.each(model.selection, function (media, i) { // if there is no thumbnail, try getting one if the media is not a placeholder item if (!media.thumbnail && media.id && media.metaData) { media.thumbnail = mediaHelper.resolveFileFromEntity(media, true); From 1ac8bbc570ab4a3a9d7f5ee24c66f0ad8a5dee85 Mon Sep 17 00:00:00 2001 From: Robert Date: Mon, 14 Jan 2019 13:23:57 +0100 Subject: [PATCH 14/70] Fixes MNTP member selection tree --- .../propertyeditors/contentpicker/contentpicker.controller.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js index e084d7116a..b72d81f16d 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js @@ -222,7 +222,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper editorService.mediaPicker($scope.currentPicker); break; case "Member": - editorService.memberGroupPicker($scope.currentPicker); + editorService.treePicker($scope.currentPicker); break; default: From 8e4090fb84d40b8aa3efa3d45119b4c8e3fa9692 Mon Sep 17 00:00:00 2001 From: Robert Date: Mon, 14 Jan 2019 14:00:17 +0100 Subject: [PATCH 15/70] Added proper memberPicker in the editorService --- .../src/common/services/editor.service.js | 26 ++++++++++++++++++- .../contentpicker/contentpicker.controller.js | 2 +- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js b/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js index 0d6432b01f..6cdb8fd0f3 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js @@ -748,6 +748,29 @@ When building a custom infinite editor view you can use the same components as a open(editor); } + /** + * @ngdoc method + * @name umbraco.services.editorService#memberPicker + * @methodOf umbraco.services.editorService + * + * @description + * Opens a member picker in infinite editing, the submit callback returns an array of selected items + * + * @param {Object} editor rendering options + * @param {Boolean} editor.multiPicker Pick one or multiple items + * @param {Function} editor.submit Callback function when the submit button is clicked. Returns the editor model object + * @param {Function} editor.close Callback function when the close button is clicked. + * + * @returns {Object} editor object + */ + function memberPicker(editor) { + editor.view = "views/common/infiniteeditors/treepicker/treepicker.html"; + editor.size = "small"; + editor.section = "member"; + editor.treeAlias = "member"; + open(editor); + } + /////////////////////// /** @@ -824,7 +847,8 @@ When building a custom infinite editor view you can use the same components as a userPicker: userPicker, itemPicker: itemPicker, macroPicker: macroPicker, - memberGroupPicker: memberGroupPicker + memberGroupPicker: memberGroupPicker, + memberPicker: memberPicker }; return service; diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js index b72d81f16d..37a97e928c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js @@ -222,7 +222,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper editorService.mediaPicker($scope.currentPicker); break; case "Member": - editorService.treePicker($scope.currentPicker); + editorService.memberPicker($scope.currentPicker); break; default: From 2e782a4f114c44184f5076a07fbe3c94b5104524 Mon Sep 17 00:00:00 2001 From: Robert Date: Tue, 15 Jan 2019 15:10:50 +0100 Subject: [PATCH 16/70] Mapping IsContainer into AdditionalData using IEntitySlim to EntityBasic mapper --- src/Umbraco.Web/Editors/EntityController.cs | 2 +- src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index 993489855f..500b25ab2e 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -769,7 +769,7 @@ namespace Umbraco.Web.Editors { throw new HttpResponseException(HttpStatusCode.NotFound); } - return Mapper.Map(found); + return Mapper.Map(found); } //now we need to convert the unknown ones switch (entityType) diff --git a/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs index 178027857c..ff7fcfc0b0 100644 --- a/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs @@ -16,7 +16,7 @@ namespace Umbraco.Web.Models.Mapping { internal class EntityMapperProfile : Profile { - private static string GetContentTypeIcon(EntitySlim entity) + private static string GetContentTypeIcon(IEntitySlim entity) => entity is ContentEntitySlim contentEntity ? contentEntity.ContentTypeIcon : null; public EntityMapperProfile() @@ -24,7 +24,7 @@ namespace Umbraco.Web.Models.Mapping // create, capture, cache var contentTypeUdiResolver = new ContentTypeUdiResolver(); - CreateMap() + CreateMap() .ForMember(dest => dest.Name, opt => opt.ResolveUsing()) .ForMember(dest => dest.Udi, opt => opt.MapFrom(src => Udi.Create(ObjectTypes.GetUdiType(src.NodeObjectType), src.Key))) .ForMember(dest => dest.Icon, opt => opt.MapFrom(src => GetContentTypeIcon(src))) @@ -36,6 +36,8 @@ namespace Umbraco.Web.Models.Mapping { dest.Icon = "icon-user"; } + + dest.AdditionalData.Add("IsContainer", src.IsContainer); }); CreateMap() @@ -186,9 +188,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Resolves the name for a content item/content variant /// - private class NameResolver : IValueResolver + private class NameResolver : IValueResolver { - public string Resolve(EntitySlim source, EntityBasic destination, string destMember, ResolutionContext context) + public string Resolve(IEntitySlim source, EntityBasic destination, string destMember, ResolutionContext context) { if (!(source is DocumentEntitySlim doc)) return source.Name; From 5ebf51e6df64419c6676051624237a6a7ca8bcc7 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Wed, 16 Jan 2019 08:40:00 +0100 Subject: [PATCH 17/70] #3417 added mockup of parameter editing --- .../src/views/macros/edit.html | 5 +- .../infiniteeditors/parameter.controller.js | 27 +++++++ .../macros/infiniteeditors/parameter.html | 58 ++++++++++++++ .../views/macros/macros.edit.controller.js | 30 ++++++- .../views/macro.parameters.controller.js | 78 +++++++++++++++++++ .../src/views/macros/views/parameters.html | 31 +++++++- 6 files changed, 223 insertions(+), 6 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.controller.js create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html create mode 100644 src/Umbraco.Web.UI.Client/src/views/macros/views/macro.parameters.controller.js diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/edit.html b/src/Umbraco.Web.UI.Client/src/views/macros/edit.html index 911dcf0c9e..ddb5f98781 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/edit.html @@ -1,7 +1,6 @@ -
- - +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ' + + + + +
diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js index ef65c77e1d..81c699a05f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js @@ -6,7 +6,7 @@ * @description * The controller for editing macros. */ -function MacrosEditController($scope, $routeParams, macroResource, editorState, navigationService, dateHelper, userService, entityResource, formHelper, contentEditingHelper, localizationService) { +function MacrosEditController($scope, $routeParams, macroResource, editorState, navigationService, dateHelper, userService, entityResource, formHelper, contentEditingHelper, localizationService, angularHelper) { var vm = this; @@ -17,6 +17,7 @@ function MacrosEditController($scope, $routeParams, macroResource, editorState, vm.save = saveMacro; vm.toggle = toggleValue; + init(); @@ -50,11 +51,25 @@ function MacrosEditController($scope, $routeParams, macroResource, editorState, "cachePeriod": 2400, "cacheByPage": true, "cacheByUser": false, - "view" : "Second" + "view": "Second", + "parameters": [ + { + "key": "title", + "label": "Label", + "editor": "editor" + }, + { + "key": "link", + "label": "Link", + "editor": "Link picker" + } + ] } vm.views = ['First', 'Second', 'Third']; + vm.parameterEditors = ['editor', 'Link picker', 'Image picker']; + vm.page.loading = false; } @@ -82,6 +97,17 @@ function MacrosEditController($scope, $routeParams, macroResource, editorState, //}); } } + + function setFormDirty() { + var currentForm = angularHelper.getCurrentForm($scope); + + if (currentForm) { + + currentForm.$setDirty(); + } + } + + vm.setDirty = setFormDirty; } angular.module("umbraco").controller("Umbraco.Editors.Macros.EditController", MacrosEditController); diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/macro.parameters.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/views/macro.parameters.controller.js new file mode 100644 index 0000000000..851b537c3b --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/macro.parameters.controller.js @@ -0,0 +1,78 @@ +/** + * @ngdoc controller + * @name Umbraco.Editors.Macros.ParametersController + * @function + * + * @description + * The controller for editing macros parameters + */ +function MacrosParametersController($scope, editorService) { + + $scope.sortableOptions = { + axis: 'y', + containment: 'parent', + cursor: 'move', + items: 'div.umb-stylesheet-rules__listitem', + handle: '.handle', + tolerance: 'pointer', + update: function (e, ui) { + $scope.model.setDirty(); + } + }; + + + $scope.remove = function (parameter, evt) { + evt.preventDefault(); + + $scope.model.macro.parameters = _.without($scope.model.macro.parameters, parameter); + $scope.model.setDirty(); + } + + $scope.add = function (evt) { + evt.preventDefault(); + + openOverlay({}, 'Add parameter', (newParameter) => { + if (!$scope.model.macro.parameters) { + $scope.model.macro.parameters = []; + } + $scope.model.macro.parameters.push(newParameter); + $scope.model.setDirty(); + }); + } + + $scope.edit = function (parameter, evt) { + evt.preventDefault(); + + openOverlay(parameter,'Edit parameter', (newParameter) => { + parameter.key = newParameter.key; + parameter.label = newParameter.label; + parameter.editor = newParameter.editor; + parameter.editor = newParameter.editor; + $scope.model.setDirty(); + }); + } + + function openOverlay(parameter, title, onSubmit) { + + const ruleDialog = { + title: title, + parameter: _.clone(parameter), + editors : $scope.model.parameterEditors, + view: "views/macros/infiniteeditors/parameter.html", + size: "small", + submit: function (model) { + onSubmit(model.parameter); + editorService.close(); + }, + close: function () { + editorService.close(); + } + }; + + editorService.open(ruleDialog); + + } + +} + +angular.module("umbraco").controller("Umbraco.Editors.Macros.ParametersController", MacrosParametersController); diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html b/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html index 6a10d4f80b..91231a49b7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/parameters.html @@ -1,3 +1,32 @@  - + +
+
+
Parameters
+ Define the parameters hat should be available when using his macro +
+
+
+
+
+ +
+ {{parameter.label}} +
+
+ Remove +
+
+
+ + +
+
+
+ +
From 31545db91ed33ad59a4049a91792d11edbee02a6 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 16 Jan 2019 19:29:42 +1100 Subject: [PATCH 18/70] Fixes routing with the packages section --- src/Umbraco.Web.UI.Client/src/routes.js | 13 ++++++++--- .../src/views/packages/edit.controller.js | 4 ++-- .../src/views/packages/overview.controller.js | 22 +++++++++---------- .../Trees/PackagesTreeController.cs | 2 +- 4 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/routes.js b/src/Umbraco.Web.UI.Client/src/routes.js index 2d8ad46371..64bddb16e2 100644 --- a/src/Umbraco.Web.UI.Client/src/routes.js +++ b/src/Umbraco.Web.UI.Client/src/routes.js @@ -149,14 +149,21 @@ app.config(function ($routeProvider) { .when('/:section/:tree/:method?', { //This allows us to dynamically change the template for this route since you cannot inject services into the templateUrl method. template: "
", - //This controller will execute for this route, then we replace the template dynamnically based on the current tree. - controller: function ($scope, $route, $routeParams, treeService) { + //This controller will execute for this route, then we replace the template dynamically based on the current tree. + controller: function ($scope, $routeParams, treeService) { if (!$routeParams.method) { $scope.templateUrl = "views/common/dashboard.html"; + return; } - // Here we need to figure out if this route is for a package tree and if so then we need + //special case for the package section + if ($routeParams.section.toLowerCase() === "packages" && $routeParams.tree.toLowerCase() === "packages" && $routeParams.method !== "edit") { + $scope.templateUrl = "views/packages/overview.html"; + return; + } + + // Here we need to figure out if this route is for a user's package tree and if so then we need // to change it's convention view path to: // /App_Plugins/{mypackage}/backoffice/{treetype}/{method}.html diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index 4afe62786e..29d871c0b1 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -130,7 +130,7 @@ } function back() { - $location.path("packages/packages/overview").search('create', null);; + $location.path("packages/packages/created").search("create", null); } function createOrUpdatePackage(editPackageForm) { @@ -148,7 +148,7 @@ if (create) { //if we are creating, then redirect to the correct url and reload - $location.path("packages/packages/edit/" + vm.package.id).search("subview", "created").search("create", null); + $location.path("packages/packages/edit/" + vm.package.id).search("create", null); //don't add a browser history for this $location.replace(); } diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js index ccd86c6f6c..59fa79dc26 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function PackagesOverviewController($scope, $location, localStorageService) { + function PackagesOverviewController($scope, $location, $routeParams, localStorageService) { //Hack! // if there is a cookie value for packageInstallUri then we need to redirect there, @@ -10,7 +10,7 @@ // we will refresh and then navigate there. let installPackageUri = localStorageService.get("packageInstallUri"); - let packageUri = $location.search().subview; + let packageUri = $routeParams.method; if (installPackageUri) { localStorageService.remove("packageInstallUri"); @@ -33,10 +33,10 @@ "name": "Packages", "icon": "icon-cloud", "view": "views/packages/views/repo.html", - "active": !packageUri || packageUri === "navigation", + "active": !packageUri || packageUri === "repo", "alias": "umbPackages", - "action": function() { - $location.search("subview", "navigation"); + "action": function () { + $location.path("/packages/packages/repo"); } }, { @@ -45,8 +45,8 @@ "view": "views/packages/views/installed.html", "active": packageUri === "installed", "alias": "umbInstalled", - "action": function() { - $location.search("subview", "installed"); + "action": function () { + $location.path("/packages/packages/installed"); } }, { @@ -55,8 +55,8 @@ "view": "views/packages/views/install-local.html", "active": packageUri === "local", "alias": "umbInstallLocal", - "action": function() { - $location.search("subview", "local"); + "action": function () { + $location.path("/packages/packages/local"); } }, { @@ -65,8 +65,8 @@ "view": "views/packages/views/created.html", "active": packageUri === "created", "alias": "umbCreatedPackages", - "action": function() { - $location.search("subview", "created"); + "action": function () { + $location.path("/packages/packages/created"); } } ]; diff --git a/src/Umbraco.Web/Trees/PackagesTreeController.cs b/src/Umbraco.Web/Trees/PackagesTreeController.cs index fdc5294aa2..68b67f9fe2 100644 --- a/src/Umbraco.Web/Trees/PackagesTreeController.cs +++ b/src/Umbraco.Web/Trees/PackagesTreeController.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Trees var root = base.CreateRootNode(queryStrings); //this will load in a custom UI instead of the dashboard for the root node - root.RoutePath = $"{Constants.Applications.Packages}/{Constants.Trees.Packages}/overview"; + root.RoutePath = $"{Constants.Applications.Packages}/{Constants.Trees.Packages}/repo"; root.Icon = "icon-box"; root.HasChildren = false; From 572c6989ceadb4edccfad2238ca1258510be4d1e Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 16 Jan 2019 19:30:07 +1100 Subject: [PATCH 19/70] Changes control to view for the package view --- .../Models/Packaging/CompiledPackage.cs | 2 +- .../Models/Packaging/IPackageInfo.cs | 7 +++- .../Models/Packaging/PackageDefinition.cs | 41 +++---------------- .../Packaging/CompiledPackageXmlParser.cs | 2 +- .../Packaging/PackageDefinitionXmlParser.cs | 4 +- .../Packaging/PackagesRepository.cs | 6 +-- .../src/views/packages/edit.controller.js | 14 +++---- .../src/views/packages/edit.html | 6 +-- .../Editors/PackageInstallController.cs | 7 ++-- 9 files changed, 32 insertions(+), 57 deletions(-) diff --git a/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs b/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs index a852fcc997..f14fe47bfe 100644 --- a/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs +++ b/src/Umbraco.Core/Models/Packaging/CompiledPackage.cs @@ -23,7 +23,7 @@ namespace Umbraco.Core.Models.Packaging public string Author { get; set; } public string AuthorUrl { get; set; } public string Readme { get; set; } - public string Control { get; set; } + public string PackageView { get; set; } public string IconUrl { get; set; } public string Actions { get; set; } //fixme: Should we make this strongly typed to IEnumerable ? diff --git a/src/Umbraco.Core/Models/Packaging/IPackageInfo.cs b/src/Umbraco.Core/Models/Packaging/IPackageInfo.cs index 8722ee7811..eea56549f1 100644 --- a/src/Umbraco.Core/Models/Packaging/IPackageInfo.cs +++ b/src/Umbraco.Core/Models/Packaging/IPackageInfo.cs @@ -13,7 +13,12 @@ namespace Umbraco.Core.Models.Packaging string Author { get; } string AuthorUrl { get; } string Readme { get; } - string Control { get; } //fixme - this needs to be an angular view + + /// + /// This is the angular view path that will be loaded when the package installs + /// + string PackageView { get; } + string IconUrl { get; } } } diff --git a/src/Umbraco.Core/Models/Packaging/PackageDefinition.cs b/src/Umbraco.Core/Models/Packaging/PackageDefinition.cs index c068c57b08..8c0ef79d0b 100644 --- a/src/Umbraco.Core/Models/Packaging/PackageDefinition.cs +++ b/src/Umbraco.Core/Models/Packaging/PackageDefinition.cs @@ -25,7 +25,7 @@ namespace Umbraco.Core.Models.Packaging Actions = compiled.Actions, Author = compiled.Author, AuthorUrl = compiled.AuthorUrl, - Control = compiled.Control, + PackageView = compiled.PackageView, IconUrl = compiled.IconUrl, License = compiled.License, LicenseUrl = compiled.LicenseUrl, @@ -115,9 +115,9 @@ namespace Umbraco.Core.Models.Packaging [DataMember(Name = "files")] public IList Files { get; set; } = new List(); - //fixme: Change this to angular view - [DataMember(Name = "loadControl")] - public string Control { get; set; } = string.Empty; + /// + [DataMember(Name = "packageView")] + public string PackageView { get; set; } = string.Empty; [DataMember(Name = "actions")] public string Actions { get; set; } = ""; @@ -127,38 +127,7 @@ namespace Umbraco.Core.Models.Packaging [DataMember(Name = "iconUrl")] public string IconUrl { get; set; } = string.Empty; - - public PackageDefinition Clone() - { - return new PackageDefinition - { - Id = Id, - PackagePath = PackagePath, - Name = Name, - Files = new List(Files), - UmbracoVersion = (Version) UmbracoVersion.Clone(), - Version = Version, - Url = Url, - Readme = Readme, - AuthorUrl = AuthorUrl, - Author = Author, - LicenseUrl = LicenseUrl, - Actions = Actions, - PackageId = PackageId, - Control = Control, - DataTypes = new List(DataTypes), - IconUrl = IconUrl, - License = License, - Templates = new List(Templates), - Languages = new List(Languages), - Macros = new List(Macros), - Stylesheets = new List(Stylesheets), - DocumentTypes = new List(DocumentTypes), - DictionaryItems = new List(DictionaryItems), - ContentNodeId = ContentNodeId, - ContentLoadChildNodes = ContentLoadChildNodes - }; - } + } diff --git a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs index 0d533cfbc2..7f62f4fd27 100644 --- a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs +++ b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs @@ -51,7 +51,7 @@ namespace Umbraco.Core.Packaging IconUrl = package.Element("iconUrl")?.Value, UmbracoVersion = new Version((int)requirements.Element("major"), (int)requirements.Element("minor"), (int)requirements.Element("patch")), UmbracoVersionRequirementsType = requirements.AttributeValue("type").IsNullOrWhiteSpace() ? RequirementsType.Legacy : Enum.Parse(requirements.AttributeValue("type"), true), - Control = package.Element("control")?.Value, + PackageView = package.Element("view")?.Value, Actions = xml.Root.Element("Actions")?.ToString(SaveOptions.None) ?? "", //take the entire outer xml value Files = xml.Root.Element("files")?.Elements("file")?.Select(CompiledPackageFile.Create).ToList() ?? new List(), Macros = xml.Root.Element("Macros")?.Elements("macro") ?? Enumerable.Empty(), diff --git a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs index 45e6fd9845..00255fa43a 100644 --- a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs +++ b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs @@ -50,7 +50,7 @@ namespace Umbraco.Core.Packaging DictionaryItems = xml.Element("dictionaryitems")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), DataTypes = xml.Element("datatypes")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), Files = xml.Element("files")?.Elements("file").Select(x => x.Value).ToList() ?? new List(), - Control = xml.Element("loadcontrol")?.Value ?? string.Empty + PackageView = xml.Element("view")?.Value ?? string.Empty }; return retVal; @@ -101,7 +101,7 @@ namespace Umbraco.Core.Packaging new XElement("files", (def.Files ?? Array.Empty()).Where(x => !x.IsNullOrWhiteSpace()).Select(x => new XElement("file", x))), new XElement("languages", string.Join(",", def.Languages ?? Array.Empty())), new XElement("dictionaryitems", string.Join(",", def.DictionaryItems ?? Array.Empty())), - new XElement("loadcontrol", def.Control ?? string.Empty)); //fixme: no more loadcontrol, needs to be an angular view + new XElement("view", def.PackageView ?? string.Empty)); return packageXml; } diff --git a/src/Umbraco.Core/Packaging/PackagesRepository.cs b/src/Umbraco.Core/Packaging/PackagesRepository.cs index 249d02a320..5531e05705 100644 --- a/src/Umbraco.Core/Packaging/PackagesRepository.cs +++ b/src/Umbraco.Core/Packaging/PackagesRepository.cs @@ -180,10 +180,10 @@ namespace Umbraco.Core.Packaging AppendFileToManifest(fileName, temporaryPath, filesXml); //Load control on install... - if (!string.IsNullOrEmpty(definition.Control)) + if (!string.IsNullOrEmpty(definition.PackageView)) { - var control = new XElement("control", definition.Control); - AppendFileToManifest(definition.Control, temporaryPath, filesXml); + var control = new XElement("view", definition.PackageView); + AppendFileToManifest(definition.PackageView, temporaryPath, filesXml); manifestRoot.Add(control); } diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index 29d871c0b1..ca20b33a3e 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -19,8 +19,8 @@ vm.openContentPicker = openContentPicker; vm.openFilePicker = openFilePicker; vm.removeFile = removeFile; - vm.openControlPicker = openControlPicker; - vm.removeControl = removeControl; + vm.openViewPicker = openViewPicker; + vm.removePackageView = removePackageView; vm.downloadFile = downloadFile; const packageId = $routeParams.id; @@ -220,16 +220,16 @@ vm.package.files.splice(index, 1); } - function openControlPicker() { + function openViewPicker() { const controlPicker = { - title: "Select control", + title: "Select view", section: "settings", treeAlias: "files", entityType: "file", onlyInitialized: false, select: function(node) { const id = unescape(node.id); - vm.package.loadControl = id; + vm.package.packageView = id; editorService.close(); }, close: function() { @@ -239,8 +239,8 @@ editorService.treePicker(controlPicker); } - function removeControl() { - vm.package.loadControl = null; + function removePackageView() { + vm.package.packageView = null; } onInit(); diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html index 8ed1a43e8a..5163fadfb5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html @@ -264,14 +264,14 @@ name="vm.package.loadControl" allow-edit="true" allow-remove="true" - on-edit="vm.openControlPicker()" - on-remove="vm.removeControl()"> + on-edit="vm.openViewPicker()" + on-remove="vm.removePackageView()"> Add diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index dd7c4302c5..544a871720 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -376,10 +376,11 @@ namespace Umbraco.Web.Editors zipFile.Delete(); var redirectUrl = ""; - if (packageInfo.Control.IsNullOrWhiteSpace() == false) + if (!packageInfo.PackageView.IsNullOrWhiteSpace()) { - //fixme: this needs to be replaced with an angular view the installer.aspx no longer exists. - //redirectUrl = string.Format("/developer/framed/{0}", + //fixme! + throw new NotImplementedException(); + //redirectUrl = string.Format("/packages/framed/{0}", // Uri.EscapeDataString( // string.Format("/umbraco/developer/Packages/installer.aspx?installing=custominstaller&dir={0}&pId={1}&customControl={2}&customUrl={3}", tempDir, model.Id, ins.Control, ins.Url))); } From c4418185ec2e83d48c335d1ca6860b27f427dba5 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 16 Jan 2019 21:27:14 +1100 Subject: [PATCH 20/70] Gets the angular view loading and allows navigating back to the view, cleans up non used lang keys --- .../Packaging/CompiledPackageXmlParser.cs | 2 +- .../Packaging/PackageDefinitionXmlParser.cs | 8 +- .../Packaging/PackagesRepository.cs | 86 +++++++++---------- .../mocks/services/localization.mocks.js | 7 -- .../src/common/resources/package.resource.js | 12 ++- src/Umbraco.Web.UI.Client/src/routes.js | 3 +- .../src/views/packages/edit.html | 10 +-- .../src/views/packages/options.controller.js | 43 ++++++++++ .../src/views/packages/options.html | 40 +++++++++ .../src/views/packages/overview.controller.js | 3 +- .../packages/views/installed.controller.js | 5 ++ .../src/views/packages/views/installed.html | 19 ++-- src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/da.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/de.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/en.xml | 7 -- .../Umbraco/config/lang/en_us.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/es.xml | 8 -- src/Umbraco.Web.UI/Umbraco/config/lang/fr.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/he.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/it.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/ja.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/ko.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/nl.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/pl.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/pt.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/ru.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/sv.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/tr.xml | 7 -- src/Umbraco.Web.UI/Umbraco/config/lang/zh.xml | 7 -- .../Umbraco/config/lang/zh_tw.xml | 7 -- src/Umbraco.Web.UI/umbraco/config/lang/nb.xml | 7 -- .../umbraco/config/lang/zh_tw.xml | 7 -- src/Umbraco.Web/Editors/PackageController.cs | 22 ++--- .../Editors/PackageInstallController.cs | 11 +-- .../ContentEditing/InstalledPackageModel.cs | 39 --------- src/Umbraco.Web/Umbraco.Web.csproj | 1 - 38 files changed, 180 insertions(+), 286 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js create mode 100644 src/Umbraco.Web.UI.Client/src/views/packages/options.html delete mode 100644 src/Umbraco.Web/Models/ContentEditing/InstalledPackageModel.cs diff --git a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs index 7f62f4fd27..9e6339178e 100644 --- a/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs +++ b/src/Umbraco.Core/Packaging/CompiledPackageXmlParser.cs @@ -51,7 +51,7 @@ namespace Umbraco.Core.Packaging IconUrl = package.Element("iconUrl")?.Value, UmbracoVersion = new Version((int)requirements.Element("major"), (int)requirements.Element("minor"), (int)requirements.Element("patch")), UmbracoVersionRequirementsType = requirements.AttributeValue("type").IsNullOrWhiteSpace() ? RequirementsType.Legacy : Enum.Parse(requirements.AttributeValue("type"), true), - PackageView = package.Element("view")?.Value, + PackageView = xml.Root.Element("view")?.Value, Actions = xml.Root.Element("Actions")?.ToString(SaveOptions.None) ?? "", //take the entire outer xml value Files = xml.Root.Element("files")?.Elements("file")?.Select(CompiledPackageFile.Create).ToList() ?? new List(), Macros = xml.Root.Element("Macros")?.Elements("macro") ?? Enumerable.Empty(), diff --git a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs index 00255fa43a..b66cdb095c 100644 --- a/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs +++ b/src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs @@ -34,6 +34,7 @@ namespace Umbraco.Core.Packaging PackageId = xml.AttributeValue("packageGuid"), IconUrl = xml.AttributeValue("iconUrl") ?? string.Empty, UmbracoVersion = xml.AttributeValue("umbVersion"), + PackageView = xml.AttributeValue("view") ?? string.Empty, License = xml.Element("license")?.Value ?? string.Empty, LicenseUrl = xml.Element("license")?.AttributeValue("url") ?? string.Empty, Author = xml.Element("author")?.Value ?? string.Empty, @@ -49,8 +50,7 @@ namespace Umbraco.Core.Packaging Languages = xml.Element("languages")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), DictionaryItems = xml.Element("dictionaryitems")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), DataTypes = xml.Element("datatypes")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - Files = xml.Element("files")?.Elements("file").Select(x => x.Value).ToList() ?? new List(), - PackageView = xml.Element("view")?.Value ?? string.Empty + Files = xml.Element("files")?.Elements("file").Select(x => x.Value).ToList() ?? new List() }; return retVal; @@ -77,6 +77,7 @@ namespace Umbraco.Core.Packaging new XAttribute("iconUrl", def.IconUrl ?? string.Empty), new XAttribute("umbVersion", def.UmbracoVersion), new XAttribute("packageGuid", def.PackageId), + new XAttribute("view", def.PackageView ?? string.Empty), new XElement("license", new XCData(def.License ?? string.Empty), @@ -100,8 +101,7 @@ namespace Umbraco.Core.Packaging new XElement("macros", string.Join(",", def.Macros ?? Array.Empty())), new XElement("files", (def.Files ?? Array.Empty()).Where(x => !x.IsNullOrWhiteSpace()).Select(x => new XElement("file", x))), new XElement("languages", string.Join(",", def.Languages ?? Array.Empty())), - new XElement("dictionaryitems", string.Join(",", def.DictionaryItems ?? Array.Empty())), - new XElement("view", def.PackageView ?? string.Empty)); + new XElement("dictionaryitems", string.Join(",", def.DictionaryItems ?? Array.Empty()))); return packageXml; } diff --git a/src/Umbraco.Core/Packaging/PackagesRepository.cs b/src/Umbraco.Core/Packaging/PackagesRepository.cs index 5531e05705..1df232f62d 100644 --- a/src/Umbraco.Core/Packaging/PackagesRepository.cs +++ b/src/Umbraco.Core/Packaging/PackagesRepository.cs @@ -161,30 +161,30 @@ namespace Umbraco.Core.Packaging try { //Init package file - var packageManifest = CreatePackageManifest(out var manifestRoot, out var filesXml); + var compiledPackageXml = CreateCompiledPackageXml(out var root, out var filesXml); //Info section - manifestRoot.Add(GetPackageInfoXml(definition)); + root.Add(GetPackageInfoXml(definition)); - PackageDocumentsAndTags(definition, manifestRoot); - PackageDocumentTypes(definition, manifestRoot); - PackageTemplates(definition, manifestRoot); - PackageStylesheets(definition, manifestRoot); - PackageMacros(definition, manifestRoot, filesXml, temporaryPath); - PackageDictionaryItems(definition, manifestRoot); - PackageLanguages(definition, manifestRoot); - PackageDataTypes(definition, manifestRoot); + PackageDocumentsAndTags(definition, root); + PackageDocumentTypes(definition, root); + PackageTemplates(definition, root); + PackageStylesheets(definition, root); + PackageMacros(definition, root, filesXml, temporaryPath); + PackageDictionaryItems(definition, root); + PackageLanguages(definition, root); + PackageDataTypes(definition, root); //Files foreach (var fileName in definition.Files) - AppendFileToManifest(fileName, temporaryPath, filesXml); + AppendFileToPackage(fileName, temporaryPath, filesXml); - //Load control on install... + //Load view on install... if (!string.IsNullOrEmpty(definition.PackageView)) { var control = new XElement("view", definition.PackageView); - AppendFileToManifest(definition.PackageView, temporaryPath, filesXml); - manifestRoot.Add(control); + AppendFileToPackage(definition.PackageView, temporaryPath, filesXml); + root.Add(control); } //Actions @@ -196,20 +196,20 @@ namespace Umbraco.Core.Packaging //this will be formatted like a full xml block like ... and we want the child nodes var parsed = XElement.Parse(definition.Actions); actionsXml.Add(parsed.Elements()); - manifestRoot.Add(actionsXml); + root.Add(actionsXml); } catch (Exception e) { - _logger.Warn(e, "Could not add package actions to the package manifest, the xml did not parse"); + _logger.Warn(e, "Could not add package actions to the package, the xml did not parse"); } } - var manifestFileName = temporaryPath + "/package.xml"; + var packageXmlFileName = temporaryPath + "/package.xml"; - if (File.Exists(manifestFileName)) - File.Delete(manifestFileName); + if (File.Exists(packageXmlFileName)) + File.Delete(packageXmlFileName); - packageManifest.Save(manifestFileName); + compiledPackageXml.Save(packageXmlFileName); // check if there's a packages directory below media @@ -242,7 +242,7 @@ namespace Umbraco.Core.Packaging throw new InvalidOperationException("Validation failed, there is invalid data on the model: " + string.Join(", ", results.Select(x => x.ErrorMessage))); } - private void PackageDataTypes(PackageDefinition definition, XContainer manifestRoot) + private void PackageDataTypes(PackageDefinition definition, XContainer root) { var dataTypes = new XElement("DataTypes"); foreach (var dtId in definition.DataTypes) @@ -252,10 +252,10 @@ namespace Umbraco.Core.Packaging if (dataType == null) continue; dataTypes.Add(_serializer.Serialize(dataType)); } - manifestRoot.Add(dataTypes); + root.Add(dataTypes); } - private void PackageLanguages(PackageDefinition definition, XContainer manifestRoot) + private void PackageLanguages(PackageDefinition definition, XContainer root) { var languages = new XElement("Languages"); foreach (var langId in definition.Languages) @@ -265,10 +265,10 @@ namespace Umbraco.Core.Packaging if (lang == null) continue; languages.Add(_serializer.Serialize(lang)); } - manifestRoot.Add(languages); + root.Add(languages); } - private void PackageDictionaryItems(PackageDefinition definition, XContainer manifestRoot) + private void PackageDictionaryItems(PackageDefinition definition, XContainer root) { var dictionaryItems = new XElement("DictionaryItems"); foreach (var dictionaryId in definition.DictionaryItems) @@ -278,10 +278,10 @@ namespace Umbraco.Core.Packaging if (di == null) continue; dictionaryItems.Add(_serializer.Serialize(di, false)); } - manifestRoot.Add(dictionaryItems); + root.Add(dictionaryItems); } - private void PackageMacros(PackageDefinition definition, XContainer manifestRoot, XContainer filesXml, string temporaryPath) + private void PackageMacros(PackageDefinition definition, XContainer root, XContainer filesXml, string temporaryPath) { var macros = new XElement("Macros"); foreach (var macroId in definition.Macros) @@ -291,14 +291,14 @@ namespace Umbraco.Core.Packaging var macroXml = GetMacroXml(outInt, out var macro); if (macroXml == null) continue; macros.Add(macroXml); - //if the macro has a file copy it to the manifest + //if the macro has a file copy it to the xml if (!string.IsNullOrEmpty(macro.MacroSource)) - AppendFileToManifest(macro.MacroSource, temporaryPath, filesXml); + AppendFileToPackage(macro.MacroSource, temporaryPath, filesXml); } - manifestRoot.Add(macros); + root.Add(macros); } - private void PackageStylesheets(PackageDefinition definition, XContainer manifestRoot) + private void PackageStylesheets(PackageDefinition definition, XContainer root) { var stylesheetsXml = new XElement("Stylesheets"); foreach (var stylesheetName in definition.Stylesheets) @@ -308,10 +308,10 @@ namespace Umbraco.Core.Packaging if (xml != null) stylesheetsXml.Add(xml); } - manifestRoot.Add(stylesheetsXml); + root.Add(stylesheetsXml); } - private void PackageTemplates(PackageDefinition definition, XContainer manifestRoot) + private void PackageTemplates(PackageDefinition definition, XContainer root) { var templatesXml = new XElement("Templates"); foreach (var templateId in definition.Templates) @@ -321,10 +321,10 @@ namespace Umbraco.Core.Packaging if (template == null) continue; templatesXml.Add(_serializer.Serialize(template)); } - manifestRoot.Add(templatesXml); + root.Add(templatesXml); } - private void PackageDocumentTypes(PackageDefinition definition, XContainer manifestRoot) + private void PackageDocumentTypes(PackageDefinition definition, XContainer root) { var contentTypes = new HashSet(); var docTypesXml = new XElement("DocumentTypes"); @@ -338,10 +338,10 @@ namespace Umbraco.Core.Packaging foreach (var contentType in contentTypes) docTypesXml.Add(_serializer.Serialize(contentType)); - manifestRoot.Add(docTypesXml); + root.Add(docTypesXml); } - private void PackageDocumentsAndTags(PackageDefinition definition, XContainer manifestRoot) + private void PackageDocumentsAndTags(PackageDefinition definition, XContainer root) { //Documents and tags if (string.IsNullOrEmpty(definition.ContentNodeId) == false && int.TryParse(definition.ContentNodeId, out var contentNodeId)) @@ -356,7 +356,7 @@ namespace Umbraco.Core.Packaging //Create the Documents/DocumentSet node - manifestRoot.Add( + root.Add( new XElement("Documents", new XElement("DocumentSet", new XAttribute("importMode", "root"), @@ -438,12 +438,12 @@ namespace Umbraco.Core.Packaging } /// - /// Appends a file to package manifest and copies the file to the correct folder. + /// Appends a file to package and copies the file to the correct folder. /// /// The path. /// The package directory. /// The files xml node - private static void AppendFileToManifest(string path, string packageDirectory, XContainer filesXml) + private static void AppendFileToPackage(string path, string packageDirectory, XContainer filesXml) { if (!path.StartsWith("~/") && !path.StartsWith("/")) path = "~/" + path; @@ -584,12 +584,12 @@ namespace Umbraco.Core.Packaging return info; } - private static XDocument CreatePackageManifest(out XElement root, out XElement files) + private static XDocument CreateCompiledPackageXml(out XElement root, out XElement files) { files = new XElement("files"); root = new XElement("umbPackage", files); - var packageManifest = new XDocument(root); - return packageManifest; + var compiledPackageXml = new XDocument(root); + return compiledPackageXml; } private XDocument EnsureStorage(out string packagesFile) diff --git a/src/Umbraco.Web.UI.Client/src/common/mocks/services/localization.mocks.js b/src/Umbraco.Web.UI.Client/src/common/mocks/services/localization.mocks.js index ec1175ab6c..87955739fb 100644 --- a/src/Umbraco.Web.UI.Client/src/common/mocks/services/localization.mocks.js +++ b/src/Umbraco.Web.UI.Client/src/common/mocks/services/localization.mocks.js @@ -453,13 +453,11 @@ angular.module('umbraco.mocks'). "notifications_notifications": "Notifications", "packager_chooseLocalPackageText": " Choose Package from your machine, by clicking the Browse
button and locating the package. Umbraco packages usually have a '.umb' or '.zip' extension. ", "packager_packageAuthor": "Author", - "packager_packageDemonstration": "Demonstration", "packager_packageDocumentation": "Documentation", "packager_packageMetaData": "Package meta data", "packager_packageName": "Package name", "packager_packageNoItemsHeader": "Package doesn't contain any items", "packager_packageNoItemsText": "This package file doesn't contain any items to uninstall.

You can safely remove this from the system by clicking 'uninstall package' below.", - "packager_packageNoUpgrades": "No upgrades available", "packager_packageOptions": "Package options", "packager_packageReadme": "Package readme", "packager_packageRepository": "Package repository", @@ -468,12 +466,7 @@ angular.module('umbraco.mocks'). "packager_packageUninstalledText": "The package was successfully uninstalled", "packager_packageUninstallHeader": "Uninstall package", "packager_packageUninstallText": "You can unselect items you do not wish to remove, at this time, below. When you click 'confirm uninstall' all checked-off items will be removed.
Notice: any documents, media etc depending on the items you remove, will stop working, and could lead to system instability, so uninstall with caution. If in doubt, contact the package author.", - "packager_packageUpgradeDownload": "Download update from the repository", - "packager_packageUpgradeHeader": "Upgrade package", - "packager_packageUpgradeInstructions": "Upgrade instructions", - "packager_packageUpgradeText": " There's an upgrade available for this package. You can download it directly from the Umbraco package repository.", "packager_packageVersion": "Package version", - "packager_viewPackageWebsite": "View package website", "paste_doNothing": "Paste with full formatting (Not recommended)", "paste_errorMessage": "The text you're trying to paste contains special characters or formatting. This could be caused by copying text from Microsoft Word. Umbraco can remove special characters or formatting automatically, so the pasted content will be more suitable for the web.", "paste_removeAll": "Paste as raw text without any formatting at all", diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/package.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/package.resource.js index 0d74d0fdd3..7519341327 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/package.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/package.resource.js @@ -175,7 +175,17 @@ function packageResource($q, $http, umbDataFormatter, umbRequestHelper) { umbRequestHelper.getApiUrl( "packageApiBaseUrl", "GetCreatedPackageById", - [{ id: id }])), + { id: id })), + 'Failed to get package'); + }, + + getInstalledById: function (id) { + return umbRequestHelper.resourcePromise( + $http.get( + umbRequestHelper.getApiUrl( + "packageApiBaseUrl", + "GetInstalledPackageById", + { id: id })), 'Failed to get package'); }, diff --git a/src/Umbraco.Web.UI.Client/src/routes.js b/src/Umbraco.Web.UI.Client/src/routes.js index 64bddb16e2..c2d3ea2df8 100644 --- a/src/Umbraco.Web.UI.Client/src/routes.js +++ b/src/Umbraco.Web.UI.Client/src/routes.js @@ -158,7 +158,8 @@ app.config(function ($routeProvider) { } //special case for the package section - if ($routeParams.section.toLowerCase() === "packages" && $routeParams.tree.toLowerCase() === "packages" && $routeParams.method !== "edit") { + var packagePages = ["edit", "options"]; + if ($routeParams.section.toLowerCase() === "packages" && $routeParams.tree.toLowerCase() === "packages" && packagePages.indexOf($routeParams.method.toLowerCase()) === -1) { $scope.templateUrl = "views/packages/overview.html"; return; } diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html index 5163fadfb5..5ad5ac2522 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html @@ -255,13 +255,13 @@ + label="Package options view" + description="Load this view after installation (ex: App_Plugins/MyApp/MyPackageOptions.html). It can be used to configure your package at any time by clicking Options on the installed package listing"> diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js new file mode 100644 index 0000000000..8ffd282e0d --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js @@ -0,0 +1,43 @@ +(function () { + "use strict"; + + function OptionsController($scope, $location, $routeParams, packageResource, umbRequestHelper) { + + const vm = this; + + vm.showBackButton = true; + vm.loading = true; + vm.back = back; + + const packageId = $routeParams.id; + + function onInit() { + + packageResource.getInstalledById(packageId).then(pck => { + vm.package = pck; + vm.loading = false; + + //make sure the packageView is formatted as a virtual path + pck.packageView = pck.packageView.startsWith("/~") + ? pck.packageView + : pck.packageView.startsWith("/") + ? "~" + pck.packageView + : "~/" + pck.packageView; + + pck.packageView = umbRequestHelper.convertVirtualToAbsolutePath(pck.packageView); + + }); + } + + function back() { + $location.path("packages/packages/installed"); + } + + + onInit(); + + } + + angular.module("umbraco").controller("Umbraco.Editors.Packages.OptionsController", OptionsController); + +})(); diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/options.html b/src/Umbraco.Web.UI.Client/src/views/packages/options.html new file mode 100644 index 0000000000..d75604d094 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/packages/options.html @@ -0,0 +1,40 @@ +
+ +
+ + + + + + + + + + +

+ This package has no configuration view +

+ +
+ +
+ + + + +
+ +
+ +
diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js index 59fa79dc26..f4c1ab9de4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js @@ -17,8 +17,7 @@ } if (installPackageUri && installPackageUri !== "installed") { - //navigate to the custom installer screen, if it is just "installed", then we'll - //show the installed view + //navigate to the custom installer screen, if it is just "installed" it means there is no custom installer screen $location.path(installPackageUri).search(""); } else { diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js index 5265897708..3b6422ace4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js @@ -7,6 +7,7 @@ vm.confirmUninstall = confirmUninstall; vm.uninstallPackage = uninstallPackage; + vm.packageOptions = packageOptions; vm.state = "list"; vm.installState = { status: "" @@ -34,6 +35,10 @@ }); } + function packageOptions(pck) { + $location.path("packages/packages/options/" + pck.id); + } + function confirmUninstall(pck) { vm.state = "packageDetails"; vm.package = pck; diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.html b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.html index 3c443e0bac..888bf02c4e 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.html @@ -23,12 +23,19 @@
- + + + + diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml index f3b16def54..db780bb358 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml @@ -617,14 +617,12 @@ a výběrem balíčku. Balíčky umbraco mají obvykle přípony ".umb" nebo ".zip". ]]> Autor - Ukázka Dokumentace Meta data balíčku Název balíčku Balíček neobsahuje žádné položky
Můžete jej ze systému bezpečně odstranit kliknutím na "odebrat balíček" níže.]]>
- Žádné aktualizace nejsou dostupné Možnosti balíčku Čti mě balíčku Úložiště balíčku @@ -635,12 +633,7 @@ Upozornění: všechny dokumenty, media atd. závislé na položkách, které odstraníte, přestanou pracovat a mohou vést k nestabilitě systému, takže odinstalovávejte opatrně. Jste-li na pochybách, kontaktujte autora balíčku.]]> - Stáhnout aktualizaci z úložiště - Balíček s aktualizací - Pokyny pro aktualizaci - Pro tento balíček je dostupná aktualizace. Můžete si ji stáhnout přímo z úložiště balíčků umbraco. Verze balíčku - Zobrazit web balíčku Vložit s úplným formatováním (nedoporučeno) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml index 523531947a..39e1341f37 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml @@ -840,13 +840,11 @@ Mange hilsner fra Umbraco robotten Denne pakke er kompatibel med de følgende versioner af Umbraco, som rapporteret af community-medlemmer. Fuld kompatibilitet kan ikke garanteres for versioner rapporteret nedenfor 100% Eksterne kilder Forfatter - Demonstration Dokumentation Pakke meta data Pakkenavn Pakken indeholder ingen elementer
Du kan roligt fjerne denne fra systemet ved at klikke på "Fjern pakke" nedenfor.]]>
- Ingen opdateringer tilgængelige Pakkevalg Pakke læs mig Pakke opbevaringsbase @@ -856,12 +854,7 @@ Mange hilsner fra Umbraco robotten Afinstallér pakke Bemærk: at dokumenter og medier som afhænger af denne pakke vil muligvis holde op med at virke, så vær forsigtig. Hvis i tvivl, kontakt personen som har udviklet pakken.]]> - Download opdatering fra opbevaringsbasen - Opdatér pakke - Opdateringsinstrukser - Der er en tilgængelig opdatering til denne pakke. Du kan downloade den direkte fra Umbracos pakke opbevaringsbase. Pakke version - Se pakkeudviklerens website Pakke allerede installeret Denne pakke kan ikke installeres, den kræver en minimum Umbraco version af Afinstallerer... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/de.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/de.xml index 915b25208e..1be81fb10f 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/de.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/de.xml @@ -610,13 +610,11 @@ Wenn Sie sich für Runway entscheiden, können Sie optional Blöcke nutzen, die Wählen Sie ein Paket auf Ihrem lokalen Computer über "Datei auswählen" aus. <br />Umbraco-Pakete besitzen üblicherweise die Dateiendungen ".umb" oder ".zip". Autor - Demonstration Dokumentation Paket-Meta-Daten Name des Pakets Paket enthält keine Elemente Die Paket-Datei enthält keine Elemente die deinstalliert werden können.<br/><br/>Sie können das Paket ohne Gefahr deinstallieren indem Sie "Paket deinstallieren" anklicken. - Keine Updates für das Paket verfügbar Paket-Optionen Informationen zum Paket Paket-Repository @@ -625,12 +623,7 @@ Wenn Sie sich für Runway entscheiden, können Sie optional Blöcke nutzen, die Das Paket wurde erfolgreich deinstalliert Paket deinstallieren Sie können einzelne Elemente, die Sie nicht deinstallieren möchten, unten abwählen. Wenn Sie "Deinstallation bestätigen" klicken, werden alle markierten Elemente entfernt.<br /><span style="color: Red; font-weight: bold;">Achtung:</span> alle Dokumente, Medien, etc, die von den zu entfernenden Elementen abhängen, werden nicht mehr funktionieren und im Zweifelsfall kann dass gesamte CMS instabil werden. Bitte deinstallieren Sie also mit Vorsicht. Falls Sie unsicher sind, kontaktieren Sie den Autor des Pakets. - Update vom Paket-Repository herunterladen - Paket-Update - Hinweise für die Durchführung des Updates - Es ist ein Update für dieses Paket verfügbar. Sie können es direkt vom Umbraco-Paket-Repository herunterladen. Version des Pakets - Paket-Webseite aufrufen Einfügen mit Formatierung (Nicht empfohlen) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index dad27d99fe..d50cac4ac4 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -1090,14 +1090,12 @@ To manage your website, simply open the Umbraco back office and start adding con This package is compatible with the following versions of Umbraco, as reported by community members. Full compatability cannot be gauranteed for versions reported below 100% External sources Author - Demonstration Documentation Package meta data Package name Package doesn't contain any items
You can safely remove this from the system by clicking "uninstall package" below.]]>
- No upgrades available Package options Package readme Package repository @@ -1108,12 +1106,7 @@ To manage your website, simply open the Umbraco back office and start adding con Notice: any documents, media etc depending on the items you remove, will stop working, and could lead to system instability, so uninstall with caution. If in doubt, contact the package author.]]> - Download update from the repository - Upgrade package - Upgrade instructions - There's an upgrade available for this package. You can download it directly from the Umbraco package repository. Package version - View package website Package already installed This package cannot be installed, it requires a minimum Umbraco version of Uninstalling... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml index ab37cf8025..23efe8047e 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -1117,14 +1117,12 @@ To manage your website, simply open the Umbraco back office and start adding con This package is compatible with the following versions of Umbraco, as reported by community members. Full compatability cannot be gauranteed for versions reported below 100% External sources Author - Demonstration Documentation Package meta data Package name Package doesn't contain any items
You can safely remove this from the system by clicking "uninstall package" below.]]>
- No upgrades available Package options Package readme Package repository @@ -1135,13 +1133,8 @@ To manage your website, simply open the Umbraco back office and start adding con Notice: any documents, media etc depending on the items you remove, will stop working, and could lead to system instability, so uninstall with caution. If in doubt, contact the package author.]]> - Download update from the repository - Upgrade package - Upgrade instructions - There's an upgrade available for this package. You can download it directly from the Umbraco package repository. Package version Upgrading from version - View package website Package already installed This package cannot be installed, it requires a minimum Umbraco version of Uninstalling... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/es.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/es.xml index 7f35e90083..090ecc875e 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/es.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/es.xml @@ -863,14 +863,11 @@ Este paquete es compatible con las siguientes versiones de Umbraco, declaradas según miembros de la comunidad. No se puede garantizar compatibilidad completa para versiones declaradas debajo del 100% Fuentes externas Autor - Documentación Meta datos del paquete Nombre del paquete El paquete no contiene ningún elemento
Puedes eliminarlo del sistema de forma segura seleccionando la opción "desinstalar paquete" de abajo.]]>
- No hay actualizaciones disponibles Opciones del paquete Léeme del paquete Repositorio de paquetes @@ -879,12 +876,7 @@ El paquete se ha desinstalado correctamente Desinstalar paquete Nota: cualquier documento, archivo etc dependiente de los elementos eliminados, dejará de funcionar, y puede conllevar inestabilidad en el sistema, por lo que lleva cuidado al desinstalar elementos. En caso de duda, contacta con el autor del paquete.]]> - Descargar actualización del repositorio - Actualizar paquete - Instrucciones de actualización - Hay una actualización disponible para este paquete. Puedes descargarla directamente del repositorio de paquetes de Umbraco. Versión del paquete - Ver página web del paquete Paquete ya instalado Este paquete no se puede instalar, requiere un versión mínima de Umbraco de Desinstalando... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/fr.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/fr.xml index 04b2cea4df..b6c23d7b63 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/fr.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/fr.xml @@ -1025,14 +1025,12 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à Ce package est compatible avec les versions suivantes de Umbraco, selon les rapports des membres de la communauté. Une compatibilité complète ne peut pas être garantie pour les versions rapportées sous 100% Sources externes Auteur - Démo Documentation Meta data du package Nom du package Le package ne contient aucun élément
Vous pouvez supprimer tranquillement ce package de votre installation en cliquant sur "Désinstaller le package" ci-dessous.]]>
- Aucune mise à jour disponible Options du package Package readme Repository des packages @@ -1043,12 +1041,7 @@ Pour gérer votre site, ouvrez simplement le backoffice Umbraco et commencez à Remarque : tous les documents, media etc. dépendant des éléments que vous supprimez vont cesser de fonctionner, ce qui peut provoquer une instabilité du système, désinstallez donc avec prudence. En cas de doute, contactez l'auteur du package.]]> - Télécharger la mise à jour depuis le repository - Mettre à jour le package - Instructions de mise à jour - Il y a une mise à jour disponible pour ce package. Vous pouvez la télécharger directement depuis le repository des packages Umbraco. Version du package - Voir le site internet du package Package déjà installé Ce package ne peut pas être installé, il nécessite au minimum la version Umbraco %0% Désinstallation... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/he.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/he.xml index 011745ac0f..8d3822943a 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/he.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/he.xml @@ -548,14 +548,12 @@ To manage your website, simply open the Umbraco back office and start adding con ויש לבחור את החבילה הרצויה. לחבילות Umbraco יש בד"כ יש סיומות בשם ".umb" או ".zip". ]]> יוצר החבילה - הדגמה תיעוד מטה דטה עבור החבילה שם החבילה החבילה לא מכילה אף פריט
ניתן למחוק בבטיחות רבה את החבילה מהמערכת על ידי לחיצה על "הסר חבילה".]]>
- אין עידכונים זמינים אפשרויות חבילה תיאור החבילה מאגר חבילות @@ -566,12 +564,7 @@ To manage your website, simply open the Umbraco back office and start adding con הערה:כל מסמך, מדיה וכו' התלוים בפריטים שהסרת יפסיקו לעבוד, ויכולים להביא למצב של אי יציבות למערכת, יש למחוק קבצים עם זהירות יתרה, אם יש ספק יש לפנות ליוצר החבילה.]]> - הורד עידכון מהמאגר - שידרוג חבילה - הורדות שידרוג - קיים עידכון זמין עבור חבילה זו. ניתן להוריד אותו ישירות ממאגר החבילות של אומברקו. גירסת החבילה - צפה באתר החבילה שמור עיצוב בהדבקה (לא מומלץ) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/it.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/it.xml index a55c626625..6796fdfc3c 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/it.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/it.xml @@ -524,14 +524,12 @@ Per gestire il tuo sito web, è sufficiente aprire il back office di Umbraco e i e selezionando il pacchetto. I pacchetti Umbraco generalmente hanno l'estensione ".umb" o ".zip". ]]> Autore - Dimostrazione Documentazione Meta dati pacchetto Nome del pacchetto Il pacchetto non contiene tutti gli elementi
E' possibile rimuovere questo pacchetto dal sistema cliccando "rimuovi pacchetto" in basso.]]>
- Non ci sono aggiornamenti disponibili Opzioni pacchetto Pacchetto leggimi Pacchetto repository @@ -542,12 +540,7 @@ Per gestire il tuo sito web, è sufficiente aprire il back office di Umbraco e i Avviso: tutti i documenti, i media, etc a seconda degli elementi che rimuoverai, smetteranno di funzionare, e potrebbero portare a un'instabilità del sistema, perciò disinstalla con cautela. In caso di dubbio contattare l'autore del pacchetto.]]> - - Aggiorna pacchetto - - Versione del pacchetto - Vedi sito web pacchetto diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/ja.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/ja.xml index 993a99ceec..ae30fde3c4 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/ja.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/ja.xml @@ -692,14 +692,12 @@ Runwayをインストールして作られた新しいウェブサイトがど パッケージを選択できます。Umbracoのパッケージは概ね".zip"ないしは".umb"といった拡張子です。 ]]> 作成者 - デモ ヘルプ パッケージのメタデータ パッケージ名 パッケージには何も含まれません
"パッケージのアンインストール"をクリックしてシステムから安全に削除できます。]]>
- 更新はありません パッケージのオプション パッケージの取扱説明書 パッケージリポジトリ @@ -710,12 +708,7 @@ Runwayをインストールして作られた新しいウェブサイトがど 注意: 全ての、文書やメディアなどに依存したアイテムを削除する場合はそれらの作業を一端止めてからアンインストールしなければシステムが不安定になる恐れがあります。 疑問点などあればパッケージの作者へ連絡してください。]]> - リポジトリからアップデートをダウンロード - パッケージのアップグレード - 更新の手順 - このパッケージの更新があります。Umbracoのパッケージリポジトリから直接ダウンロードできます。 パッケージのバージョン - パッケージのウェブサイトを見る 完全な書式を含んだまま貼り付け (非推奨) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/ko.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/ko.xml index 7a46ea81c8..7507ca07e8 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/ko.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/ko.xml @@ -532,14 +532,12 @@ Umbraco 패키지는 보통 ".umb" 나 ".zip" 확장자를 가집니다. ]]> 저자 - 데모 문서화 패키지 메타데이터 패키지 이름 패키지가 포함한 아이템이 없습니다.
아래 "패키지 삭제"를 클릭하시면 안전하게 시스템에서 삭제하실 수 있습니다.]]>
- 업그레이드할 패키지가 없습니다. 패키지 옵션 패키지 정보 패키지 저장소 @@ -550,12 +548,7 @@ 알림: 문서, 미디어등 삭제항목에 관련된 모든 항목이 삭제됩니다, 작업을 중단하면 시스템이 불안정적으로 동작할 수 있습니다. 삭제는 매우 주의를 요하기 때문에 의심스러운항목은 패키지 제작자에게 문의하시기 바랍니다.]]> - 저장소에서 업데이트 다운로드 - 업그레이드 패키지 - 업그레이드 지시사항 - 업그레이드할 패키지가 없습니다. Umbraco패키지 저장소에서 직접다운로드하실 수 있습니다. 패키지 버전 - 패키지 웹사이트 보기 포맷을 포함여하 붙여넣기(권장하지 않음) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml index a3c8abb946..39f4dd9560 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml @@ -589,13 +589,11 @@ Vennlig hilsen Umbraco roboten Umbraco-pakker har vanligvis endelsen ".umb" eller ".zip".]]> Utvikler - Demonstrasjon Dokumentasjon Metadata Pakkenavn Pakken inneholder ingen elementer
Du kan trygt fjerne pakken fra systemet ved å klikke "avinstaller pakke" nedenfor.]]>
- Ingen oppdateringer tilgjengelig Alternativer for pakke Lesmeg for pakke Pakkebrønn @@ -604,12 +602,7 @@ Vennlig hilsen Umbraco roboten Pakken ble vellykket avinstallert Avinstaller pakke Advarsel: alle dokumenter, media, etc. som som er avhengig av elementene du sletter, vil slutte å virke, noe som kan føre til ustabilitet, så avinstaller med forsiktighet. Hvis du er i tvil, kontakt pakkeutvikleren.]]> - Last ned oppdatering fra pakkeregisteret - Oppgrader pakke - Oppgraderingsinstrukser - Det er en oppdatering tilgjengelig for denne pakken. Du kan laste den ned direkte fra pakkebrønnen. Pakkeversjon - Se pakkens nettsted Lim inn med full formattering (Anbefales ikke) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/nl.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/nl.xml index 8189be9429..4722abb557 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/nl.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/nl.xml @@ -698,7 +698,6 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Kies een package op je computer door op "Bladeren" te klikken en de package te selecteren. Umbraco packages hebben meestal ".umb" of ".zip" als extensie. Auteur - Demonstratie Documentatie Package meta data Package naam @@ -706,7 +705,6 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je
Je kunt deze package veilig verwijderen door op 'verwijder package' te klikken. ]]>
- Geen upgrades beschikbaar Package opties Package lees mij Package repository @@ -718,12 +716,7 @@ Echter, Runway biedt een gemakkelijke basis om je snel op weg te helpen. Als je Waarschuwing: alle documenten, media etc, die afhankelijk zijn van de items die je verwijderd, zullen niet meer werken en kan leiden tot een instabiele installatie, wees dus voorzichtig met verwijderen. Als je het niet zeker weet, neem dan contact op met de auteur van de package. ]]> - Download update uit de repository - Upgrade package - Upgrade instructies - Er is een upgrade beschikbaar voor deze package. Je kunt het direct downloaden uit de Umbraco package repository. Package versie - Bekijk de package website Package reeds geinstalleerd Deze package kan niet worden geinstalleerd omdat minimaal Umbraco versie %0% benodigd is. Aan het deinstalleren... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/pl.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/pl.xml index 1f64a5ab21..788afd3c1a 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/pl.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/pl.xml @@ -859,14 +859,12 @@ Naciśnij przycisk instaluj, aby zainstalować bazę danych Umb Według raportów członków społeczności, ten pakiet jest zgodny z następującymi wersjami Umbraco. Pełna zgodność nie może być zagwarantowana dla wersji zaraportowanych poniżej 100% Zewnętrzne źródła Autor - Demonstracja Dokumentacja Metadane pakietu Nazwa pakietu Pakiet nie zawiera żadnych elementów
Możesz bezpiecznie go usunąć z systemu poprzez kliknięcie na przycisku "odinstaluj pakiet"]]>
- Nie ma dostępnych aktualizacji Opcje pakietu Opis pakietu Repozytorium pakietu @@ -877,12 +875,7 @@ Naciśnij przycisk instaluj, aby zainstalować bazę danych Umb Uwaga: wszystkie elementy, media, itp. w zależności od elementów, które usuwasz, przestaną działać i mogą spowodować niestabilność systemu, więc odinstalowuj z uwagą. W przypadku problemów skontaktuj się z autorem pakietu.]]> - Pobierz aktualizację z repozytorium - Aktualizuj pakiet - Instrukcja aktualizacji - Jest dostępna aktualizacja dla tego pakietu. Możesz ją pobrać wprost z repozytorium pakietów Umbraco. Wersja pakietu - Odwiedź stronę pakietu Pakiet jest już zainstalowany Ten pakiet nie może być zainstalowany, ponieważ wymaga Umbraco w wersji przynajmniej %0% Odinstalowywanie... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/pt.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/pt.xml index cff6009bb4..56297d23df 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/pt.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/pt.xml @@ -522,14 +522,12 @@ Vá até http://%4%/#/content/content/edit/%5% para editar. e localizando o pacote. Pacotes Umbraco tem extensão ".umb" ou ".zip".]]> Autor - Demonstração Documentação Dado meta do pacote Nome do pacote Pacote não contém nenhum item
Você pode remover com segurança do seu sistema clicando em "desinstalar pacote" abaixo.]]>
- Nenhuma atualização disponível Oções do pacote Leia-me do pacote Repositório do pacote @@ -539,12 +537,7 @@ Você pode remover com segurança do seu sistema clicando em "desinstalar pacote Desinstalar pacote Aviso: quaisquer documentos, mídia, etc dependentes dos itens que forem removidos vão parar de funcionar e podem levar à instabilidade do sistema. Então desinstale com cuidado. Se tiver dúvidas, contate o autor do pacote]]> - Baixar atualização pelo repositório - Atualizar pacote - Instruções de atualização - Há uma atualizaçào disponível para este pacote. Você pode baixá-lo diretamente do repositório de pacotes do Umbraco. Versão do pacote - Ver website do pacote Colar com formatação completa (Não recomendado) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/ru.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/ru.xml index 61c42d9d6d..1744d19581 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/ru.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/ru.xml @@ -1182,14 +1182,12 @@ Этот пакет совместим со следующими версиями Umbraco, по сообщениям участников сообщества. Полная совместимость не гарантируется для версий со значением ниже 100% Внешние источники Автор - Демонстрация Документация (описание) Мета-данные пакета Название пакета Пакет ничего не содержит
Вы можете безопасно удалить данный пакет из системы, нажав на кнопку "Деинсталлировать пакет".]]>
- Нет доступных обновлений Опции пакета Краткий обзор пакета Репозиторий пакета @@ -1200,12 +1198,7 @@ Обратите внимание: все документы, медиа-файлы и другой контент, зависящий от этого пакета, перестанет нормально работать, что может привести к нестабильному поведению системы, поэтому удаляйте пакеты очень осторожно. При наличии сомнений, свяжитесь с автором пакета.]]> - Скачать обновление из репозитория - Обновление пакета - Руководство по обновлению - Для данного пакета доступно обновление. Вы можете загрузить это обновление непосредственно из центрального репозитория пакетов Umbraco. Версия пакета - Перейти на веб-сайт пакета Этот пакет уже установлен в системе Этот пакет не может быть установлен, он требует наличия Umbraco версии как минимум Удаление... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/sv.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/sv.xml index 05c6dc927d..625caa0432 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/sv.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/sv.xml @@ -544,13 +544,11 @@ och leta upp paketet. Umbracos installationspaket har oftast filändelsen ".umb" eller ".zip".]]> Utvecklare - Demonstration Dokumentation Paket metadata Paketnamn Paketet innehåller inga poster
Det är säkert att ta bort den ur systemet genom att klicka på "avinstallera paket" nedan.]]>
- Inga uppdateringar tillgängliga Paketalternativ Paket läsmig Paketvalv @@ -559,12 +557,7 @@ Paketet har avinstallerats utan problem Avinstallera paket OBS! dokument, media osv som använder de borttagna posterna kommer sluta fungera vilket kan leda till att systemet blir instabilt. Avinstallera därför med försiktighet. Om du är osäker, kontakta personen som skapat paketet.]]> - Hämta uppdatering från paketvalvet - Uppdatera paket - Uppdateringsinstruktioner - Det finns an uppdaterad version av paketet. Du kan hämta den direkt från Umbracos paketvalv. Paketversion - Besök paketets webbplats Klistra in med helt bibehållen formatering (rekommenderas ej) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/tr.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/tr.xml index 4ff9d22c86..053430d68d 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/tr.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/tr.xml @@ -609,14 +609,12 @@ To manage your website, simply open the Umbraco back office and start adding con button and locating the package. Umbraco packages usually have a ".umb" or ".zip" extension. ]]> Author - Demonstration Documentation Package meta data Package name Package doesn't contain any items
You can safely remove this from the system by clicking "uninstall package" below.]]>
- No upgrades available Package options Package readme Package repository @@ -627,12 +625,7 @@ To manage your website, simply open the Umbraco back office and start adding con Notice: any documents, media etc depending on the items you remove, will stop working, and could lead to system instability, so uninstall with caution. If in doubt, contact the package author.]]> - Download update from the repository - Upgrade package - Upgrade instructions - There's an upgrade available for this package. You can download it directly from the Umbraco package repository. Package version - View package website Paste with full formatting (Not recommended) diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/zh.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/zh.xml index 7286c3f914..227e40cf94 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/zh.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/zh.xml @@ -728,14 +728,12 @@ 选择 ".umb" 或者 ".zip" 文件 ]]> 作者 - 演示 文档 元数据 名称 扩展包不含任何项
点击下面的“卸载”,您可以安全的删除。]]>
- 无可用更新 选项 说明 程序库 @@ -746,12 +744,7 @@ 注意: 卸载包将导致所有依赖该包的东西失效,请确认。 ]]> - 从程序库下载更新 - 更新扩展包 - 更新说明 - 此软件包有一个可用的升级。您可以直接从 Umbraco 软件包存储库下载。 版本 - 访问扩展包网站 已安装软件包 此软件包无法安装, 它需要一个最小的 Umbraco 版本的%0% 卸载中... diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml index b61e1154b8..23da0c817c 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml @@ -714,14 +714,12 @@ 按鈕並點選該檔案。Umbraco擴展包通常有「.zip」的副檔名。 ]]> 作者 - 演示 文檔 中繼資料 名稱 擴展包不含任何項
您可以點選下方「移除擴展包」來安全地移除此項目。]]>
- 無可用更新 選項 說明 程式庫 @@ -732,12 +730,7 @@ 注意: 任何文檔,媒體或需要這些項目才能運作的物件將會停止運作,並可能使得系統不穩定, 請小心移除。若有疑慮,請聯絡擴展包作者。]]> - 從程式庫下載更新 - 更新擴展包 - 更新說明 - 擴展包有可用的更新,您可以從程式庫網站更新。 版本 - 訪問擴展包網站 擴展包已安裝 這個擴展包無法安裝,它需要Umbraco至少是版本 %0% 移除中... diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/nb.xml b/src/Umbraco.Web.UI/umbraco/config/lang/nb.xml index a3c8abb946..39f4dd9560 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/nb.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/nb.xml @@ -589,13 +589,11 @@ Vennlig hilsen Umbraco roboten Umbraco-pakker har vanligvis endelsen ".umb" eller ".zip".]]> Utvikler - Demonstrasjon Dokumentasjon Metadata Pakkenavn Pakken inneholder ingen elementer
Du kan trygt fjerne pakken fra systemet ved å klikke "avinstaller pakke" nedenfor.]]>
- Ingen oppdateringer tilgjengelig Alternativer for pakke Lesmeg for pakke Pakkebrønn @@ -604,12 +602,7 @@ Vennlig hilsen Umbraco roboten Pakken ble vellykket avinstallert Avinstaller pakke Advarsel: alle dokumenter, media, etc. som som er avhengig av elementene du sletter, vil slutte å virke, noe som kan føre til ustabilitet, så avinstaller med forsiktighet. Hvis du er i tvil, kontakt pakkeutvikleren.]]> - Last ned oppdatering fra pakkeregisteret - Oppgrader pakke - Oppgraderingsinstrukser - Det er en oppdatering tilgjengelig for denne pakken. Du kan laste den ned direkte fra pakkebrønnen. Pakkeversjon - Se pakkens nettsted Lim inn med full formattering (Anbefales ikke) diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/zh_tw.xml b/src/Umbraco.Web.UI/umbraco/config/lang/zh_tw.xml index b61e1154b8..23da0c817c 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/zh_tw.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/zh_tw.xml @@ -714,14 +714,12 @@ 按鈕並點選該檔案。Umbraco擴展包通常有「.zip」的副檔名。 ]]> 作者 - 演示 文檔 中繼資料 名稱 擴展包不含任何項
您可以點選下方「移除擴展包」來安全地移除此項目。]]>
- 無可用更新 選項 說明 程式庫 @@ -732,12 +730,7 @@ 注意: 任何文檔,媒體或需要這些項目才能運作的物件將會停止運作,並可能使得系統不穩定, 請小心移除。若有疑慮,請聯絡擴展包作者。]]> - 從程式庫下載更新 - 更新擴展包 - 更新說明 - 擴展包有可用的更新,您可以從程式庫網站更新。 版本 - 訪問擴展包網站 擴展包已安裝 這個擴展包無法安裝,它需要Umbraco至少是版本 %0% 移除中... diff --git a/src/Umbraco.Web/Editors/PackageController.cs b/src/Umbraco.Web/Editors/PackageController.cs index 4814a8000a..c60d035562 100644 --- a/src/Umbraco.Web/Editors/PackageController.cs +++ b/src/Umbraco.Web/Editors/PackageController.cs @@ -115,11 +115,18 @@ namespace Umbraco.Web.Editors return response; } + public PackageDefinition GetInstalledPackageById(int id) + { + var pack = Services.PackagingService.GetInstalledPackageById(id); + if (pack == null) throw new HttpResponseException(HttpStatusCode.NotFound); + return pack; + } + /// /// Returns all installed packages - only shows their latest versions /// /// - public IEnumerable GetInstalled() + public IEnumerable GetInstalled() { return Services.PackagingService.GetAllInstalledPackages() .GroupBy( @@ -136,19 +143,6 @@ namespace Umbraco.Web.Editors //only return the first package with this version return grouping.First(x => x.version == maxVersion).package; }) - .Select(pack => new InstalledPackageModel - { - Name = pack.Name, - Id = pack.Id, - Author = pack.Author, - Version = pack.Version, - Url = pack.Url, - License = pack.License, - LicenseUrl = pack.LicenseUrl, - Files = pack.Files, - IconUrl = pack.IconUrl, - Readme = pack.Readme - }) .ToList(); } } diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 544a871720..f87f323df8 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -369,20 +369,17 @@ namespace Umbraco.Web.Editors var packageInfo = Services.PackagingService.GetCompiledPackageInfo(zipFile); + zipFile.Delete(); + + //bump cdf to be safe var clientDependencyConfig = new ClientDependencyConfiguration(Logger); var clientDependencyUpdated = clientDependencyConfig.UpdateVersionNumber( UmbracoVersion.SemanticVersion, DateTime.UtcNow, "yyyyMMdd"); - zipFile.Delete(); - var redirectUrl = ""; if (!packageInfo.PackageView.IsNullOrWhiteSpace()) { - //fixme! - throw new NotImplementedException(); - //redirectUrl = string.Format("/packages/framed/{0}", - // Uri.EscapeDataString( - // string.Format("/umbraco/developer/Packages/installer.aspx?installing=custominstaller&dir={0}&pId={1}&customControl={2}&customUrl={3}", tempDir, model.Id, ins.Control, ins.Url))); + redirectUrl = $"/packages/packages/options/{model.Id}"; } return new PackageInstallResult diff --git a/src/Umbraco.Web/Models/ContentEditing/InstalledPackageModel.cs b/src/Umbraco.Web/Models/ContentEditing/InstalledPackageModel.cs deleted file mode 100644 index 67bfe6fe53..0000000000 --- a/src/Umbraco.Web/Models/ContentEditing/InstalledPackageModel.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; -using System.Runtime.Serialization; - -namespace Umbraco.Web.Models.ContentEditing -{ - [DataContract] - public class InstalledPackageModel - { - [DataMember(Name = "id")] - public int Id { get; set; } - - [DataMember(Name = "name")] - public string Name { get; set; } - - [DataMember(Name = "author")] - public string Author { get; set; } - - [DataMember(Name = "files")] - public IEnumerable Files { get; set; } - - [DataMember(Name = "version")] - public string Version { get; set; } - - [DataMember(Name = "url")] - public string Url { get; set; } - - [DataMember(Name = "license")] - public string License { get; set; } - - [DataMember(Name = "licenseUrl")] - public string LicenseUrl { get; set; } - - [DataMember(Name = "iconUrl")] - public string IconUrl { get; set; } - - [DataMember(Name = "readme")] - public string Readme { get; set; } - } -} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index b0142771d2..62a7d6175c 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -596,7 +596,6 @@ - From 7bb358888980bdcd8d605214b611ba7bd22c0712 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 16 Jan 2019 23:53:10 +1100 Subject: [PATCH 21/70] Adds the whole package definition to the scope model for devs to use, adds a custom query string parameter when redirecting to the angular view after install (so devs know its a new install) --- .../src/views/packages/edit.controller.js | 2 +- .../src/views/packages/options.controller.js | 6 +++++- .../src/views/packages/overview.controller.js | 14 +++++++------- .../packages/views/install-local.controller.js | 10 ++-------- .../views/packages/views/installed.controller.js | 5 +++-- .../src/views/packages/views/repo.controller.js | 6 ++---- 6 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index ca20b33a3e..bed3341c6b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -130,7 +130,7 @@ } function back() { - $location.path("packages/packages/created").search("create", null); + $location.path("packages/packages/created").search("create", null).search("packageId", null); } function createOrUpdatePackage(editPackageForm) { diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js index 8ffd282e0d..4fdf6488a0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/options.controller.js @@ -15,6 +15,10 @@ packageResource.getInstalledById(packageId).then(pck => { vm.package = pck; + + //set the $scope too, packages can then access this if they wanted from their own scope or parent scope + $scope.package = pck; + vm.loading = false; //make sure the packageView is formatted as a virtual path @@ -30,7 +34,7 @@ } function back() { - $location.path("packages/packages/installed"); + $location.path("packages/packages/installed").search("packageId", null); } diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js index f4c1ab9de4..e48271aa23 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/overview.controller.js @@ -4,26 +4,26 @@ function PackagesOverviewController($scope, $location, $routeParams, localStorageService) { //Hack! - // if there is a cookie value for packageInstallUri then we need to redirect there, + // if there is a local storage value for packageInstallData then we need to redirect there, // the issue is that we still have webforms and we cannot go to a hash location and then window.reload // because it will double load it. // we will refresh and then navigate there. - let installPackageUri = localStorageService.get("packageInstallUri"); + let packageInstallData = localStorageService.get("packageInstallData"); let packageUri = $routeParams.method; - if (installPackageUri) { - localStorageService.remove("packageInstallUri"); + if (packageInstallData) { + localStorageService.remove("packageInstallData"); } - if (installPackageUri && installPackageUri !== "installed") { + if (packageInstallData && packageInstallData !== "installed" && packageInstallData.postInstallationPath) { //navigate to the custom installer screen, if it is just "installed" it means there is no custom installer screen - $location.path(installPackageUri).search(""); + $location.path(packageInstallData.postInstallationPath).search("packageId", packageInstallData.id); } else { var vm = this; - packageUri = installPackageUri ? installPackageUri : packageUri; //use the path stored in storage over the one in the current path + packageUri = packageInstallData ? packageInstallData : packageUri; //use the path stored in storage over the one in the current path vm.page = {}; vm.page.name = "Packages"; diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.controller.js index 17b417de48..0d9341243b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.controller.js @@ -184,14 +184,8 @@ installError) .then(function (result) { - if (result.postInstallationPath) { - //Put the redirect Uri in a cookie so we can use after reloading - localStorageService.set("packageInstallUri", result.postInstallationPath); - } - else { - //set to a constant value so it knows to just go to the installed view - localStorageService.set("packageInstallUri", "installed"); - } + //Put the package data in local storage so we can use after reloading + localStorageService.set("packageInstallData", result); vm.installState.status = labels.installStateCompleted; vm.installCompleted = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js index 3b6422ace4..ddfee19ac1 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/installed.controller.js @@ -36,7 +36,8 @@ } function packageOptions(pck) { - $location.path("packages/packages/options/" + pck.id); + $location.path("packages/packages/options/" + pck.id) + .search("packageId", null); //ensure the installId flag is gone, it's only available on first install } function confirmUninstall(pck) { @@ -56,7 +57,7 @@ vm.installState.progress = "100"; //set this flag so that on refresh it shows the installed packages list - localStorageService.set("packageInstallUri", "installed"); + localStorageService.set("packageInstallData", "installed"); //reload on next digest (after cookie) $timeout(function () { diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.controller.js index b77326d2fc..dc3e67db15 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/repo.controller.js @@ -257,10 +257,8 @@ error) .then(function (result) { - if (result.postInstallationPath) { - //Put the redirect Uri in a cookie so we can use after reloading - localStorageService.set("packageInstallUri", result.postInstallationPath); - } + //Put the package data in local storage so we can use after reloading + localStorageService.set("packageInstallData", result); vm.installState.status = labels.installStateCompleted; vm.installCompleted = true; From ddcead26582daa2d87b7eeaa74f5b5e475a57eb1 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 00:29:43 +1100 Subject: [PATCH 22/70] Updates EntityController to support stylesheets, languages and dictionary items GetAll so we can use it for the packager without worrying about security access to sections --- .../src/views/packages/edit.controller.js | 8 +-- .../Editors/DictionaryController.cs | 4 +- src/Umbraco.Web/Editors/EntityController.cs | 57 +++++++++++++++++-- .../ContentEditing/UmbracoEntityTypes.cs | 7 ++- .../Models/Mapping/CodeFileMapperProfile.cs | 12 ++++ .../Models/Mapping/DictionaryMapperProfile.cs | 12 ++++ .../Models/Mapping/LanguageMapperProfile.cs | 12 ++++ 7 files changed, 99 insertions(+), 13 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index bed3341c6b..0a44192041 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function EditController($scope, $location, $routeParams, umbRequestHelper, entityResource, stylesheetResource, languageResource, packageResource, dictionaryResource, editorService, formHelper) { + function EditController($scope, $location, $routeParams, umbRequestHelper, entityResource, packageResource, editorService, formHelper) { const vm = this; @@ -73,7 +73,7 @@ }); // get all stylesheets - stylesheetResource.getAll().then(stylesheets => { + entityResource.getAll("Stylesheet").then(stylesheets => { vm.stylesheets = stylesheets; }); @@ -87,7 +87,7 @@ }); // get all languages - languageResource.getAll().then(languages => { + entityResource.getAll("Language").then(languages => { // a package stores the id as a string so we // need to convert all ids to string for comparison languages.forEach(language => { @@ -97,7 +97,7 @@ }); // get all dictionary items - dictionaryResource.getList().then(dictionaryItems => { + entityResource.getAll("DictionaryItem").then(dictionaryItems => { // a package stores the id as a string so we // need to convert all ids to string for comparison dictionaryItems.forEach(dictionaryItem => { diff --git a/src/Umbraco.Web/Editors/DictionaryController.cs b/src/Umbraco.Web/Editors/DictionaryController.cs index cd3141c7b9..9d01cc9d64 100644 --- a/src/Umbraco.Web/Editors/DictionaryController.cs +++ b/src/Umbraco.Web/Editors/DictionaryController.cs @@ -219,7 +219,7 @@ namespace Umbraco.Web.Editors /// /// The list. /// - private void GetChildItemsForList(IDictionaryItem dictionaryItem, int level, List list) + private void GetChildItemsForList(IDictionaryItem dictionaryItem, int level, ICollection list) { foreach (var childItem in Services.LocalizationService.GetDictionaryItemChildren(dictionaryItem.Key).OrderBy(ItemSort())) { @@ -231,6 +231,6 @@ namespace Umbraco.Web.Editors } } - private Func ItemSort() => item => item.ItemKey; + private static Func ItemSort() => item => item.ItemKey; } } diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index 993489855f..396615a339 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -839,8 +839,6 @@ namespace Umbraco.Web.Editors return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.DocumentType: return UmbracoObjectTypes.DocumentType; - case UmbracoEntityTypes.Stylesheet: - return UmbracoObjectTypes.Stylesheet; case UmbracoEntityTypes.Member: return UmbracoObjectTypes.Member; case UmbracoEntityTypes.DataType: @@ -912,13 +910,31 @@ namespace Umbraco.Web.Editors case UmbracoEntityTypes.User: - long total; - var users = Services.UserService.GetAll(0, int.MaxValue, out total); + var users = Services.UserService.GetAll(0, int.MaxValue, out _); var filteredUsers = ExecutePostFilter(users, postFilter, postFilterParams); return Mapper.Map, IEnumerable>(filteredUsers); - case UmbracoEntityTypes.Domain: + case UmbracoEntityTypes.Stylesheet: + + if (!postFilter.IsNullOrWhiteSpace() || (postFilterParams != null && postFilterParams.Count > 0)) + throw new NotSupportedException("Filtering on stylesheets is not currently supported"); + + return Services.FileService.GetStylesheets().Select(Mapper.Map); + case UmbracoEntityTypes.Language: + + if (!postFilter.IsNullOrWhiteSpace() || (postFilterParams != null && postFilterParams.Count > 0)) + throw new NotSupportedException("Filtering on languages is not currently supported"); + + return Services.LocalizationService.GetAllLanguages().Select(Mapper.Map); + case UmbracoEntityTypes.DictionaryItem: + + if (!postFilter.IsNullOrWhiteSpace() || (postFilterParams != null && postFilterParams.Count > 0)) + throw new NotSupportedException("Filtering on languages is not currently supported"); + + return GetAllDictionaryItems(); + + case UmbracoEntityTypes.Domain: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } @@ -937,5 +953,36 @@ namespace Umbraco.Web.Editors } return entities; } + + + #region Methods to get all dictionary items + private IEnumerable GetAllDictionaryItems() + { + var list = new List(); + + foreach (var dictionaryItem in Services.LocalizationService.GetRootDictionaryItems().OrderBy(DictionaryItemSort())) + { + var item = Mapper.Map(dictionaryItem); + list.Add(item); + GetChildItemsForList(dictionaryItem, list); + } + + return list; + } + + private static Func DictionaryItemSort() => item => item.ItemKey; + + private void GetChildItemsForList(IDictionaryItem dictionaryItem, ICollection list) + { + foreach (var childItem in Services.LocalizationService.GetDictionaryItemChildren(dictionaryItem.Key).OrderBy(DictionaryItemSort())) + { + var item = Mapper.Map(childItem); + list.Add(item); + + GetChildItemsForList(childItem, list); + } + } + #endregion + } } diff --git a/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs b/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs index 04d06845d9..fcf7271673 100644 --- a/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs +++ b/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs @@ -86,8 +86,11 @@ namespace Umbraco.Web.Models.ContentEditing /// /// Property Group /// - PropertyGroup + PropertyGroup, - //TODO: Dictionary? + /// + /// Dictionary Item + /// + DictionaryItem } } diff --git a/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs index 94c43f8f11..b3f5f0374c 100644 --- a/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs @@ -9,6 +9,18 @@ namespace Umbraco.Web.Models.Mapping { public CodeFileMapperProfile() { + CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(sheet => sheet.Id)) + .ForMember(dest => dest.Alias, opt => opt.MapFrom(sheet => sheet.Alias)) + .ForMember(dest => dest.Key, opt => opt.MapFrom(sheet => sheet.Key)) + .ForMember(dest => dest.Name, opt => opt.MapFrom(sheet => sheet.Name)) + .ForMember(dest => dest.ParentId, opt => opt.UseValue(-1)) + .ForMember(dest => dest.Path, opt => opt.MapFrom(sheet => sheet.Path)) + .ForMember(dest => dest.Trashed, opt => opt.Ignore()) + .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()) + .ForMember(dest => dest.Udi, opt => opt.Ignore()) + .ForMember(dest => dest.Icon, opt => opt.Ignore()); + CreateMap() .ForMember(dest => dest.FileType, opt => opt.Ignore()) .ForMember(dest => dest.Notifications, opt => opt.Ignore()) diff --git a/src/Umbraco.Web/Models/Mapping/DictionaryMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/DictionaryMapperProfile.cs index ebd675f572..b3af04603c 100644 --- a/src/Umbraco.Web/Models/Mapping/DictionaryMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/DictionaryMapperProfile.cs @@ -17,6 +17,18 @@ namespace Umbraco.Web.Models.Mapping { public DictionaryMapperProfile(ILocalizationService localizationService) { + CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(sheet => sheet.Id)) + .ForMember(dest => dest.Alias, opt => opt.MapFrom(sheet => sheet.ItemKey)) + .ForMember(dest => dest.Key, opt => opt.MapFrom(sheet => sheet.Key)) + .ForMember(dest => dest.Name, opt => opt.MapFrom(sheet => sheet.ItemKey)) + .ForMember(dest => dest.ParentId, opt => opt.Ignore()) + .ForMember(dest => dest.Path, opt => opt.Ignore()) + .ForMember(dest => dest.Trashed, opt => opt.Ignore()) + .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()) + .ForMember(dest => dest.Udi, opt => opt.Ignore()) + .ForMember(dest => dest.Icon, opt => opt.Ignore()); + CreateMap() .ForMember(x => x.Translations, expression => expression.Ignore()) .ForMember(x => x.Notifications, expression => expression.Ignore()) diff --git a/src/Umbraco.Web/Models/Mapping/LanguageMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/LanguageMapperProfile.cs index f820d5ae54..ea29b671a6 100644 --- a/src/Umbraco.Web/Models/Mapping/LanguageMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/LanguageMapperProfile.cs @@ -12,6 +12,18 @@ namespace Umbraco.Web.Models.Mapping { public LanguageMapperProfile() { + CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(x => x.Id)) + .ForMember(dest => dest.Name, opt => opt.MapFrom(x => x.CultureName)) + .ForMember(dest => dest.Key, opt => opt.MapFrom(x => x.Key)) + .ForMember(dest => dest.Alias, opt => opt.MapFrom(x => x.IsoCode)) + .ForMember(dest => dest.ParentId, opt => opt.UseValue(-1)) + .ForMember(dest => dest.Path, opt => opt.Ignore()) + .ForMember(dest => dest.Trashed, opt => opt.Ignore()) + .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()) + .ForMember(dest => dest.Udi, opt => opt.Ignore()) + .ForMember(dest => dest.Icon, opt => opt.Ignore()); + CreateMap() .ForMember(l => l.Name, expression => expression.MapFrom(x => x.CultureInfo.DisplayName)); From b6a8ad1b6e9827c0a211b51af28e67c98cc36c94 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Wed, 16 Jan 2019 16:21:19 +0100 Subject: [PATCH 23/70] #3417 load available partial views from api --- .../src/common/resources/macro.resource.js | 7 + .../views/macros/macros.edit.controller.js | 144 +++++++++++------- src/Umbraco.Web/Editors/MacrosController.cs | 124 ++++++++++++++- 3 files changed, 215 insertions(+), 60 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index 9f22465757..237a361f7e 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -87,6 +87,13 @@ function macroResource($q, $http, umbRequestHelper) { ), 'Failed to create macro "' + name + '"' ); + }, + + getPartialViews: function() { + return umbRequestHelper.resourcePromise( + $http.get(umbRequestHelper.getApiUrl("macroApiBaseUrl", "GetPartialViews"), + "Failed to get partial views") + ); } }; } diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js index 81c699a05f..fa3a4e45a5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js @@ -6,77 +6,25 @@ * @description * The controller for editing macros. */ -function MacrosEditController($scope, $routeParams, macroResource, editorState, navigationService, dateHelper, userService, entityResource, formHelper, contentEditingHelper, localizationService, angularHelper) { +function MacrosEditController($scope, $q, $routeParams, macroResource, editorState, navigationService, dateHelper, userService, entityResource, formHelper, contentEditingHelper, localizationService, angularHelper) { var vm = this; + vm.promises = {}; + vm.page = {}; vm.page.loading = false; vm.page.saveButtonState = "init"; vm.page.menu = {} - vm.save = saveMacro; - vm.toggle = toggleValue; - - - init(); - - function init() { - vm.page.loading = true; - - - vm.page.navigation = [ - { - "name": "Settings", - "alias": "settings", - "icon": "icon-settings", - "view": "views/macros/views/settings.html", - "active": true - }, - { - "name": "Parameters", - "alias": "parameters", - "icon": "icon-list", - "view": "views/macros/views/parameters.html" - } - ]; - - vm.macro = { - "name": "Test macro", - "alias": "testMacro", - "id": 1, - "key": "unique key goes here", - "useInEditor": true, - "renderInEditor": false, - "cachePeriod": 2400, - "cacheByPage": true, - "cacheByUser": false, - "view": "Second", - "parameters": [ - { - "key": "title", - "label": "Label", - "editor": "editor" - }, - { - "key": "link", - "label": "Link", - "editor": "Link picker" - } - ] - } - - vm.views = ['First', 'Second', 'Third']; - - vm.parameterEditors = ['editor', 'Link picker', 'Image picker']; - - vm.page.loading = false; - } + function toggleValue(key) { vm.macro[key] = !vm.macro[key]; } + vm.toggle = toggleValue; + function saveMacro() { vm.page.saveButtonState = "busy"; @@ -98,6 +46,8 @@ function MacrosEditController($scope, $routeParams, macroResource, editorState, } } + vm.save = saveMacro; + function setFormDirty() { var currentForm = angularHelper.getCurrentForm($scope); @@ -108,6 +58,84 @@ function MacrosEditController($scope, $routeParams, macroResource, editorState, } vm.setDirty = setFormDirty; + + function getPartialViews() { + var deferred = $q.defer(); + + macroResource.getPartialViews().then(function (data) { + deferred.resolve(data); + }, function () { + deferred.reject(); + }); + + return deferred.promise; + } + + function init() { + vm.page.loading = true; + + vm.promises['partialViews'] = getPartialViews(); + + $q.all(vm.promises).then(function (values) { + var keys = Object.keys(values); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + + if (keys[i] === 'partialViews') { + vm.views = values[key]; + } + } + + vm.page.loading = false; + }); + + + vm.page.navigation = [ + { + "name": "Settings", + "alias": "settings", + "icon": "icon-settings", + "view": "views/macros/views/settings.html", + "active": true + }, + { + "name": "Parameters", + "alias": "parameters", + "icon": "icon-list", + "view": "views/macros/views/parameters.html" + } + ]; + + vm.macro = { + "name": "Test macro", + "alias": "testMacro", + "id": 1, + "key": "unique key goes here", + "useInEditor": true, + "renderInEditor": false, + "cachePeriod": 2400, + "cacheByPage": true, + "cacheByUser": false, + "view": "Second", + "parameters": [ + { + "key": "title", + "label": "Label", + "editor": "editor" + }, + { + "key": "link", + "label": "Link", + "editor": "Link picker" + } + ] + } + + vm.parameterEditors = ['editor', 'Link picker', 'Image picker']; + } + + init(); } angular.module("umbraco").controller("Umbraco.Editors.Macros.EditController", MacrosEditController); diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index f1d949231e..553924c3e6 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -14,6 +14,12 @@ using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Editors { + using System.Collections.Generic; + using System.IO; + using System.Linq; + + using Umbraco.Core.IO; + /// /// The API controller used for editing dictionary items /// @@ -48,7 +54,7 @@ namespace Umbraco.Web.Editors try { - var macro = new Macro { Alias = alias, Name = name, MacroSource = string.Empty}; + var macro = new Macro { Alias = alias, Name = name, MacroSource = string.Empty }; this.Services.MacroService.Save(macro, this.Security.CurrentUser.Id); @@ -58,7 +64,121 @@ namespace Umbraco.Web.Editors { this.Logger.Error(exception, "Error creating macro"); return Request.CreateNotificationValidationErrorResponse("Error creating dictionary item"); - } + } + } + + /// + /// Gets a list of available macro partials + /// + /// + /// The . + /// + public HttpResponseMessage GetPartialViews() + { + var views = new List(); + + views.AddRange(this.FindPartialViewsFiles()); + + return this.Request.CreateResponse(HttpStatusCode.OK, views); + } + + /// + /// Finds all the macro partials + /// + /// + /// The . + /// + private IEnumerable FindPartialViewsFiles() + { + var files = new List(); + + files.AddRange(this.FindPartialViewFilesInViewsFolder()); + files.AddRange(this.FindPartialViewFilesInPluginFolders()); + + return files; + } + + /// + /// Finds all macro partials in the views folder + /// + /// + /// The . + /// + private IEnumerable FindPartialViewFilesInViewsFolder() + { + var partialsDir = IOHelper.MapPath(SystemDirectories.MacroPartials); + + return this.FindPartialViewFilesInFolder( + partialsDir, + partialsDir, + SystemDirectories.MacroPartials); + } + + /// + /// Finds partial view files in app plugin folders. + /// + /// + /// The . + /// + private IEnumerable FindPartialViewFilesInPluginFolders() + { + var files = new List(); + + var appPluginsFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)); + + if (!appPluginsFolder.Exists) + { + return files; + } + + foreach (var directory in appPluginsFolder.GetDirectories()) + { + var viewsFolder = directory.GetDirectories("Views"); + if (viewsFolder.Any()) + { + var macroPartials = viewsFolder.First().GetDirectories("MacroPartials"); + if (macroPartials.Any()) + { + files.AddRange(this.FindPartialViewFilesInFolder(macroPartials.First().FullName, macroPartials.First().FullName, SystemDirectories.AppPlugins + "/" + directory.Name + "/Views/MacroPartials")); + } + } + } + + return files; + } + + /// + /// Finds all partial views in a folder and subfolders + /// + /// + /// The org path. + /// + /// + /// The path. + /// + /// + /// The prefix virtual path. + /// + /// + /// The . + /// + private IEnumerable FindPartialViewFilesInFolder(string orgPath, string path, string prefixVirtualPath) + { + var files = new List(); + var dirInfo = new DirectoryInfo(path); + + foreach (var dir in dirInfo.GetDirectories()) + { + files.AddRange(this.FindPartialViewFilesInFolder(orgPath, path + "/" + dir.Name, prefixVirtualPath)); + } + + var fileInfo = dirInfo.GetFiles("*.*"); + + files.AddRange( + fileInfo.Select(file => + prefixVirtualPath.TrimEnd('/') + "/" + (path.Replace(orgPath, string.Empty).Trim('/') + "/" + file.Name).Trim('/'))); + + return files; } } } From c0e62c4c5fa39ae3858eb5d74f0b3f417aeed10e Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Wed, 16 Jan 2019 16:37:33 +0100 Subject: [PATCH 24/70] #3417 retreive a list with parameter editors from API --- .../src/common/resources/macro.resource.js | 7 +++++++ .../macros/infiniteeditors/parameter.html | 2 +- .../views/macros/macros.edit.controller.js | 21 ++++++++++++++++--- src/Umbraco.Web/Editors/MacrosController.cs | 12 +++++++++++ 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index 237a361f7e..5313eadcaa 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -94,6 +94,13 @@ function macroResource($q, $http, umbRequestHelper) { $http.get(umbRequestHelper.getApiUrl("macroApiBaseUrl", "GetPartialViews"), "Failed to get partial views") ); + }, + + getParameterEditors: function () { + return umbRequestHelper.resourcePromise( + $http.get(umbRequestHelper.getApiUrl("macroApiBaseUrl", "GetParameterEditors"), + "Failed to get parameter editors") + ); } }; } diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html index ac01fa588e..bf9dbf86a3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html @@ -26,7 +26,7 @@ - + diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js index fa3a4e45a5..f8cde110e6 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js @@ -71,10 +71,23 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta return deferred.promise; } + function getParameterEditors() { + var deferred = $q.defer(); + + macroResource.getParameterEditors().then(function (data) { + deferred.resolve(data); + }, function () { + deferred.reject(); + }); + + return deferred.promise; + } + function init() { vm.page.loading = true; vm.promises['partialViews'] = getPartialViews(); + vm.promises['parameterEditors'] = getParameterEditors(); $q.all(vm.promises).then(function (values) { var keys = Object.keys(values); @@ -85,6 +98,10 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta if (keys[i] === 'partialViews') { vm.views = values[key]; } + + if (keys[i] === 'parameterEditors') { + vm.parameterEditors = values[key]; + } } vm.page.loading = false; @@ -130,9 +147,7 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta "editor": "Link picker" } ] - } - - vm.parameterEditors = ['editor', 'Link picker', 'Image picker']; + } } init(); diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 553924c3e6..6e2d032ad4 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -19,6 +19,7 @@ namespace Umbraco.Web.Editors using System.Linq; using Umbraco.Core.IO; + using Umbraco.Web.Composing; /// /// The API controller used for editing dictionary items @@ -82,6 +83,17 @@ namespace Umbraco.Web.Editors return this.Request.CreateResponse(HttpStatusCode.OK, views); } + /// + /// Gets the available parameter editors + /// + /// + /// The . + /// + public HttpResponseMessage GetParameterEditors() + { + return this.Request.CreateResponse(HttpStatusCode.OK, Current.ParameterEditors); + } + /// /// Finds all the macro partials /// From 355ac09d90f435f96a217c32ce9dbe93852a85bb Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 13:20:19 +1100 Subject: [PATCH 25/70] WIP - moved out the tree and section service from Core, these are web only things, removes their xml parsing, fixes base controller ctor params with UmbracoContext, need to implement tree/section collections taking into account controllers and not scanning so much --- .../Composing/Composers/ServicesComposer.cs | 4 - src/Umbraco.Core/Models/ApplicationTree.cs | 170 ---- src/Umbraco.Core/Models/Section.cs | 22 - src/Umbraco.Core/Services/ISectionService.cs | 114 --- src/Umbraco.Core/Services/ServiceContext.cs | 20 +- src/Umbraco.Core/Umbraco.Core.csproj | 4 - .../Cache/DistributedCacheBinderTests.cs | 7 - .../Packages/Document_Type_Picker_1.1.zip | Bin 0 -> 6147 bytes .../Services/SectionServiceTests.cs | 17 +- .../TestControllerActivatorBase.cs | 3 +- .../TestHelpers/TestObjects-Mocks.cs | 2 - src/Umbraco.Tests/TestHelpers/TestObjects.cs | 6 +- .../TreesAndSections/ApplicationTreeTest.cs | 724 ++++++++--------- .../TreesAndSections/SectionTests.cs | 454 +++++------ .../Cache/ApplicationTreeCacheRefresher.cs | 68 +- .../Cache/DistributedCacheBinder_Handlers.cs | 72 +- .../Cache/DistributedCacheExtensions.cs | 24 +- .../{ => Controllers}/TagsController.cs | 6 +- .../Editors/AuthenticationController.cs | 4 +- .../Editors/BackOfficeServerVariables.cs | 4 +- .../Editors/ContentTypeController.cs | 4 +- .../Editors/ContentTypeControllerBase.cs | 3 +- .../Editors/DashboardController.cs | 4 +- src/Umbraco.Web/Editors/DashboardSecurity.cs | 1 + src/Umbraco.Web/Editors/Dashboards.cs | 1 + src/Umbraco.Web/Editors/EntityController.cs | 16 +- .../Editors/MediaTypeController.cs | 3 +- .../Editors/MemberTypeController.cs | 3 +- .../Editors/PackageInstallController.cs | 4 +- src/Umbraco.Web/Editors/SectionController.cs | 30 +- .../UmbracoAuthorizedJsonController.cs | 4 +- .../Models/ContentEditing/ApplicationTree.cs | 177 +++++ .../ContentEditing/IBackOfficeSection.cs | 15 + .../Models/Mapping/SectionMapperProfile.cs | 3 +- .../Models/Mapping/UserMapperProfile.cs | 1 + .../Models/Trees/ApplicationAttribute.cs | 30 - .../Models/Trees/ApplicationDefinitions.cs | 90 ++- src/Umbraco.Web/Models/Trees/IApplication.cs | 10 - .../Mvc/SurfaceControllerTypeCollection.cs | 2 + .../Runtime/WebRuntimeComponent.cs | 2 + src/Umbraco.Web/Runtime/WebRuntimeComposer.cs | 11 + .../Search/SearchableTreeCollection.cs | 1 + .../Services/ApplicationTreeService.cs | 747 +++++++++--------- .../Services/IApplicationTreeService.cs | 121 +-- src/Umbraco.Web/Services/ISectionService.cs | 116 +++ src/Umbraco.Web/Services/SectionService.cs | 443 +++++------ .../Trees/ApplicationTreeController.cs | 33 +- .../Trees/BackOfficeSectionCollection.cs | 21 + src/Umbraco.Web/Trees/TreeCollection.cs | 27 + src/Umbraco.Web/Trees/TreeController.cs | 34 +- src/Umbraco.Web/Trees/TreeControllerBase.cs | 98 +-- ...xtensions.cs => TreeControllerResolver.cs} | 106 ++- .../UI/Pages/UmbracoEnsuredPage.cs | 14 +- src/Umbraco.Web/Umbraco.Web.csproj | 13 +- src/Umbraco.Web/UrlHelperExtensions.cs | 1 - .../Filters/LegacyTreeAuthorizeAttribute.cs | 29 - .../Filters/UmbracoTreeAuthorizeAttribute.cs | 23 +- .../WebApi/UmbracoApiController.cs | 4 +- .../WebApi/UmbracoApiControllerBase.cs | 11 +- .../UmbracoApiControllerTypeCollection.cs | 2 + .../WebApi/UmbracoAuthorizedApiController.cs | 4 +- .../_Legacy/PackageActions/addApplication.cs | 106 +-- 62 files changed, 2043 insertions(+), 2050 deletions(-) delete mode 100644 src/Umbraco.Core/Models/ApplicationTree.cs delete mode 100644 src/Umbraco.Core/Models/Section.cs delete mode 100644 src/Umbraco.Core/Services/ISectionService.cs create mode 100644 src/Umbraco.Tests/Packaging/Packages/Document_Type_Picker_1.1.zip rename src/Umbraco.Web/{ => Controllers}/TagsController.cs (89%) create mode 100644 src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs create mode 100644 src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs delete mode 100644 src/Umbraco.Web/Models/Trees/ApplicationAttribute.cs delete mode 100644 src/Umbraco.Web/Models/Trees/IApplication.cs rename src/{Umbraco.Core => Umbraco.Web}/Services/IApplicationTreeService.cs (52%) create mode 100644 src/Umbraco.Web/Services/ISectionService.cs create mode 100644 src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs create mode 100644 src/Umbraco.Web/Trees/TreeCollection.cs rename src/Umbraco.Web/Trees/{ApplicationTreeExtensions.cs => TreeControllerResolver.cs} (56%) delete mode 100644 src/Umbraco.Web/WebApi/Filters/LegacyTreeAuthorizeAttribute.cs diff --git a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs index 8c9ccd1088..0b83373d99 100644 --- a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs +++ b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs @@ -73,10 +73,6 @@ namespace Umbraco.Core.Composing.Composers factory.GetInstance(), factory.GetInstance(), new DirectoryInfo(IOHelper.GetRootDirectorySafe()))); - //TODO: These are replaced in the web project - we need to declare them so that - // something is wired up, just not sure this is very nice but will work for now. - composition.RegisterUnique(); - composition.RegisterUnique(); return composition; } diff --git a/src/Umbraco.Core/Models/ApplicationTree.cs b/src/Umbraco.Core/Models/ApplicationTree.cs deleted file mode 100644 index ccdebea724..0000000000 --- a/src/Umbraco.Core/Models/ApplicationTree.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using Umbraco.Core.Services; - -namespace Umbraco.Core.Models -{ - [DebuggerDisplay("Tree - {Title} ({ApplicationAlias})")] - public class ApplicationTree - { - private static readonly ConcurrentDictionary ResolvedTypes = new ConcurrentDictionary(); - - /// - /// Initializes a new instance of the class. - /// - public ApplicationTree() { } - - /// - /// Initializes a new instance of the class. - /// - /// if set to true [initialize]. - /// The sort order. - /// The application alias. - /// The tree alias. - /// The tree title. - /// The icon closed. - /// The icon opened. - /// The tree type. - public ApplicationTree(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - { - Initialize = initialize; - SortOrder = sortOrder; - ApplicationAlias = applicationAlias; - Alias = alias; - Title = title; - IconClosed = iconClosed; - IconOpened = iconOpened; - Type = type; - - } - - /// - /// Gets or sets a value indicating whether this should initialize. - /// - /// true if initialize; otherwise, false. - public bool Initialize { get; set; } - - /// - /// Gets or sets the sort order. - /// - /// The sort order. - public int SortOrder { get; set; } - - /// - /// Gets the application alias. - /// - /// The application alias. - public string ApplicationAlias { get; } - - /// - /// Gets the tree alias. - /// - /// The alias. - public string Alias { get; } - - /// - /// Gets or sets the tree title. - /// - /// The title. - public string Title { get; set; } - - /// - /// Gets or sets the icon closed. - /// - /// The icon closed. - public string IconClosed { get; set; } - - /// - /// Gets or sets the icon opened. - /// - /// The icon opened. - public string IconOpened { get; set; } - - /// - /// Gets or sets the tree type assembly name. - /// - /// The type. - public string Type { get; set; } - - /// - /// Returns the localized root node display name - /// - /// - /// - public string GetRootNodeDisplayName(ILocalizedTextService textService) - { - var label = $"[{Alias}]"; - - // try to look up a the localized tree header matching the tree alias - var localizedLabel = textService.Localize("treeHeaders/" + Alias); - - // if the localizedLabel returns [alias] then return the title attribute from the trees.config file, if it's defined - if (localizedLabel != null && localizedLabel.Equals(label, StringComparison.InvariantCultureIgnoreCase)) - { - if (string.IsNullOrEmpty(Title) == false) - label = Title; - } - else - { - // the localizedLabel translated into something that's not just [alias], so use the translation - label = localizedLabel; - } - - return label; - } - - private Type _runtimeType; - - /// - /// Returns the CLR type based on it's assembly name stored in the config - /// - /// - public Type GetRuntimeType() - { - return _runtimeType ?? (_runtimeType = System.Type.GetType(Type)); - } - - /// - /// Used to try to get and cache the tree type - /// - /// - /// - internal static Type TryGetType(string type) - { - try - { - return ResolvedTypes.GetOrAdd(type, s => - { - var result = System.Type.GetType(type); - if (result != null) - { - return result; - } - - //we need to implement a bit of a hack here due to some trees being renamed and backwards compat - var parts = type.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length != 2) - throw new InvalidOperationException("Could not resolve type"); - if (parts[1].Trim() != "Umbraco.Web" || parts[0].StartsWith("Umbraco.Web.Trees") == false || parts[0].EndsWith("Controller")) - throw new InvalidOperationException("Could not resolve type"); - - //if it's one of our controllers but it's not suffixed with "Controller" then add it and try again - var tempType = parts[0] + "Controller, Umbraco.Web"; - - result = System.Type.GetType(tempType); - if (result != null) - return result; - - throw new InvalidOperationException("Could not resolve type"); - }); - } - catch (InvalidOperationException) - { - //swallow, this is our own exception, couldn't find the type - // fixme bad use of exceptions here! - return null; - } - } - } -} diff --git a/src/Umbraco.Core/Models/Section.cs b/src/Umbraco.Core/Models/Section.cs deleted file mode 100644 index 4b7f8309dd..0000000000 --- a/src/Umbraco.Core/Models/Section.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Umbraco.Core.Models -{ - /// - /// Represents a section defined in the app.config file. - /// - public class Section - { - public Section(string name, string @alias, int sortOrder) - { - Name = name; - Alias = alias; - SortOrder = sortOrder; - } - - public Section() - { } - - public string Name { get; set; } - public string Alias { get; set; } - public int SortOrder { get; set; } - } -} diff --git a/src/Umbraco.Core/Services/ISectionService.cs b/src/Umbraco.Core/Services/ISectionService.cs deleted file mode 100644 index 899ae78245..0000000000 --- a/src/Umbraco.Core/Services/ISectionService.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Collections.Generic; -using Umbraco.Core.Models; - -namespace Umbraco.Core.Services -{ - public interface ISectionService - { - /// - /// The cache storage for all applications - /// - IEnumerable
GetSections(); - - /// - /// Get the user group's allowed sections - /// - /// - /// - IEnumerable
GetAllowedSections(int userId); - - /// - /// Gets the application by its alias. - /// - /// The application alias. - /// - Section GetByAlias(string appAlias); - - /// - /// Creates a new applcation if no application with the specified alias is found. - /// - /// The application name. - /// The application alias. - /// The application icon, which has to be located in umbraco/images/tray folder. - void MakeNew(string name, string alias, string icon); - - /// - /// Makes the new. - /// - /// The name. - /// The alias. - /// The icon. - /// The sort order. - void MakeNew(string name, string alias, string icon, int sortOrder); - - /// - /// Deletes the section - /// - void DeleteSection(Section section); - } - - /// - /// Purely used to allow a service context to create the default services - /// - internal class EmptySectionService : ISectionService - { - /// - /// The cache storage for all applications - /// - public IEnumerable
GetSections() - { - throw new System.NotImplementedException(); - } - - /// - /// Get the user's allowed sections - /// - /// - /// - public IEnumerable
GetAllowedSections(int userId) - { - throw new System.NotImplementedException(); - } - - /// - /// Gets the application by its alias. - /// - /// The application alias. - /// - public Section GetByAlias(string appAlias) - { - throw new System.NotImplementedException(); - } - - /// - /// Creates a new applcation if no application with the specified alias is found. - /// - /// The application name. - /// The application alias. - /// The application icon, which has to be located in umbraco/images/tray folder. - public void MakeNew(string name, string alias, string icon) - { - throw new System.NotImplementedException(); - } - - /// - /// Makes the new. - /// - /// The name. - /// The alias. - /// The icon. - /// The sort order. - public void MakeNew(string name, string alias, string icon, int sortOrder) - { - throw new System.NotImplementedException(); - } - - /// - /// Deletes the section - /// - public void DeleteSection(Section section) - { - throw new System.NotImplementedException(); - } - } -} diff --git a/src/Umbraco.Core/Services/ServiceContext.cs b/src/Umbraco.Core/Services/ServiceContext.cs index 731d3a58c6..6d7ac8a5e7 100644 --- a/src/Umbraco.Core/Services/ServiceContext.cs +++ b/src/Umbraco.Core/Services/ServiceContext.cs @@ -25,8 +25,6 @@ namespace Umbraco.Core.Services private readonly Lazy _serverRegistrationService; private readonly Lazy _entityService; private readonly Lazy _relationService; - private readonly Lazy _treeService; - private readonly Lazy _sectionService; private readonly Lazy _macroService; private readonly Lazy _memberTypeService; private readonly Lazy _memberGroupService; @@ -38,7 +36,7 @@ namespace Umbraco.Core.Services /// /// Initializes a new instance of the class with lazy services. /// - public ServiceContext(Lazy publicAccessService, Lazy domainService, Lazy auditService, Lazy localizedTextService, Lazy tagService, Lazy contentService, Lazy userService, Lazy memberService, Lazy mediaService, Lazy contentTypeService, Lazy mediaTypeService, Lazy dataTypeService, Lazy fileService, Lazy localizationService, Lazy packagingService, Lazy serverRegistrationService, Lazy entityService, Lazy relationService, Lazy treeService, Lazy sectionService, Lazy macroService, Lazy memberTypeService, Lazy memberGroupService, Lazy notificationService, Lazy externalLoginService, Lazy redirectUrlService, Lazy consentService) + public ServiceContext(Lazy publicAccessService, Lazy domainService, Lazy auditService, Lazy localizedTextService, Lazy tagService, Lazy contentService, Lazy userService, Lazy memberService, Lazy mediaService, Lazy contentTypeService, Lazy mediaTypeService, Lazy dataTypeService, Lazy fileService, Lazy localizationService, Lazy packagingService, Lazy serverRegistrationService, Lazy entityService, Lazy relationService, Lazy macroService, Lazy memberTypeService, Lazy memberGroupService, Lazy notificationService, Lazy externalLoginService, Lazy redirectUrlService, Lazy consentService) { _publicAccessService = publicAccessService; _domainService = domainService; @@ -58,8 +56,6 @@ namespace Umbraco.Core.Services _serverRegistrationService = serverRegistrationService; _entityService = entityService; _relationService = relationService; - _treeService = treeService; - _sectionService = sectionService; _macroService = macroService; _memberTypeService = memberTypeService; _memberGroupService = memberGroupService; @@ -90,8 +86,6 @@ namespace Umbraco.Core.Services IMemberTypeService memberTypeService = null, IMemberService memberService = null, IUserService userService = null, - ISectionService sectionService = null, - IApplicationTreeService treeService = null, ITagService tagService = null, INotificationService notificationService = null, ILocalizedTextService localizedTextService = null, @@ -125,8 +119,6 @@ namespace Umbraco.Core.Services Lazy(serverRegistrationService), Lazy(entityService), Lazy(relationService), - Lazy(treeService), - Lazy(sectionService), Lazy(macroService), Lazy(memberTypeService), Lazy(memberGroupService), @@ -236,16 +228,6 @@ namespace Umbraco.Core.Services ///
public IMemberService MemberService => _memberService.Value; - /// - /// Gets the - /// - public ISectionService SectionService => _sectionService.Value; - - /// - /// Gets the - /// - public IApplicationTreeService ApplicationTreeService => _treeService.Value; - /// /// Gets the MemberTypeService /// diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 2236854351..8395dd9cb8 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -678,7 +678,6 @@ - @@ -875,7 +874,6 @@ - @@ -1390,7 +1388,6 @@ - @@ -1420,7 +1417,6 @@ - diff --git a/src/Umbraco.Tests/Cache/DistributedCacheBinderTests.cs b/src/Umbraco.Tests/Cache/DistributedCacheBinderTests.cs index 50b27da89f..3532a11c63 100644 --- a/src/Umbraco.Tests/Cache/DistributedCacheBinderTests.cs +++ b/src/Umbraco.Tests/Cache/DistributedCacheBinderTests.cs @@ -47,13 +47,6 @@ namespace Umbraco.Tests.Cache //Permission.Deleted += PermissionDeleted; //PermissionRepository.AssignedPermissions += CacheRefresherEventHandler_AssignedPermissions; - new EventDefinition(null, serviceContext.ApplicationTreeService, new EventArgs(), "Deleted"), - new EventDefinition(null, serviceContext.ApplicationTreeService, new EventArgs(), "Updated"), - new EventDefinition(null, serviceContext.ApplicationTreeService, new EventArgs(), "New"), - - new EventDefinition(null, serviceContext.SectionService, new EventArgs(), "Deleted"), - new EventDefinition(null, serviceContext.SectionService, new EventArgs(), "New"), - new EventDefinition>(null, serviceContext.UserService, new SaveEventArgs(Enumerable.Empty())), new EventDefinition>(null, serviceContext.UserService, new DeleteEventArgs(Enumerable.Empty())), new EventDefinition>(null, serviceContext.UserService, new SaveEventArgs(Enumerable.Empty())), diff --git a/src/Umbraco.Tests/Packaging/Packages/Document_Type_Picker_1.1.zip b/src/Umbraco.Tests/Packaging/Packages/Document_Type_Picker_1.1.zip new file mode 100644 index 0000000000000000000000000000000000000000..18449bd3735870c98e711525a7ea9883941e321f GIT binary patch literal 6147 zcma)=RZJWVl!bAp6qn)@DHL~ich`a9GDv|U9o*dqXP~$j8>HwIcc+6CcZxg3_Ww7V z%_f^o_TGmt_vYr@m-BSARFP4L5D*YB5dOwu%SOrHjmG{vav>nF{0m`zTP^`UD|RbO zJ{xvEJ{}u(VJ6 z>RqIdc64-an*}K5AZ-UAemx4uIqk2~WIP~j*f$8$!If+UInR2e$q(g!=FuH-F4L-4 z9dYM91Y;{#CsPV><>WPb+O>B}bWg&$d6f8SWagJ$DRHjNnOwXeRSe4r{pSursKP2+ z5*!Csj==m?xdmqNt(gZb?I}|u@T-17dXyRCfw)Zm+V*Ay#4LOW7g^5bn$2t^_RxbI zb~nFqnEJIPe82VAW1vgLGN5?NciA2C@u8*RO#64`l1El`KGb^eq{hBl4d;)_RN9|h z;2vSvnrG6N7_BRX3JZ;r19(S{2)`5E;kr~#Mr_~Kl~nJtaO8z|tn0FriIPLEk-0X6 zvkrodN)M#{Ib62%^qF1q_<~==kbKIOK6YgSp`>(Lk|N2qo8u_hSPg*eGz2WtsELJg z&i!U|fb7dz**KzB*2#Yx-xvl~W{KI5olssKlTbSoK4HwQbkz%LRT0Zs&^mDvdZM^f zaJ6-Hs!Z$PJ3v>ei2UT60fWv}du)Y_hI){-2L5Ct%oxT=k6UZvoJj>&I^!)jbKH&Z zn`AY%?Dat5!Xs-{1DBUi;|eN+y0ooBU9<+W zXtE^aR5vrFAIN4;N9Ijz8F;tVH*fW17b6FKG25!*j&7OkS`7Kf{_6PgnqvHT(@?hk zLv`$3uPtrWhuOD|xBV3K-Z=x^L*J84#xI&3h8UoEF81qz>!y#mJLY5D1@>wIkH3r( zKD4hMlFtyiV)%T#VfSo7!H3Sox<$um(_bE!wiwmw%hWWmIl0OA#aZY==|=ILqn824 zdZOgHV!5W3XWn)GHS;s9Br+0=)89}`$X;b0zt|G{kaO!YVoO;^U|9U?4*?C z!%|*r>zZj^}+;2PT53CIGVe$h&mj**Cis2A- z`8%{XPB83WbizI%%r;n-d1*hl?rK}yc6^H~msEv1`WhYfE;4vHO~yK60KQbPy+H~& z`rp(kJ4~kAZ*nz~nKy2r#MMU^21S{qW`tix;>?ZXUT`dLZ6bRY-q$g#o^Br|Ldz)_ zDg*O{d2CY7!@cjB=Op+FYx~N>fq<(Ap`nroe+W26+&nUTGK}0iDtO^=(%MYj)iRO# z?oT?0ZWTHZ_P``(^9-`JtTQyLdIA#NI|)c0!3Dc?);nWKZ{Cszq-_5F9y*io>5Hs_ zAnWq_~2s-hqXHNdHM>xV6h`*qRK!=$MrB=hXz+vHdBI$$LU=ggLL z^jO=a$aVtKjpt#M5lUhlQ9Qx@QXkS}vB$}6U~xu4-=rlJC}joEaE7=&(6 z-FR1gL)Z7leecjH^`_wsAd@Ib5u$uuuP82a*C4daRl_d$88oY z?qOz0+t3y^;Qp(6uXXmoj0;jop*I%skt<_q-YP(blUACHztsDilz|0Jd@ULU$sc+RLK@h*@r?;B}v z5IR{Rml=D#;)V+nRmdHtzuv~~FmDRVv)(rn+fk1Yzhcp14yw3Di#tW^85Hq1ZQVh1EGVb^Pax`C0-tS*wo!YH)*C?b4l>Vd)h$bQvM zNSz2P#E`kRXV;MRxn)F7ARMWiXcSQ(iu@Eq6X`bGc#i~zADH>Am4e1_OzOkKBI!m< z5joA{8()ep_|OZrSOWD$LqRZUQF*|}qFR(&V0a?+IQvVvdeiP8IhwTVglv`-h2`=uZ zwI0SrzXM<)cRy#(T3;a9U#glApBlWuG3yBb(Dk~5p$5_3H;wnI@2XOw=YrfS{!*7u z!a)pbk#MBP%1@F8K3KPxe-~fzp(YrDTIB`9&np ztMlJ}{Q*|$yDUgbRY&CGkDxUh_5?3`NWEGwS7;n+Y6(spup!c*h{@AP*SUfef@0ej zlCCAABKL2mkX~}vCOp`U((16TP~2 zxKU*Dd2$2VNmPQMwt~1_3Aj|k8m7@uWe7mq1%nXTy!oGrE^CkEty^Pbnro5D>Aspl ziUt=k7gWZqNu}1Qa&_*oo?Z2$e^eRLTjSg3$omYe6;Z8!i9pU+Of8oM{Iqvl_}wkRr_ix0&v0i6~@8!2pJC z0?yO1Lt}PzprseZS^620EvXAmX#;6|$gCV5aw66pHHh;7pohN53HJUgym11h0jGT- znJ#Tb$S;1B9Xh0Q7{kcJ_icsw*?<*Go{dAqDRdLD{m}#B1gZm$H28~O^a20@7UFd; z^36^G%h6?Y1+qrj_`+%8r5B+Oov?kBJsBZ})OR8HZny>6jN6V{zL7h7RpcaO z5gO`zz>0is7z+KjO(6iDFK#}CfU5I7l!)6=*Ub>G`aIq+tQvmPydGtaCD@oHL7j90pUrRf%j^&T{Jpd~)}G*FsWLG6xG|$2-QLDh zs_|#`jtveNrTh3?w*S(#Uy?=#qbF-XKV_X`86NIM@j3^XQuIuxS==-_^47lWv$vJq zAS-P47_7Qm>CT+iJm*k8G{$l8J-3y)##sctTD3kLG_*=!qr&g1_QQB(#59Eb%crLV zyB0Zy2en_nt@k~(T!~f6Jdu38;wfg|vSD{Jz{iU_vPH+URQobavCM`S`ojBP9;v#WL= z>Z>yLbwtLvJL$L%%hHAtZ)_WxxdjDH?IaWh#|7-DgT4f|^*0Mk?5N0h@9(^Ql#GIQ zIPZo_?1=li8lhhfl>D5VUi_o>5u6|BkcdlML!dv$Kug0CZ>N#VXU~Vj14NKiemoKL z8^EUPT9E^p7+)OUXJn4d@ETz@+s$N&yHVJsIlvm?kZ-d?&o2WH?C?`O%u(#MA9=o$ zFRG_EyMLUP8e&~#83rVlo?X{NHswSt)xi)PQDuT0WK_FkPNI*INOd%XY!yZvU(ZCP zliy@uGXh7|XauM@$j8aYgvj>o&U@JHj=HIZDP;bHTs~l z#J%r#h;A3H8V{i4hs=?{$rrsAJ!&sZf`nK1fw!_E1@2Ahg8SUhmgqI(azDLQ4M@iN zC^^OE24Bns*a5 zYX13M#}>VKWJ{)NbfNLRWwol7POHxS-zz(`+@#DH?~BEaN{`5>vKM7uzs4yEHtZ6? z%b<$VnhJ`OpC?)Tqq&=9t&ST?%NVFxmMrV7#gut+RWr>z947bo(U#Wsuepn;P z2CFR7mLNf@aY{4MQuz%Ey_;>92&Gazd0)1pkuV>KwP$FYH0)fzzAyzRb18KS!#fP| zDm)@sn%t?!zS76PA{H;7zsbm`LvQ< zujr5-h3qLt)ms{ZJ(|eq>yHUna6T$~q`<+!`i{I(0_}hdrjfw{)sLA>FU8Y#MTJzp z*e50C?c_m#FH~OBZ=h(72(>P=r?NoiPd(G^7sqAn!C@OdA#19pGdl0kztLc)mT@T{ z7Be~GoNdd0Ql|LXVMXGm$s{cIE-K^)y>^vSo|GH9rXpxxY-9~l>K#GNBhG=cQF4E7 zPQ)#W|4u#$G>eS?!x}d`c5DPSs!rJR`EPK;qm=L;;3B%{6}`SczsYyVAJc^r&E~K3qG|;RjqSU&+G3p*#4?VcqDZL6ezyGN!?Y&PAwMCGXttI%{xhL8yTaq?Eq< z!Dq0=I+ttmY;wh-`*-ieub$qXlxxTIW~q$@is3z}pp}|?M^7ZTK{O0Ozv+k!XItJ+ ztD2PAu@d&U|2j?_Wf89v($Jg`iub|tXMYh$t*YDIY6l0NCw1QrW4HSAJsemBZ5|$j zc=CN$8#*Yuse0CY|4tT1nYIGD4da+(W(J81-!t|qml8NsXvJnZY`DH*u52LwX6eOO zS=lmpgRjK@9j`nq4@p?zC}%LCs(}HYF7g11dgq<8GP&Ae+?Lx6RC8wWoWnR|#or^n z#*ni+O-L?dB$%ySp}o{={FHmXPRfKTAdMzNu`Kd!M#z({447Y!hR=?#UPT;3TsRPy zp4Ci{VaAufHd_@(ddu4eCH3r1WMq6r})JmSFPFdJrM`@a{?6axWC`G}A^DqGoIlg>9x%ssmFHAc zA;yh4FL&ObY{WN%1-N@ZkQEL$$G;3WwzQ5C?2izkG6-CG9J)TO|IP@-u!NrV(IF!O z^B$y&*w-qd>0l#76lq7<_+~i>wK9}j-kQ0>a__4_Y*flT4t|0TMxo|Gdl@&YMrW|_ zyf>Rk#+sy%!PnQtW14igo!1F%z6^)&_4m-!DYYxrb*s~~n$M{#zt~jJ>Kv8V(9+i4 z*g{(07N zU#$Pmp^gUD6>_j~06U-(Tzh@KF1lDf`}$<|G`?Nw)~I&+x44+O+%wT@SuA!g(T~rN zmHKA#w_@Giy|&*|g5qw%ZWaBZm22Khof#gU!Ab#UAiM>3)4w63*ZCrZ{O}|}InXr) zDEm-=^Z;@c|HA%q!+sU`IP!MD@9;zfov$>&X%zS7{fYQ{R}k>5k%iHQbAPk6 zv>`9*-r5WeOnzihj!z!MY(Xwx=F_No(zlR6)h*&N*Y?j*K;h+iW6?!6m(t{sdS4>4 zTY#&rxiRB(jqCp|IZW2TpJOt1#LY=mIgpIsnu_FWt6e;Mw;{xXkgAk8nI`qZsD(Bv zyvkm`XZB0;m2<6&qi_R=jZU%pn;+RV=FBo@`K9B9KhnO?%gL_4Nh)<;z>P1{#oja~ zP5Tq~;tO(M&{(VFdC$4z)(}~%)j} zHaDuLH34?Tfy}eJl|Mlb3)|1$JHVBocd@TYa85+6|IRZ*9m?fCGU0)xkq{6-Cf*ZaN#F@~PP8t@EI#8X^FN|lf;z-*2tigPkH zbrg##Zrs60*X2O={)MXU%7Jr7nG#W4#aq<9*%R6EOj#p%)rC#(AeEk5y&=)qjcZUYRKJY3dvzFX0C%hZGvfmP~T#f zQE#0|`ZS;WNqe8?#T>YB${6@t4y*v{!=MN#$xTUjBy>z@K=aez!CKP*$1RsptqQGc zk|dGUV%496zS~E$+R}9%)*?sIBLm?z(d9%m`4Vn|Q4@2fa3w3t2p9ictT=2AdNUk? zLMN+KIpxkKthpLGVjEiap8)2v_dljd3GU)?Wp^bc@nX?%6L_7;3XYi#EDg^QzNTP` zBCVgG%9kK`2UACUoY-(lhqhT1bsm4*L4MLduukZszN-JxqW4DwVYV}pKLAJ%KHlO7 zpyewOysjBD1=o3I%T2PT-pko?rE%RcxC@rsV8_gkw$Oz4V4M&15?no@=0_tjhZ+fC z8$IL`v60`W-u5o)k=v(nZlh|cA|eqX{NLI6KX&^c_5V%M|5cUzFV+9;;P?NfNc#_` z|9SmC{EUV0?-Bt45rGV0H$DE%j^h-f<+aM~_CI_MRr*hAsiLC&dxP{(H~m8q(toG_ E0K6^9ApigX literal 0 HcmV?d00001 diff --git a/src/Umbraco.Tests/Services/SectionServiceTests.cs b/src/Umbraco.Tests/Services/SectionServiceTests.cs index ca5d755220..206c99ffbf 100644 --- a/src/Umbraco.Tests/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests/Services/SectionServiceTests.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using Umbraco.Core.Models.Membership; using Umbraco.Tests.Testing; +using Umbraco.Web.Services; namespace Umbraco.Tests.Services { @@ -14,24 +15,20 @@ namespace Umbraco.Tests.Services [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] public class SectionServiceTests : TestWithSomeContentBase { - public override void CreateTestData() - { - base.CreateTestData(); - - ServiceContext.SectionService.MakeNew("Content", "content", "icon-content"); - ServiceContext.SectionService.MakeNew("Media", "media", "icon-media"); - ServiceContext.SectionService.MakeNew("Settings", "settings", "icon-settings"); - ServiceContext.SectionService.MakeNew("Developer", "developer", "icon-developer"); - } + //fixme + private ISectionService SectionService => new SectionService(ServiceContext.UserService, null, null); + [Test] public void SectionService_Can_Get_Allowed_Sections_For_User() { + //fixme - need to mock + // Arrange var user = CreateTestUser(); // Act - var result = ServiceContext.SectionService.GetAllowedSections(user.Id).ToList(); + var result = SectionService.GetAllowedSections(user.Id).ToList(); // Assert Assert.AreEqual(3, result.Count); diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 9e2a2156ee..31ee34843d 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -60,8 +60,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting memberTypeService: mockedMemberTypeService, dataTypeService: mockedDataTypeService, contentTypeService: mockedContentTypeService, - localizedTextService:Mock.Of(), - sectionService:Mock.Of()); + localizedTextService:Mock.Of()); var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 8c230f98d0..4dfaa9e674 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -73,8 +73,6 @@ namespace Umbraco.Tests.TestHelpers MockService(container), MockService(container), MockService(container), - MockService(container), - MockService(container), MockService(container), MockService(container), MockService(container), diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 14ffeb743f..f7f0d26c0e 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -188,9 +188,7 @@ namespace Umbraco.Tests.TestHelpers new DirectoryInfo(IOHelper.GetRootDirectorySafe()))); }); var relationService = GetLazyService(factory, c => new RelationService(scopeProvider, logger, eventMessagesFactory, entityService.Value, GetRepo(c), GetRepo(c))); - var treeService = GetLazyService(factory, c => new ApplicationTreeService(logger, cache, typeLoader)); - var tagService = GetLazyService(factory, c => new TagService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); - var sectionService = GetLazyService(factory, c => new SectionService(userService.Value, treeService.Value, scopeProvider, cache)); + var tagService = GetLazyService(factory, c => new TagService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var redirectUrlService = GetLazyService(factory, c => new RedirectUrlService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); var consentService = GetLazyService(factory, c => new ConsentService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); @@ -213,8 +211,6 @@ namespace Umbraco.Tests.TestHelpers serverRegistrationService, entityService, relationService, - treeService, - sectionService, macroService, memberTypeService, memberGroupService, diff --git a/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs b/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs index 951246c535..95d90f1463 100644 --- a/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs +++ b/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs @@ -1,397 +1,397 @@ -using System.IO; -using NUnit.Framework; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using System; -using System.Linq; -using System.Threading; -using Umbraco.Tests.Testing; -using Umbraco.Web.Services; -using Current = Umbraco.Web.Composing.Current; +//using System.IO; +//using NUnit.Framework; +//using Umbraco.Core.Services; +//using Umbraco.Tests.TestHelpers; +//using System; +//using System.Linq; +//using System.Threading; +//using Umbraco.Tests.Testing; +//using Umbraco.Web.Services; +//using Current = Umbraco.Web.Composing.Current; -namespace Umbraco.Tests.TreesAndSections -{ +//namespace Umbraco.Tests.TreesAndSections +//{ - /// - ///This is a test class for ApplicationTreeTest and is intended - ///to contain all ApplicationTreeTest Unit Tests - /// - [TestFixture] - [Apartment(ApartmentState.STA)] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class ApplicationTreeTest : TestWithDatabaseBase - { - public override void SetUp() - { - base.SetUp(); +// /// +// ///This is a test class for ApplicationTreeTest and is intended +// ///to contain all ApplicationTreeTest Unit Tests +// /// +// [TestFixture] +// [Apartment(ApartmentState.STA)] +// [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] +// public class ApplicationTreeTest : TestWithDatabaseBase +// { +// public override void SetUp() +// { +// base.SetUp(); - var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); - var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); - Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); - using (var writer = File.CreateText(treesConfig)) - { - writer.Write(ResourceFiles.trees); - } - using (var writer = File.CreateText(appConfig)) - { - writer.Write(ResourceFiles.applications); - } +// var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); +// var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); +// Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); +// using (var writer = File.CreateText(treesConfig)) +// { +// writer.Write(ResourceFiles.trees); +// } +// using (var writer = File.CreateText(appConfig)) +// { +// writer.Write(ResourceFiles.applications); +// } - ApplicationTreeService.TreeConfigFilePath = treesConfig; - SectionService.AppConfigFilePath = appConfig; - } +// //ApplicationTreeService.TreeConfigFilePath = treesConfig; +// SectionService.AppConfigFilePath = appConfig; +// } - public override void TearDown() - { - base.TearDown(); +// public override void TearDown() +// { +// base.TearDown(); - if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) - { - Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); - } - ApplicationTreeService.TreeConfigFilePath = null; - SectionService.AppConfigFilePath = null; - } +// if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) +// { +// Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); +// } +// //ApplicationTreeService.TreeConfigFilePath = null; +// SectionService.AppConfigFilePath = null; +// } - /// - /// Creates a new app tree linked to an application, then delete the application and make sure the tree is gone as well - /// - [Test()] - public void ApplicationTree_Make_New_Then_Delete_App() - { - //create new app - var appName = Guid.NewGuid().ToString("N"); - var treeName = Guid.NewGuid().ToString("N"); - Current.Services.SectionService.MakeNew(appName, appName, "icon.jpg"); +// ///// +// ///// Creates a new app tree linked to an application, then delete the application and make sure the tree is gone as well +// ///// +// //[Test()] +// //public void ApplicationTree_Make_New_Then_Delete_App() +// //{ +// // //create new app +// // var appName = Guid.NewGuid().ToString("N"); +// // var treeName = Guid.NewGuid().ToString("N"); +// // Current.Services.SectionService.MakeNew(appName, appName, "icon.jpg"); - //check if it exists - var app = Current.Services.SectionService.GetByAlias(appName); - Assert.IsNotNull(app); +// // //check if it exists +// // var app = Current.Services.SectionService.GetByAlias(appName); +// // Assert.IsNotNull(app); - //create the new app tree assigned to the new app - Current.Services.ApplicationTreeService.MakeNew(false, 0, app.Alias, treeName, treeName, "icon.jpg", "icon.jpg", "Umbraco.Web.Trees.ContentTreeController, Umbraco.Web"); - var tree = Current.Services.ApplicationTreeService.GetByAlias(treeName); - Assert.IsNotNull(tree); +// // //create the new app tree assigned to the new app +// // Current.Services.ApplicationTreeService.MakeNew(false, 0, app.Alias, treeName, treeName, "icon.jpg", "icon.jpg", "Umbraco.Web.Trees.ContentTreeController, Umbraco.Web"); +// // var tree = Current.Services.ApplicationTreeService.GetByAlias(treeName); +// // Assert.IsNotNull(tree); - //now delete the app - Current.Services.SectionService.DeleteSection(app); +// // //now delete the app +// // Current.Services.SectionService.DeleteSection(app); - //check that the tree is gone - Assert.AreEqual(0, Current.Services.ApplicationTreeService.GetApplicationTrees(treeName).Count()); - } +// // //check that the tree is gone +// // Assert.AreEqual(0, Current.Services.ApplicationTreeService.GetApplicationTrees(treeName).Count()); +// //} - #region Tests to write - ///// - /////A test for ApplicationTree Constructor - ///// - //[TestMethod()] - //public void ApplicationTreeConstructorTest() - //{ - // bool silent = false; // TODO: Initialize to an appropriate value - // bool initialize = false; // TODO: Initialize to an appropriate value - // byte sortOrder = 0; // TODO: Initialize to an appropriate value - // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value - // string alias = string.Empty; // TODO: Initialize to an appropriate value - // string title = string.Empty; // TODO: Initialize to an appropriate value - // string iconClosed = string.Empty; // TODO: Initialize to an appropriate value - // string iconOpened = string.Empty; // TODO: Initialize to an appropriate value - // string assemblyName = string.Empty; // TODO: Initialize to an appropriate value - // string type = string.Empty; // TODO: Initialize to an appropriate value - // string action = string.Empty; // TODO: Initialize to an appropriate value - // ApplicationTree target = new ApplicationTree(silent, initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, assemblyName, type, action); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} +// #region Tests to write +// ///// +// /////A test for ApplicationTree Constructor +// ///// +// //[TestMethod()] +// //public void ApplicationTreeConstructorTest() +// //{ +// // bool silent = false; // TODO: Initialize to an appropriate value +// // bool initialize = false; // TODO: Initialize to an appropriate value +// // byte sortOrder = 0; // TODO: Initialize to an appropriate value +// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value +// // string alias = string.Empty; // TODO: Initialize to an appropriate value +// // string title = string.Empty; // TODO: Initialize to an appropriate value +// // string iconClosed = string.Empty; // TODO: Initialize to an appropriate value +// // string iconOpened = string.Empty; // TODO: Initialize to an appropriate value +// // string assemblyName = string.Empty; // TODO: Initialize to an appropriate value +// // string type = string.Empty; // TODO: Initialize to an appropriate value +// // string action = string.Empty; // TODO: Initialize to an appropriate value +// // ApplicationTree target = new ApplicationTree(silent, initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, assemblyName, type, action); +// // Assert.Inconclusive("TODO: Implement code to verify target"); +// //} - ///// - /////A test for ApplicationTree Constructor - ///// - //[TestMethod()] - //public void ApplicationTreeConstructorTest1() - //{ - // ApplicationTree target = new ApplicationTree(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} +// ///// +// /////A test for ApplicationTree Constructor +// ///// +// //[TestMethod()] +// //public void ApplicationTreeConstructorTest1() +// //{ +// // ApplicationTree target = new ApplicationTree(); +// // Assert.Inconclusive("TODO: Implement code to verify target"); +// //} - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} +// ///// +// /////A test for Delete +// ///// +// //[TestMethod()] +// //public void DeleteTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // target.Delete(); +// // Assert.Inconclusive("A method that does not return a value cannot be verified."); +// //} - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} +// ///// +// /////A test for Save +// ///// +// //[TestMethod()] +// //public void SaveTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // target.Save(); +// // Assert.Inconclusive("A method that does not return a value cannot be verified."); +// //} - ///// - /////A test for getAll - ///// - //[TestMethod()] - //public void getAllTest() - //{ - // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value - // ApplicationTree[] actual; - // actual = ApplicationTree.getAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getAll +// ///// +// //[TestMethod()] +// //public void getAllTest() +// //{ +// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value +// // ApplicationTree[] actual; +// // actual = ApplicationTree.getAll(); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for getApplicationTree - ///// - //[TestMethod()] - //public void getApplicationTreeTest() - //{ - // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value - // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value - // ApplicationTree[] actual; - // actual = ApplicationTree.getApplicationTree(applicationAlias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getApplicationTree +// ///// +// //[TestMethod()] +// //public void getApplicationTreeTest() +// //{ +// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value +// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value +// // ApplicationTree[] actual; +// // actual = ApplicationTree.getApplicationTree(applicationAlias); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for getApplicationTree - ///// - //[TestMethod()] - //public void getApplicationTreeTest1() - //{ - // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value - // bool onlyInitializedApplications = false; // TODO: Initialize to an appropriate value - // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value - // ApplicationTree[] actual; - // actual = ApplicationTree.getApplicationTree(applicationAlias, onlyInitializedApplications); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getApplicationTree +// ///// +// //[TestMethod()] +// //public void getApplicationTreeTest1() +// //{ +// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value +// // bool onlyInitializedApplications = false; // TODO: Initialize to an appropriate value +// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value +// // ApplicationTree[] actual; +// // actual = ApplicationTree.getApplicationTree(applicationAlias, onlyInitializedApplications); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for getByAlias - ///// - //[TestMethod()] - //public void getByAliasTest() - //{ - // string treeAlias = string.Empty; // TODO: Initialize to an appropriate value - // ApplicationTree expected = null; // TODO: Initialize to an appropriate value - // ApplicationTree actual; - // actual = ApplicationTree.getByAlias(treeAlias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getByAlias +// ///// +// //[TestMethod()] +// //public void getByAliasTest() +// //{ +// // string treeAlias = string.Empty; // TODO: Initialize to an appropriate value +// // ApplicationTree expected = null; // TODO: Initialize to an appropriate value +// // ApplicationTree actual; +// // actual = ApplicationTree.getByAlias(treeAlias); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Action - ///// - //[TestMethod()] - //public void ActionTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Action = expected; - // actual = target.Action; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for Action +// ///// +// //[TestMethod()] +// //public void ActionTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.Action = expected; +// // actual = target.Action; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.Alias; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for Alias +// ///// +// //[TestMethod()] +// //public void AliasTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string actual; +// // actual = target.Alias; +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for ApplicationAlias - ///// - //[TestMethod()] - //public void ApplicationAliasTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.ApplicationAlias; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for ApplicationAlias +// ///// +// //[TestMethod()] +// //public void ApplicationAliasTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string actual; +// // actual = target.ApplicationAlias; +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for AssemblyName - ///// - //[TestMethod()] - //public void AssemblyNameTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.AssemblyName = expected; - // actual = target.AssemblyName; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for AssemblyName +// ///// +// //[TestMethod()] +// //public void AssemblyNameTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.AssemblyName = expected; +// // actual = target.AssemblyName; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for IconClosed - ///// - //[TestMethod()] - //public void IconClosedTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.IconClosed = expected; - // actual = target.IconClosed; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for IconClosed +// ///// +// //[TestMethod()] +// //public void IconClosedTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.IconClosed = expected; +// // actual = target.IconClosed; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for IconOpened - ///// - //[TestMethod()] - //public void IconOpenedTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.IconOpened = expected; - // actual = target.IconOpened; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for IconOpened +// ///// +// //[TestMethod()] +// //public void IconOpenedTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.IconOpened = expected; +// // actual = target.IconOpened; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Initialize - ///// - //[TestMethod()] - //public void InitializeTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.Initialize = expected; - // actual = target.Initialize; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for Initialize +// ///// +// //[TestMethod()] +// //public void InitializeTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // bool expected = false; // TODO: Initialize to an appropriate value +// // bool actual; +// // target.Initialize = expected; +// // actual = target.Initialize; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Silent - ///// - //[TestMethod()] - //public void SilentTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.Silent = expected; - // actual = target.Silent; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for Silent +// ///// +// //[TestMethod()] +// //public void SilentTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // bool expected = false; // TODO: Initialize to an appropriate value +// // bool actual; +// // target.Silent = expected; +// // actual = target.Silent; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for SortOrder - ///// - //[TestMethod()] - //public void SortOrderTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // byte expected = 0; // TODO: Initialize to an appropriate value - // byte actual; - // target.SortOrder = expected; - // actual = target.SortOrder; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for SortOrder +// ///// +// //[TestMethod()] +// //public void SortOrderTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // byte expected = 0; // TODO: Initialize to an appropriate value +// // byte actual; +// // target.SortOrder = expected; +// // actual = target.SortOrder; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for SqlHelper - ///// - //[TestMethod()] - //public void SqlHelperTest() - //{ - // ISqlHelper actual; - // actual = ApplicationTree.SqlHelper; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for SqlHelper +// ///// +// //[TestMethod()] +// //public void SqlHelperTest() +// //{ +// // ISqlHelper actual; +// // actual = ApplicationTree.SqlHelper; +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Title - ///// - //[TestMethod()] - //public void TitleTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Title = expected; - // actual = target.Title; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for Title +// ///// +// //[TestMethod()] +// //public void TitleTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.Title = expected; +// // actual = target.Title; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for Type - ///// - //[TestMethod()] - //public void TypeTest() - //{ - // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Type = expected; - // actual = target.Type; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion +// ///// +// /////A test for Type +// ///// +// //[TestMethod()] +// //public void TypeTest() +// //{ +// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.Type = expected; +// // actual = target.Type; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} +// #endregion - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} +// #region Additional test attributes +// // +// //You can use the following additional attributes as you write your tests: +// // +// //Use ClassInitialize to run code before running the first test in the class +// //[ClassInitialize()] +// //public static void MyClassInitialize(TestContext testContext) +// //{ +// //} +// // +// //Use ClassCleanup to run code after all tests in a class have run +// //[ClassCleanup()] +// //public static void MyClassCleanup() +// //{ +// //} +// // +// //Use TestInitialize to run code before running each test +// //[TestInitialize()] +// //public void MyTestInitialize() +// //{ +// //} +// // +// //Use TestCleanup to run code after each test has run +// //[TestCleanup()] +// //public void MyTestCleanup() +// //{ +// //} +// // +// #endregion +// } +//} diff --git a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs b/src/Umbraco.Tests/TreesAndSections/SectionTests.cs index 1f4a01fd3d..83de6c4479 100644 --- a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs +++ b/src/Umbraco.Tests/TreesAndSections/SectionTests.cs @@ -1,252 +1,252 @@ -using System.IO; -using NUnit.Framework; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using System; -using Umbraco.Core.Composing; -using Umbraco.Tests.Testing; -using Umbraco.Web.Services; +//using System.IO; +//using NUnit.Framework; +//using Umbraco.Core.Services; +//using Umbraco.Tests.TestHelpers; +//using System; +//using Umbraco.Core.Composing; +//using Umbraco.Tests.Testing; +//using Umbraco.Web.Services; -namespace Umbraco.Tests.TreesAndSections -{ - /// - ///This is a test class for ApplicationTest and is intended - ///to contain all ApplicationTest Unit Tests - /// - [TestFixture] - [UmbracoTest(AutoMapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class SectionTests : TestWithDatabaseBase - { - protected override void Compose() - { - base.Compose(); - Composition.RegisterUnique(); - } +//namespace Umbraco.Tests.TreesAndSections +//{ +// /// +// ///This is a test class for ApplicationTest and is intended +// ///to contain all ApplicationTest Unit Tests +// /// +// [TestFixture] +// [UmbracoTest(AutoMapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] +// public class SectionTests : TestWithDatabaseBase +// { +// protected override void Compose() +// { +// base.Compose(); +// Composition.RegisterUnique(); +// } - public override void SetUp() - { - base.SetUp(); +// public override void SetUp() +// { +// base.SetUp(); - var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); - var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); - Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); - using (var writer = File.CreateText(treesConfig)) - { - writer.Write(ResourceFiles.trees); - } - using (var writer = File.CreateText(appConfig)) - { - writer.Write(ResourceFiles.applications); - } +// var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); +// var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); +// Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); +// using (var writer = File.CreateText(treesConfig)) +// { +// writer.Write(ResourceFiles.trees); +// } +// using (var writer = File.CreateText(appConfig)) +// { +// writer.Write(ResourceFiles.applications); +// } - ApplicationTreeService.TreeConfigFilePath = treesConfig; - SectionService.AppConfigFilePath = appConfig; - } +// ApplicationTreeService.TreeConfigFilePath = treesConfig; +// SectionService.AppConfigFilePath = appConfig; +// } - public override void TearDown() - { - base.TearDown(); +// public override void TearDown() +// { +// base.TearDown(); - if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) - { - Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); - } - ApplicationTreeService.TreeConfigFilePath = null; - SectionService.AppConfigFilePath = null; - } +// if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) +// { +// Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); +// } +// ApplicationTreeService.TreeConfigFilePath = null; +// SectionService.AppConfigFilePath = null; +// } - /// - /// Create a new application and delete it - /// - [Test()] - public void Application_Make_New() - { - var name = Guid.NewGuid().ToString("N"); - ServiceContext.SectionService.MakeNew(name, name, "icon.jpg"); +// ///// +// ///// Create a new application and delete it +// ///// +// //[Test()] +// //public void Application_Make_New() +// //{ +// // var name = Guid.NewGuid().ToString("N"); +// // ServiceContext.SectionService.MakeNew(name, name, "icon.jpg"); - //check if it exists - var app = ServiceContext.SectionService.GetByAlias(name); - Assert.IsNotNull(app); +// // //check if it exists +// // var app = ServiceContext.SectionService.GetByAlias(name); +// // Assert.IsNotNull(app); - //now remove it - ServiceContext.SectionService.DeleteSection(app); - Assert.IsNull(ServiceContext.SectionService.GetByAlias(name)); - } +// // //now remove it +// // ServiceContext.SectionService.DeleteSection(app); +// // Assert.IsNull(ServiceContext.SectionService.GetByAlias(name)); +// //} - #region Tests to write +// #region Tests to write - ///// - /////A test for Application Constructor - ///// - //[TestMethod()] - //public void ApplicationConstructorTest() - //{ - // string name = string.Empty; // TODO: Initialize to an appropriate value - // string alias = string.Empty; // TODO: Initialize to an appropriate value - // string icon = string.Empty; // TODO: Initialize to an appropriate value - // Application target = new Application(name, alias, icon); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} +// ///// +// /////A test for Application Constructor +// ///// +// //[TestMethod()] +// //public void ApplicationConstructorTest() +// //{ +// // string name = string.Empty; // TODO: Initialize to an appropriate value +// // string alias = string.Empty; // TODO: Initialize to an appropriate value +// // string icon = string.Empty; // TODO: Initialize to an appropriate value +// // Application target = new Application(name, alias, icon); +// // Assert.Inconclusive("TODO: Implement code to verify target"); +// //} - ///// - /////A test for Application Constructor - ///// - //[TestMethod()] - //public void ApplicationConstructorTest1() - //{ - // Application target = new Application(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} +// ///// +// /////A test for Application Constructor +// ///// +// //[TestMethod()] +// //public void ApplicationConstructorTest1() +// //{ +// // Application target = new Application(); +// // Assert.Inconclusive("TODO: Implement code to verify target"); +// //} - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // Application target = new Application(); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} +// ///// +// /////A test for Delete +// ///// +// //[TestMethod()] +// //public void DeleteTest() +// //{ +// // Application target = new Application(); // TODO: Initialize to an appropriate value +// // target.Delete(); +// // Assert.Inconclusive("A method that does not return a value cannot be verified."); +// //} - ///// - /////A test for MakeNew - ///// - //[TestMethod()] - //public void MakeNewTest1() - //{ - // string name = string.Empty; // TODO: Initialize to an appropriate value - // string alias = string.Empty; // TODO: Initialize to an appropriate value - // string icon = string.Empty; // TODO: Initialize to an appropriate value - // Application.MakeNew(name, alias, icon); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} +// ///// +// /////A test for MakeNew +// ///// +// //[TestMethod()] +// //public void MakeNewTest1() +// //{ +// // string name = string.Empty; // TODO: Initialize to an appropriate value +// // string alias = string.Empty; // TODO: Initialize to an appropriate value +// // string icon = string.Empty; // TODO: Initialize to an appropriate value +// // Application.MakeNew(name, alias, icon); +// // Assert.Inconclusive("A method that does not return a value cannot be verified."); +// //} - ///// - /////A test for RegisterIApplications - ///// - //[TestMethod()] - //public void RegisterIApplicationsTest() - //{ - // Application.RegisterIApplications(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} +// ///// +// /////A test for RegisterIApplications +// ///// +// //[TestMethod()] +// //public void RegisterIApplicationsTest() +// //{ +// // Application.RegisterIApplications(); +// // Assert.Inconclusive("A method that does not return a value cannot be verified."); +// //} - ///// - /////A test for getAll - ///// - //[TestMethod()] - //public void getAllTest() - //{ - // List expected = null; // TODO: Initialize to an appropriate value - // List actual; - // actual = Application.getAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getAll +// ///// +// //[TestMethod()] +// //public void getAllTest() +// //{ +// // List expected = null; // TODO: Initialize to an appropriate value +// // List actual; +// // actual = Application.getAll(); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for getByAlias - ///// - //[TestMethod()] - //public void getByAliasTest() - //{ - // string appAlias = string.Empty; // TODO: Initialize to an appropriate value - // Application expected = null; // TODO: Initialize to an appropriate value - // Application actual; - // actual = Application.getByAlias(appAlias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for getByAlias +// ///// +// //[TestMethod()] +// //public void getByAliasTest() +// //{ +// // string appAlias = string.Empty; // TODO: Initialize to an appropriate value +// // Application expected = null; // TODO: Initialize to an appropriate value +// // Application actual; +// // actual = Application.getByAlias(appAlias); +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for SqlHelper - ///// - //[TestMethod()] - //public void SqlHelperTest() - //{ - // ISqlHelper actual; - // actual = Application.SqlHelper; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for SqlHelper +// ///// +// //[TestMethod()] +// //public void SqlHelperTest() +// //{ +// // ISqlHelper actual; +// // actual = Application.SqlHelper; +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for alias - ///// - //[TestMethod()] - //public void aliasTest() - //{ - // Application target = new Application(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.alias = expected; - // actual = target.alias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for alias +// ///// +// //[TestMethod()] +// //public void aliasTest() +// //{ +// // Application target = new Application(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.alias = expected; +// // actual = target.alias; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for icon - ///// - //[TestMethod()] - //public void iconTest() - //{ - // Application target = new Application(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.icon = expected; - // actual = target.icon; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} +// ///// +// /////A test for icon +// ///// +// //[TestMethod()] +// //public void iconTest() +// //{ +// // Application target = new Application(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.icon = expected; +// // actual = target.icon; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} - ///// - /////A test for name - ///// - //[TestMethod()] - //public void nameTest() - //{ - // Application target = new Application(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.name = expected; - // actual = target.name; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion +// ///// +// /////A test for name +// ///// +// //[TestMethod()] +// //public void nameTest() +// //{ +// // Application target = new Application(); // TODO: Initialize to an appropriate value +// // string expected = string.Empty; // TODO: Initialize to an appropriate value +// // string actual; +// // target.name = expected; +// // actual = target.name; +// // Assert.AreEqual(expected, actual); +// // Assert.Inconclusive("Verify the correctness of this test method."); +// //} +// #endregion - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} +// #region Additional test attributes +// // +// //You can use the following additional attributes as you write your tests: +// // +// //Use ClassInitialize to run code before running the first test in the class +// //[ClassInitialize()] +// //public static void MyClassInitialize(TestContext testContext) +// //{ +// //} +// // +// //Use ClassCleanup to run code after all tests in a class have run +// //[ClassCleanup()] +// //public static void MyClassCleanup() +// //{ +// //} +// // +// //Use TestInitialize to run code before running each test +// //[TestInitialize()] +// //public void MyTestInitialize() +// //{ +// //} +// // +// //Use TestCleanup to run code after each test has run +// //[TestCleanup()] +// //public void MyTestCleanup() +// //{ +// //} +// // +// #endregion +// } +//} diff --git a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs index 247c33c361..4d6740a0b1 100644 --- a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs @@ -1,46 +1,46 @@ -using System; -using Umbraco.Core.Cache; +//using System; +//using Umbraco.Core.Cache; -namespace Umbraco.Web.Cache -{ - public sealed class ApplicationTreeCacheRefresher : CacheRefresherBase - { - public ApplicationTreeCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) - { } +//namespace Umbraco.Web.Cache +//{ +// public sealed class ApplicationTreeCacheRefresher : CacheRefresherBase +// { +// public ApplicationTreeCacheRefresher(CacheHelper cacheHelper) +// : base(cacheHelper) +// { } - #region Define +// #region Define - protected override ApplicationTreeCacheRefresher This => this; +// protected override ApplicationTreeCacheRefresher This => this; - public static readonly Guid UniqueId = Guid.Parse("0AC6C028-9860-4EA4-958D-14D39F45886E"); +// public static readonly Guid UniqueId = Guid.Parse("0AC6C028-9860-4EA4-958D-14D39F45886E"); - public override Guid RefresherUniqueId => UniqueId; +// public override Guid RefresherUniqueId => UniqueId; - public override string Name => "Application Tree Cache Refresher"; +// public override string Name => "Application Tree Cache Refresher"; - #endregion +// #endregion - #region Refresher +// #region Refresher - public override void RefreshAll() - { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); - base.RefreshAll(); - } +// public override void RefreshAll() +// { +// CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); +// base.RefreshAll(); +// } - public override void Refresh(int id) - { - Remove(id); - base.Refresh(id); - } +// public override void Refresh(int id) +// { +// Remove(id); +// base.Refresh(id); +// } - public override void Remove(int id) - { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); - base.Remove(id); - } +// public override void Remove(int id) +// { +// CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); +// base.Remove(id); +// } - #endregion - } -} +// #endregion +// } +//} diff --git a/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs b/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs index d522e54de6..421eb546a4 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs @@ -46,19 +46,19 @@ namespace Umbraco.Web.Cache _logger.Info("Initializing Umbraco internal event handlers for cache refreshing."); - // bind to application tree events - Bind(() => ApplicationTreeService.Deleted += ApplicationTreeService_Deleted, - () => ApplicationTreeService.Deleted -= ApplicationTreeService_Deleted); - Bind(() => ApplicationTreeService.Updated += ApplicationTreeService_Updated, - () => ApplicationTreeService.Updated -= ApplicationTreeService_Updated); - Bind(() => ApplicationTreeService.New += ApplicationTreeService_New, - () => ApplicationTreeService.New -= ApplicationTreeService_New); + //// bind to application tree events + //Bind(() => ApplicationTreeService.Deleted += ApplicationTreeService_Deleted, + // () => ApplicationTreeService.Deleted -= ApplicationTreeService_Deleted); + //Bind(() => ApplicationTreeService.Updated += ApplicationTreeService_Updated, + // () => ApplicationTreeService.Updated -= ApplicationTreeService_Updated); + //Bind(() => ApplicationTreeService.New += ApplicationTreeService_New, + // () => ApplicationTreeService.New -= ApplicationTreeService_New); - // bind to application events - Bind(() => SectionService.Deleted += SectionService_Deleted, - () => SectionService.Deleted -= SectionService_Deleted); - Bind(() => SectionService.New += SectionService_New, - () => SectionService.New -= SectionService_New); + //// bind to application events + //Bind(() => SectionService.Deleted += SectionService_Deleted, + // () => SectionService.Deleted -= SectionService_Deleted); + //Bind(() => SectionService.New += SectionService_New, + // () => SectionService.New -= SectionService_New); // bind to user and user group events Bind(() => UserService.SavedUserGroup += UserService_SavedUserGroup, @@ -231,38 +231,38 @@ namespace Umbraco.Web.Cache #endregion - #region ApplicationTreeService + //#region ApplicationTreeService - private void ApplicationTreeService_New(ApplicationTree sender, EventArgs e) - { - _distributedCache.RefreshAllApplicationTreeCache(); - } + //private void ApplicationTreeService_New(ApplicationTree sender, EventArgs e) + //{ + // _distributedCache.RefreshAllApplicationTreeCache(); + //} - private void ApplicationTreeService_Updated(ApplicationTree sender, EventArgs e) - { - _distributedCache.RefreshAllApplicationTreeCache(); - } + //private void ApplicationTreeService_Updated(ApplicationTree sender, EventArgs e) + //{ + // _distributedCache.RefreshAllApplicationTreeCache(); + //} - private void ApplicationTreeService_Deleted(ApplicationTree sender, EventArgs e) - { - _distributedCache.RefreshAllApplicationTreeCache(); - } + //private void ApplicationTreeService_Deleted(ApplicationTree sender, EventArgs e) + //{ + // _distributedCache.RefreshAllApplicationTreeCache(); + //} - #endregion + //#endregion - #region Application event handlers + //#region Application event handlers - private void SectionService_New(ISectionService sender, EventArgs e) - { - _distributedCache.RefreshAllApplicationCache(); - } + //private void SectionService_New(ISectionService sender, EventArgs e) + //{ + // _distributedCache.RefreshAllApplicationCache(); + //} - private void SectionService_Deleted(ISectionService sender, EventArgs e) - { - _distributedCache.RefreshAllApplicationCache(); - } + //private void SectionService_Deleted(ISectionService sender, EventArgs e) + //{ + // _distributedCache.RefreshAllApplicationCache(); + //} - #endregion + //#endregion #region LocalizationService / Dictionary diff --git a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs index 68ac339a46..aab0f9b157 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs @@ -18,23 +18,23 @@ namespace Umbraco.Web.Cache #endregion - #region ApplicationTreeCache + //#region ApplicationTreeCache - public static void RefreshAllApplicationTreeCache(this DistributedCache dc) - { - dc.RefreshAll(ApplicationTreeCacheRefresher.UniqueId); - } + //public static void RefreshAllApplicationTreeCache(this DistributedCache dc) + //{ + // dc.RefreshAll(ApplicationTreeCacheRefresher.UniqueId); + //} - #endregion + //#endregion - #region ApplicationCache + //#region ApplicationCache - public static void RefreshAllApplicationCache(this DistributedCache dc) - { - dc.RefreshAll(ApplicationCacheRefresher.UniqueId); - } + //public static void RefreshAllApplicationCache(this DistributedCache dc) + //{ + // dc.RefreshAll(ApplicationCacheRefresher.UniqueId); + //} - #endregion + //#endregion #region User cache diff --git a/src/Umbraco.Web/TagsController.cs b/src/Umbraco.Web/Controllers/TagsController.cs similarity index 89% rename from src/Umbraco.Web/TagsController.cs rename to src/Umbraco.Web/Controllers/TagsController.cs index 181b9f7da2..cb6a28be47 100644 --- a/src/Umbraco.Web/TagsController.cs +++ b/src/Umbraco.Web/Controllers/TagsController.cs @@ -8,7 +8,7 @@ using Umbraco.Core.Services; using Umbraco.Web.Models; using Umbraco.Web.WebApi; -namespace Umbraco.Web.WebServices +namespace Umbraco.Web.Controllers { /// /// A public web service for querying tags @@ -29,8 +29,8 @@ namespace Umbraco.Web.WebServices /// /// Initializes a new instance of the with all its dependencies. /// - public TagsController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public TagsController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } /// diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index 231ec9ba67..7ffc6e1207 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -52,8 +52,8 @@ namespace Umbraco.Web.Editors /// /// Initializes a new instance of the class with all its dependencies. /// - public AuthenticationController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public AuthenticationController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } protected BackOfficeUserManager UserManager => _userManager diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index ee973a4b58..65ab27d76a 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -14,13 +14,13 @@ using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; +using Umbraco.Web.Controllers; using Umbraco.Web.Features; using Umbraco.Web.HealthCheck; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using Umbraco.Web.PropertyEditors; using Umbraco.Web.Trees; -using Umbraco.Web.WebServices; using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Editors @@ -158,7 +158,7 @@ namespace Umbraco.Web.Editors }, { "treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( - controller => controller.GetApplicationTrees(null, null, null, true)) + controller => controller.GetApplicationTrees(null, null, null)) }, { "contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index 670d37e7a7..00a0cb90bc 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -54,11 +54,11 @@ namespace Umbraco.Web.Editors public ContentTypeController(IEntityXmlSerializer serializer, ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, - IUmbracoContextAccessor umbracoContextAccessor, + UmbracoContext umbracoContext, ISqlContext sqlContext, PropertyEditorCollection propertyEditors, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + : base(cultureDictionaryFactory, globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _serializer = serializer; _propertyEditors = propertyEditors; diff --git a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs index 898208319a..a11fcaa869 100644 --- a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs +++ b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs @@ -33,7 +33,8 @@ namespace Umbraco.Web.Editors private readonly ICultureDictionaryFactory _cultureDictionaryFactory; private ICultureDictionary _cultureDictionary; - protected ContentTypeControllerBase(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected ContentTypeControllerBase(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _cultureDictionaryFactory = cultureDictionaryFactory; } diff --git a/src/Umbraco.Web/Editors/DashboardController.cs b/src/Umbraco.Web/Editors/DashboardController.cs index 8960f110c3..0340926ce4 100644 --- a/src/Umbraco.Web/Editors/DashboardController.cs +++ b/src/Umbraco.Web/Editors/DashboardController.cs @@ -38,8 +38,8 @@ namespace Umbraco.Web.Editors /// /// Initializes a new instance of the with all its dependencies. /// - public DashboardController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, Dashboards dashboards) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public DashboardController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, Dashboards dashboards) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _dashboards = dashboards; } diff --git a/src/Umbraco.Web/Editors/DashboardSecurity.cs b/src/Umbraco.Web/Editors/DashboardSecurity.cs index 1481606c7e..fdbf5af7d9 100644 --- a/src/Umbraco.Web/Editors/DashboardSecurity.cs +++ b/src/Umbraco.Web/Editors/DashboardSecurity.cs @@ -6,6 +6,7 @@ using Umbraco.Core; using Umbraco.Core.Configuration.Dashboard; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; +using Umbraco.Web.Services; namespace Umbraco.Web.Editors { diff --git a/src/Umbraco.Web/Editors/Dashboards.cs b/src/Umbraco.Web/Editors/Dashboards.cs index 4bf2d81045..c837cbbf33 100644 --- a/src/Umbraco.Web/Editors/Dashboards.cs +++ b/src/Umbraco.Web/Editors/Dashboards.cs @@ -8,6 +8,7 @@ using Umbraco.Core.Manifest; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Services; namespace Umbraco.Web.Editors { diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index 993489855f..c8368d11b0 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -16,11 +16,16 @@ using Constants = Umbraco.Core.Constants; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using System.Web.Http.Controllers; using Examine; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration; +using Umbraco.Core.Logging; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence; using Umbraco.Core.Services; using Umbraco.Core.Xml; using Umbraco.Web.Models.Mapping; using Umbraco.Web.Search; +using Umbraco.Web.Services; using Umbraco.Web.Trees; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; @@ -37,6 +42,15 @@ namespace Umbraco.Web.Editors [PluginController("UmbracoApi")] public class EntityController : UmbracoAuthorizedJsonController { + private readonly IApplicationTreeService _treeService; + + public EntityController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, + IApplicationTreeService treeService) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) + { + _treeService = treeService; + } + /// /// Configures this controller with a custom action selector /// @@ -129,7 +143,7 @@ namespace Umbraco.Web.Editors { if (allowedSections.Contains(searchableTree.Value.AppAlias)) { - var tree = Services.ApplicationTreeService.GetByAlias(searchableTree.Key); + var tree = _treeService.GetByAlias(searchableTree.Key); if (tree == null) continue; //shouldn't occur var searchableTreeAttribute = searchableTree.Value.SearchableTree.GetType().GetCustomAttribute(false); diff --git a/src/Umbraco.Web/Editors/MediaTypeController.cs b/src/Umbraco.Web/Editors/MediaTypeController.cs index f2b8fd3dda..e2fbe8c428 100644 --- a/src/Umbraco.Web/Editors/MediaTypeController.cs +++ b/src/Umbraco.Web/Editors/MediaTypeController.cs @@ -37,7 +37,8 @@ namespace Umbraco.Web.Editors [MediaTypeControllerControllerConfiguration] public class MediaTypeController : ContentTypeControllerBase { - public MediaTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public MediaTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(cultureDictionaryFactory, globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/MemberTypeController.cs b/src/Umbraco.Web/Editors/MemberTypeController.cs index 3abc0035d3..c59bf6d332 100644 --- a/src/Umbraco.Web/Editors/MemberTypeController.cs +++ b/src/Umbraco.Web/Editors/MemberTypeController.cs @@ -30,7 +30,8 @@ namespace Umbraco.Web.Editors [UmbracoTreeAuthorize(new string[] { Constants.Trees.MemberTypes, Constants.Trees.Members})] public class MemberTypeController : ContentTypeControllerBase { - public MemberTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public MemberTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(cultureDictionaryFactory, globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 05d1e2a7a3..ec81b794a1 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -44,10 +44,10 @@ namespace Umbraco.Web.Editors [UmbracoApplicationAuthorize(Core.Constants.Applications.Packages)] public class PackageInstallController : UmbracoAuthorizedJsonController { - public PackageInstallController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, + public PackageInstallController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/SectionController.cs b/src/Umbraco.Web/Editors/SectionController.cs index f650c18fb3..7b484b09b1 100644 --- a/src/Umbraco.Web/Editors/SectionController.cs +++ b/src/Umbraco.Web/Editors/SectionController.cs @@ -2,10 +2,17 @@ using AutoMapper; using Umbraco.Web.Mvc; using System.Linq; +using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration; +using Umbraco.Core.Logging; using Umbraco.Core.Models; +using Umbraco.Core.Persistence; +using Umbraco.Core.Services; using Umbraco.Web.Trees; using Section = Umbraco.Web.Models.ContentEditing.Section; using Umbraco.Web.Models.Trees; +using Umbraco.Web.Services; namespace Umbraco.Web.Editors { @@ -16,21 +23,32 @@ namespace Umbraco.Web.Editors public class SectionController : UmbracoAuthorizedJsonController { private readonly Dashboards _dashboards; + private readonly ISectionService _sectionService; + private readonly TreeControllerResolver _treeControllerResolver; + private readonly IApplicationTreeService _treeService; - public SectionController(Dashboards dashboards) + public SectionController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, + Dashboards dashboards, ISectionService sectionService, TreeControllerResolver treeControllerResolver, IApplicationTreeService treeService) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _dashboards = dashboards; + _sectionService = sectionService; + _treeControllerResolver = treeControllerResolver; + _treeService = treeService; } public IEnumerable
GetSections() { - var sections = Services.SectionService.GetAllowedSections(Security.GetUserId().ResultOr(0)); + var sections = _sectionService.GetAllowedSections(Security.GetUserId().ResultOr(0)); - var sectionModels = sections.Select(Mapper.Map).ToArray(); + var sectionModels = sections.Select(Mapper.Map
).ToArray(); // 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 { ControllerContext = ControllerContext }; + var appTreeController = new ApplicationTreeController(GlobalSettings, UmbracoContext, SqlContext, Services, ApplicationCache, Logger, RuntimeState, _treeControllerResolver, _treeService) + { + ControllerContext = ControllerContext + }; var dashboards = _dashboards.GetDashboards(Security.CurrentUser); @@ -76,8 +94,8 @@ namespace Umbraco.Web.Editors /// public IEnumerable
GetAllSections() { - var sections = Services.SectionService.GetSections(); - var mapped = sections.Select(Mapper.Map); + var sections = _sectionService.GetSections(); + var mapped = sections.Select(Mapper.Map
); if (Security.CurrentUser.IsAdmin()) return mapped; diff --git a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs index 3baa5e85ff..4e430b833c 100644 --- a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs +++ b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs @@ -31,13 +31,13 @@ namespace Umbraco.Web.Editors /// Initializes a new instance of the class with all its dependencies. ///
/// - /// + /// /// /// /// /// /// - protected UmbracoAuthorizedJsonController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected UmbracoAuthorizedJsonController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } } diff --git a/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs b/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs new file mode 100644 index 0000000000..e9befb0e27 --- /dev/null +++ b/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs @@ -0,0 +1,177 @@ +using System; +using System.Diagnostics; +using Umbraco.Core.Services; + +namespace Umbraco.Web.Models.ContentEditing +{ + [DebuggerDisplay("Tree - {Alias} ({ApplicationAlias})")] + public class ApplicationTree + { + //private static readonly ConcurrentDictionary ResolvedTypes = new ConcurrentDictionary(); + + ///// + ///// Initializes a new instance of the class. + ///// + //public ApplicationTree() { } + + ///// + ///// Initializes a new instance of the class. + ///// + ///// if set to true [initialize]. + ///// The sort order. + ///// The application alias. + ///// The tree alias. + ///// The tree title. + ///// The icon closed. + ///// The icon opened. + ///// The tree type. + //public ApplicationTree(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) + //{ + // //Initialize = initialize; + // SortOrder = sortOrder; + // ApplicationAlias = applicationAlias; + // Alias = alias; + // Title = title; + // IconClosed = iconClosed; + // IconOpened = iconOpened; + // Type = type; + + //} + + public ApplicationTree(int sortOrder, string applicationAlias, string alias, string title) + { + SortOrder = sortOrder; + ApplicationAlias = applicationAlias; + Alias = alias; + Title = title; + } + + ///// + ///// Gets or sets a value indicating whether this should initialize. + ///// + ///// true if initialize; otherwise, false. + //public bool Initialize { get; set; } + + /// + /// Gets or sets the sort order. + /// + /// The sort order. + public int SortOrder { get; set; } + + /// + /// Gets the application alias. + /// + /// The application alias. + public string ApplicationAlias { get; } + + /// + /// Gets the tree alias. + /// + /// The alias. + public string Alias { get; } + + /// + /// Gets or sets the tree title (fallback if the tree alias isn't localized) + /// + /// The title. + public string Title { get; set; } + + ///// + ///// Gets or sets the icon closed. + ///// + ///// The icon closed. + //public string IconClosed { get; set; } + + ///// + ///// Gets or sets the icon opened. + ///// + ///// The icon opened. + //public string IconOpened { get; set; } + + ///// + ///// Gets or sets the tree type assembly name. + ///// + ///// The type. + //public string Type { get; set; } + + /// + /// Returns the localized root node display name + /// + /// + /// + public string GetRootNodeDisplayName(ILocalizedTextService textService) + { + var label = $"[{Alias}]"; + + // try to look up a the localized tree header matching the tree alias + var localizedLabel = textService.Localize("treeHeaders/" + Alias); + + // if the localizedLabel returns [alias] then return the title if it's defined + if (localizedLabel != null && localizedLabel.Equals(label, StringComparison.InvariantCultureIgnoreCase)) + { + if (string.IsNullOrEmpty(Title) == false) + label = Title; + } + else + { + // the localizedLabel translated into something that's not just [alias], so use the translation + label = localizedLabel; + } + + return label; + } + + //private Type _runtimeType; + + ///// + ///// Returns the CLR type based on it's assembly name stored in the config + ///// + ///// + //public Type GetRuntimeType() + //{ + // return _runtimeType ?? (_runtimeType = System.Type.GetType(Type)); + //} + + ///// + ///// Used to try to get and cache the tree type + ///// + ///// + ///// + //internal static Type TryGetType(string type) + //{ + // try + // { + // return ResolvedTypes.GetOrAdd(type, s => + // { + // var result = System.Type.GetType(type); + // if (result != null) + // { + // return result; + // } + + // //we need to implement a bit of a hack here due to some trees being renamed and backwards compat + // var parts = type.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + // if (parts.Length != 2) + // throw new InvalidOperationException("Could not resolve type"); + // if (parts[1].Trim() != "Umbraco.Web" || parts[0].StartsWith("Umbraco.Web.Trees") == false || parts[0].EndsWith("Controller")) + // throw new InvalidOperationException("Could not resolve type"); + + // //if it's one of our controllers but it's not suffixed with "Controller" then add it and try again + // var tempType = parts[0] + "Controller, Umbraco.Web"; + + // result = System.Type.GetType(tempType); + // if (result != null) + // return result; + + // throw new InvalidOperationException("Could not resolve type"); + // }); + // } + // catch (InvalidOperationException) + // { + // //swallow, this is our own exception, couldn't find the type + // // fixme bad use of exceptions here! + // return null; + // } + //} + } +} diff --git a/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs b/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs new file mode 100644 index 0000000000..f27941035a --- /dev/null +++ b/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core.Composing; + +namespace Umbraco.Web.Models.ContentEditing +{ + + /// + /// Defines a back office section + /// + public interface IBackOfficeSection : IDiscoverable + { + string Alias { get; } + string Name { get; } + int SortOrder { get; } + } +} diff --git a/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs index ba7ff3c38d..683fce36e8 100644 --- a/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using AutoMapper; +using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; @@ -9,7 +10,7 @@ namespace Umbraco.Web.Models.Mapping { public SectionMapperProfile(ILocalizedTextService textService) { - CreateMap() + CreateMap() .ForMember(dest => dest.RoutePath, opt => opt.Ignore()) .ForMember(dest => dest.Icon, opt => opt.Ignore()) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => textService.Localize("sections/" + src.Alias, (IDictionary)null))) diff --git a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index 8261dda0d4..c975f3a106 100644 --- a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Models.Entities; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Web.Actions; +using Umbraco.Web.Services; namespace Umbraco.Web.Models.Mapping diff --git a/src/Umbraco.Web/Models/Trees/ApplicationAttribute.cs b/src/Umbraco.Web/Models/Trees/ApplicationAttribute.cs deleted file mode 100644 index 65fc4ed6f3..0000000000 --- a/src/Umbraco.Web/Models/Trees/ApplicationAttribute.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -namespace Umbraco.Web.Models.Trees -{ - /// - /// Identifies an application tree - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class ApplicationAttribute : Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The alias. - /// The name. - /// The sort order. - public ApplicationAttribute(string alias, - string name, - int sortOrder = 0) - { - Alias = alias; - Name = name; - SortOrder = sortOrder; - } - - public string Alias { get; private set; } - public string Name { get; private set; } - public int SortOrder { get; private set; } - } -} diff --git a/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs b/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs index aa8e0cfda6..ba48c9e240 100644 --- a/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs +++ b/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs @@ -1,37 +1,77 @@ using Umbraco.Core; using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Trees { - // The application definitions are intended as a means to auto populate - // the application.config. On app startup, Umbraco will look for any - // unregistered classes with an ApplicationAttribute and add them to the cache + /// + /// Defines the back office content section + /// + public class ContentBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Content; + public string Name => "Content"; + public int SortOrder => 0; + } - [Application(Constants.Applications.Content, "Content")] - public class ContentApplicationDefinition : IApplication - { } + /// + /// Defines the back office media section + /// + public class MediaBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Media; + public string Name => "Media"; + public int SortOrder => 1; + } - [Application(Constants.Applications.Media, "Media", sortOrder: 1)] - public class MediaApplicationDefinition : IApplication - { } + /// + /// Defines the back office settings section + /// + public class SettingsBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Settings; + public string Name => "Settings"; + public int SortOrder => 2; + } - [Application(Constants.Applications.Settings, "Settings", sortOrder: 2)] - public class SettingsApplicationDefinition : IApplication - { } + /// + /// Defines the back office packages section + /// + public class PackagesBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Packages; + public string Name => "Packages"; + public int SortOrder => 3; + } - [Application(Constants.Applications.Packages, "Packages", sortOrder: 3)] - public class PackagesApplicationDefinition : IApplication - { } + /// + /// Defines the back office users section + /// + public class UsersBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Users; + public string Name => "Users"; + public int SortOrder => 4; + } - [Application(Constants.Applications.Users, "Users", sortOrder: 4)] - public class UsersApplicationDefinition : IApplication - { } + /// + /// Defines the back office members section + /// + public class MembersBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Members; + public string Name => "Members"; + public int SortOrder => 5; + } - [Application(Constants.Applications.Members, "Members", sortOrder: 5)] - public class MembersApplicationDefinition : IApplication - { } - - [Application(Constants.Applications.Translation, "Translation", sortOrder: 6)] - public class TranslationApplicationDefinition : IApplication - { } + /// + /// Defines the back office translation section + /// + public class TranslationBackOfficeSectionDefinition : IBackOfficeSection + { + public string Alias => Constants.Applications.Translation; + public string Name => "Translation"; + public int SortOrder => 6; + } } diff --git a/src/Umbraco.Web/Models/Trees/IApplication.cs b/src/Umbraco.Web/Models/Trees/IApplication.cs deleted file mode 100644 index 4e9cae43fd..0000000000 --- a/src/Umbraco.Web/Models/Trees/IApplication.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Umbraco.Core.Composing; - -namespace Umbraco.Web.Models.Trees -{ - /// - /// Marker interface for created applications in the umbraco backoffice - /// - public interface IApplication : IDiscoverable - { } -} diff --git a/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs b/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs index 30c21fce96..eef6ab1ca2 100644 --- a/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs +++ b/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs @@ -8,6 +8,8 @@ namespace Umbraco.Web.Mvc // which we are not doing at the moment // we can inherit from BuilderCollectionBase and just be enumerable + //fixme: this should be LazyCollectionBuilderBase ? + public class SurfaceControllerTypeCollection : BuilderCollectionBase { public SurfaceControllerTypeCollection(IEnumerable items) diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index 422b502f80..b7f4e13432 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -22,10 +22,12 @@ using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Profiling; using Umbraco.Core.Services; using Umbraco.Web.Install; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; using Umbraco.Web.Security; +using Umbraco.Web.Trees; using Umbraco.Web.UI.JavaScript; using Umbraco.Web.WebApi; diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs index 51e4fbd008..0ef9adddb7 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs @@ -8,6 +8,8 @@ using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; +using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.ValueConverters; @@ -21,6 +23,7 @@ using Umbraco.Web.Dictionary; using Umbraco.Web.Editors; using Umbraco.Web.Features; using Umbraco.Web.HealthCheck; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.PublishedContent; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; @@ -189,6 +192,14 @@ namespace Umbraco.Web.Runtime .Append() .Append() .Append(); + + // register back office sections + composition.WithCollectionBuilder() + .Add(() => composition.TypeLoader.GetTypes()); + + // register back office trees + composition.WithCollectionBuilder() + .Add(() => composition.TypeLoader.GetTypes()); } } } diff --git a/src/Umbraco.Web/Search/SearchableTreeCollection.cs b/src/Umbraco.Web/Search/SearchableTreeCollection.cs index 38c329cafa..2b1baa5194 100644 --- a/src/Umbraco.Web/Search/SearchableTreeCollection.cs +++ b/src/Umbraco.Web/Search/SearchableTreeCollection.cs @@ -5,6 +5,7 @@ using System.Linq; using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Services; +using Umbraco.Web.Services; using Umbraco.Web.Trees; namespace Umbraco.Web.Search diff --git a/src/Umbraco.Web/Services/ApplicationTreeService.cs b/src/Umbraco.Web/Services/ApplicationTreeService.cs index 86bfc5d0bb..72b26e26d3 100644 --- a/src/Umbraco.Web/Services/ApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/ApplicationTreeService.cs @@ -11,7 +11,9 @@ using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Composing; +using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Services; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; namespace Umbraco.Web.Services @@ -19,276 +21,251 @@ namespace Umbraco.Web.Services internal class ApplicationTreeService : IApplicationTreeService { private readonly ILogger _logger; - private readonly CacheHelper _cache; - private readonly TypeLoader _typeLoader; - private Lazy> _allAvailableTrees; - internal const string TreeConfigFileName = "trees.config"; - private static string _treeConfig; + private readonly TreeCollection _treeCollection; private static readonly object Locker = new object(); private readonly Lazy>> _groupedTrees; - public ApplicationTreeService(ILogger logger, CacheHelper cache, TypeLoader typeLoader) + public ApplicationTreeService(ILogger logger, TreeCollection treeCollection) { _logger = logger; - _cache = cache; - _typeLoader = typeLoader; - _groupedTrees = new Lazy>>(InitGroupedTrees); + _treeCollection = treeCollection; + //_groupedTrees = new Lazy>>(InitGroupedTrees); } - /// - /// gets/sets the trees.config file path - /// - /// - /// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath - /// - internal static string TreeConfigFilePath - { - get - { - if (string.IsNullOrWhiteSpace(_treeConfig)) - { - _treeConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + TreeConfigFileName); - } - return _treeConfig; - } - set { _treeConfig = value; } - } + ///// + ///// gets/sets the trees.config file path + ///// + ///// + ///// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath + ///// + //internal static string TreeConfigFilePath + //{ + // get + // { + // if (string.IsNullOrWhiteSpace(_treeConfig)) + // { + // _treeConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + TreeConfigFileName); + // } + // return _treeConfig; + // } + // set { _treeConfig = value; } + //} - /// - /// The main entry point to get application trees - /// - /// - /// This lazily on first access will scan for plugin trees and ensure the trees.config is up-to-date with the plugins. If plugins - /// haven't changed on disk then the file will not be saved. The trees are all then loaded from this config file into cache and returned. - /// - private List GetAppTrees() - { - return _cache.RuntimeCache.GetCacheItem>( - CacheKeys.ApplicationTreeCacheKey, - () => - { - var list = ReadFromXmlAndSort(); + ///// + ///// The main entry point to get application trees + ///// + ///// + ///// This lazily on first access will scan for plugin trees and ensure the trees.config is up-to-date with the plugins. If plugins + ///// haven't changed on disk then the file will not be saved. The trees are all then loaded from this config file into cache and returned. + ///// + //private List GetAppTrees() + //{ + // return _cache.RuntimeCache.GetCacheItem>( + // CacheKeys.ApplicationTreeCacheKey, + // () => + // { + // var list = ReadFromXmlAndSort(); - //now we can check the non-volatile flag - if (_allAvailableTrees != null) - { - var hasChanges = false; + // //now we can check the non-volatile flag + // if (_allAvailableTrees != null) + // { + // var hasChanges = false; - LoadXml(doc => - { - //Now, load in the xml structure and update it with anything that is not declared there and save the file. + // LoadXml(doc => + // { + // //Now, load in the xml structure and update it with anything that is not declared there and save the file. - //NOTE: On the first iteration here, it will lazily scan all trees, etc... this is because this ienumerable is lazy - // based on the ApplicationTreeRegistrar - and as noted there this is not an ideal way to do things but were stuck like this - // currently because of the legacy assemblies and types not in the Core. + // //NOTE: On the first iteration here, it will lazily scan all trees, etc... this is because this ienumerable is lazy + // // based on the ApplicationTreeRegistrar - and as noted there this is not an ideal way to do things but were stuck like this + // // currently because of the legacy assemblies and types not in the Core. - //Get all the trees not registered in the config (those not matching by alias casing will be detected as "unregistered") - var unregistered = _allAvailableTrees.Value - .Where(x => list.Any(l => l.Alias == x.Alias) == false) - .ToArray(); + // //Get all the trees not registered in the config (those not matching by alias casing will be detected as "unregistered") + // var unregistered = _allAvailableTrees.Value + // .Where(x => list.Any(l => l.Alias == x.Alias) == false) + // .ToArray(); - hasChanges = unregistered.Any(); + // hasChanges = unregistered.Any(); - if (hasChanges == false) return false; + // if (hasChanges == false) return false; - //add or edit the unregistered ones and re-save the file if any changes were found - var count = 0; - foreach (var tree in unregistered) - { - var existingElement = doc.Root.Elements("add").SingleOrDefault(x => - string.Equals(x.Attribute("alias").Value, tree.Alias, - StringComparison.InvariantCultureIgnoreCase) && - string.Equals(x.Attribute("application").Value, tree.ApplicationAlias, - StringComparison.InvariantCultureIgnoreCase)); - if (existingElement != null) - { - existingElement.SetAttributeValue("alias", tree.Alias); - } - else - { - if (tree.Title.IsNullOrWhiteSpace()) - { - doc.Root.Add(new XElement("add", - new XAttribute("initialize", tree.Initialize), - new XAttribute("sortOrder", tree.SortOrder), - new XAttribute("alias", tree.Alias), - new XAttribute("application", tree.ApplicationAlias), - new XAttribute("iconClosed", tree.IconClosed), - new XAttribute("iconOpen", tree.IconOpened), - new XAttribute("type", tree.Type))); - } - else - { - doc.Root.Add(new XElement("add", - new XAttribute("initialize", tree.Initialize), - new XAttribute("sortOrder", tree.SortOrder), - new XAttribute("alias", tree.Alias), - new XAttribute("application", tree.ApplicationAlias), - new XAttribute("title", tree.Title), - new XAttribute("iconClosed", tree.IconClosed), - new XAttribute("iconOpen", tree.IconOpened), - new XAttribute("type", tree.Type))); - } + // //add or edit the unregistered ones and re-save the file if any changes were found + // var count = 0; + // foreach (var tree in unregistered) + // { + // var existingElement = doc.Root.Elements("add").SingleOrDefault(x => + // string.Equals(x.Attribute("alias").Value, tree.Alias, + // StringComparison.InvariantCultureIgnoreCase) && + // string.Equals(x.Attribute("application").Value, tree.ApplicationAlias, + // StringComparison.InvariantCultureIgnoreCase)); + // if (existingElement != null) + // { + // existingElement.SetAttributeValue("alias", tree.Alias); + // } + // else + // { + // if (tree.Title.IsNullOrWhiteSpace()) + // { + // doc.Root.Add(new XElement("add", + // new XAttribute("initialize", tree.Initialize), + // new XAttribute("sortOrder", tree.SortOrder), + // new XAttribute("alias", tree.Alias), + // new XAttribute("application", tree.ApplicationAlias), + // new XAttribute("iconClosed", tree.IconClosed), + // new XAttribute("iconOpen", tree.IconOpened), + // new XAttribute("type", tree.Type))); + // } + // else + // { + // doc.Root.Add(new XElement("add", + // new XAttribute("initialize", tree.Initialize), + // new XAttribute("sortOrder", tree.SortOrder), + // new XAttribute("alias", tree.Alias), + // new XAttribute("application", tree.ApplicationAlias), + // new XAttribute("title", tree.Title), + // new XAttribute("iconClosed", tree.IconClosed), + // new XAttribute("iconOpen", tree.IconOpened), + // new XAttribute("type", tree.Type))); + // } - } - count++; - } + // } + // count++; + // } - //don't save if there's no changes - return count > 0; - }, true); + // //don't save if there's no changes + // return count > 0; + // }, true); - if (hasChanges) - { - //If there were changes, we need to re-read the structures from the XML - list = ReadFromXmlAndSort(); - } - } + // if (hasChanges) + // { + // //If there were changes, we need to re-read the structures from the XML + // list = ReadFromXmlAndSort(); + // } + // } - return list; - }, new TimeSpan(0, 10, 0)); - } + // return list; + // }, new TimeSpan(0, 10, 0)); + //} - /// - /// Creates a new application tree. - /// - /// if set to true [initialize]. - /// The sort order. - /// The application alias. - /// The alias. - /// The title. - /// The icon closed. - /// The icon opened. - /// The type. - public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - { - LoadXml(doc => - { - var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == alias && x.Attribute("application").Value == applicationAlias); + ///// + ///// Creates a new application tree. + ///// + ///// if set to true [initialize]. + ///// The sort order. + ///// The application alias. + ///// The alias. + ///// The title. + ///// The icon closed. + ///// The icon opened. + ///// The type. + //public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) + //{ + // LoadXml(doc => + // { + // var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == alias && x.Attribute("application").Value == applicationAlias); - if (el == null) - { - doc.Root.Add(new XElement("add", - new XAttribute("initialize", initialize), - new XAttribute("sortOrder", sortOrder), - new XAttribute("alias", alias), - new XAttribute("application", applicationAlias), - new XAttribute("title", title), - new XAttribute("iconClosed", iconClosed), - new XAttribute("iconOpen", iconOpened), - new XAttribute("type", type))); - } + // if (el == null) + // { + // doc.Root.Add(new XElement("add", + // new XAttribute("initialize", initialize), + // new XAttribute("sortOrder", sortOrder), + // new XAttribute("alias", alias), + // new XAttribute("application", applicationAlias), + // new XAttribute("title", title), + // new XAttribute("iconClosed", iconClosed), + // new XAttribute("iconOpen", iconOpened), + // new XAttribute("type", type))); + // } - return true; + // return true; - }, true); + // }, true); - OnNew(new ApplicationTree(initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, type), new EventArgs()); - } + // OnNew(new ApplicationTree(initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, type), new EventArgs()); + //} - /// - /// Saves this instance. - /// - public void SaveTree(ApplicationTree tree) - { - LoadXml(doc => - { - var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == tree.Alias && x.Attribute("application").Value == tree.ApplicationAlias); + ///// + ///// Saves this instance. + ///// + //public void SaveTree(ApplicationTree tree) + //{ + // LoadXml(doc => + // { + // var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == tree.Alias && x.Attribute("application").Value == tree.ApplicationAlias); - if (el != null) - { - el.RemoveAttributes(); + // if (el != null) + // { + // el.RemoveAttributes(); - el.Add(new XAttribute("initialize", tree.Initialize)); - el.Add(new XAttribute("sortOrder", tree.SortOrder)); - el.Add(new XAttribute("alias", tree.Alias)); - el.Add(new XAttribute("application", tree.ApplicationAlias)); - el.Add(new XAttribute("title", tree.Title)); - el.Add(new XAttribute("iconClosed", tree.IconClosed)); - el.Add(new XAttribute("iconOpen", tree.IconOpened)); - el.Add(new XAttribute("type", tree.Type)); - } + // el.Add(new XAttribute("initialize", tree.Initialize)); + // el.Add(new XAttribute("sortOrder", tree.SortOrder)); + // el.Add(new XAttribute("alias", tree.Alias)); + // el.Add(new XAttribute("application", tree.ApplicationAlias)); + // el.Add(new XAttribute("title", tree.Title)); + // el.Add(new XAttribute("iconClosed", tree.IconClosed)); + // el.Add(new XAttribute("iconOpen", tree.IconOpened)); + // el.Add(new XAttribute("type", tree.Type)); + // } - return true; + // return true; - }, true); + // }, true); - OnUpdated(tree, new EventArgs()); - } + // OnUpdated(tree, new EventArgs()); + //} - /// - /// Deletes this instance. - /// - public void DeleteTree(ApplicationTree tree) - { - LoadXml(doc => - { - doc.Root.Elements("add") - .Where(x => x.Attribute("application") != null - && x.Attribute("application").Value == tree.ApplicationAlias - && x.Attribute("alias") != null && x.Attribute("alias").Value == tree.Alias).Remove(); + ///// + ///// Deletes this instance. + ///// + //public void DeleteTree(ApplicationTree tree) + //{ + // LoadXml(doc => + // { + // doc.Root.Elements("add") + // .Where(x => x.Attribute("application") != null + // && x.Attribute("application").Value == tree.ApplicationAlias + // && x.Attribute("alias") != null && x.Attribute("alias").Value == tree.Alias).Remove(); - return true; + // return true; - }, true); + // }, true); - OnDeleted(tree, new EventArgs()); - } + // OnDeleted(tree, new EventArgs()); + //} - /// - /// Gets an ApplicationTree by it's tree alias. - /// - /// The tree alias. - /// An ApplicationTree instance - public ApplicationTree GetByAlias(string treeAlias) - { - return GetAppTrees().Find(t => (t.Alias == treeAlias)); + /// + public ApplicationTree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.Alias == treeAlias); - } + /// + public IEnumerable GetAll() => _treeCollection; - /// - /// Gets all applicationTrees registered in umbraco from the umbracoAppTree table.. - /// - /// Returns a ApplicationTree Array - public IEnumerable GetAll() - { - return GetAppTrees().OrderBy(x => x.SortOrder); - } - - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// Returns a ApplicationTree Array + /// public IEnumerable GetApplicationTrees(string applicationAlias) - { - return GetApplicationTrees(applicationAlias, false); - } + => GetAll().Where(x => x.ApplicationAlias.InvariantEquals(applicationAlias)).OrderBy(x => x.SortOrder).ToList(); - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// - /// Returns a ApplicationTree Array - public IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized) - { - var list = GetAppTrees().FindAll( - t => - { - if (onlyInitialized) - return (t.ApplicationAlias == applicationAlias && t.Initialize); - return (t.ApplicationAlias == applicationAlias); - } - ); + ///// + ///// Gets the application tree for the applcation with the specified alias + ///// + ///// The application alias. + ///// + ///// Returns a ApplicationTree Array + //public IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized) + //{ + // var list = GetAppTrees().FindAll( + // t => + // { + // if (onlyInitialized) + // return (t.ApplicationAlias == applicationAlias && t.Initialize); + // return (t.ApplicationAlias == applicationAlias); + // } + // ); - return list.OrderBy(x => x.SortOrder).ToArray(); - } + // return list.OrderBy(x => x.SortOrder).ToArray(); + //} - public IDictionary> GetGroupedApplicationTrees(string applicationAlias, bool onlyInitialized) + public IDictionary> GetGroupedApplicationTrees(string applicationAlias) { var result = new Dictionary>(); - var foundTrees = GetApplicationTrees(applicationAlias, onlyInitialized); + var foundTrees = GetApplicationTrees(applicationAlias).ToList(); foreach(var treeGroup in _groupedTrees.Value) { List resultGroup = null; @@ -309,185 +286,185 @@ namespace Umbraco.Web.Services return result; } - /// - /// Creates a group of all tree groups and their tree aliases - /// - /// - /// - /// Used to initialize the field - /// - private IReadOnlyCollection> InitGroupedTrees() - { - var result = GetAll() - .Select(x => (treeAlias: x.Alias, treeGroup: x.GetRuntimeType().GetCustomAttribute(false)?.TreeGroup)) - .GroupBy(x => x.treeGroup, x => x.treeAlias) - .ToList(); - return result; - } - - /// - /// Loads in the xml structure from disk if one is found, otherwise loads in an empty xml structure, calls the - /// callback with the xml document and saves the structure back to disk if saveAfterCallback is true. - /// - /// - /// - internal void LoadXml(Func callback, bool saveAfterCallbackIfChanges) - { - lock (Locker) - { - var doc = System.IO.File.Exists(TreeConfigFilePath) - ? XDocument.Load(TreeConfigFilePath) - : XDocument.Parse(""); + ///// + ///// Creates a group of all tree groups and their tree aliases + ///// + ///// + ///// + ///// Used to initialize the field + ///// + //private IReadOnlyCollection> InitGroupedTrees() + //{ + // var result = GetAll() + // .Select(x => (treeAlias: x.Alias, treeGroup: x.GetRuntimeType().GetCustomAttribute(false)?.TreeGroup)) + // .GroupBy(x => x.treeGroup, x => x.treeAlias) + // .ToList(); + // return result; + //} - if (doc.Root != null) - { - var hasChanges = callback.Invoke(doc); + ///// + ///// Loads in the xml structure from disk if one is found, otherwise loads in an empty xml structure, calls the + ///// callback with the xml document and saves the structure back to disk if saveAfterCallback is true. + ///// + ///// + ///// + //internal void LoadXml(Func callback, bool saveAfterCallbackIfChanges) + //{ + // lock (Locker) + // { + // var doc = System.IO.File.Exists(TreeConfigFilePath) + // ? XDocument.Load(TreeConfigFilePath) + // : XDocument.Parse(""); - if (saveAfterCallbackIfChanges && hasChanges - //Don't save it if it is empty, in some very rare cases if the app domain get's killed in the middle of this process - // in some insane way the file saved will be empty. I'm pretty sure it's not actually anything to do with the xml doc and - // more about the IO trying to save the XML doc, but it doesn't hurt to check. - && doc.Root != null && doc.Root.Elements().Any()) - { - //ensures the folder exists - Directory.CreateDirectory(Path.GetDirectoryName(TreeConfigFilePath)); + // if (doc.Root != null) + // { + // var hasChanges = callback.Invoke(doc); - //saves it - doc.Save(TreeConfigFilePath); + // if (saveAfterCallbackIfChanges && hasChanges + // //Don't save it if it is empty, in some very rare cases if the app domain get's killed in the middle of this process + // // in some insane way the file saved will be empty. I'm pretty sure it's not actually anything to do with the xml doc and + // // more about the IO trying to save the XML doc, but it doesn't hurt to check. + // && doc.Root != null && doc.Root.Elements().Any()) + // { + // //ensures the folder exists + // Directory.CreateDirectory(Path.GetDirectoryName(TreeConfigFilePath)); - //remove the cache now that it has changed SD: I'm leaving this here even though it - // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); - } - } - } - } + // //saves it + // doc.Save(TreeConfigFilePath); - private List ReadFromXmlAndSort() - { - var list = new List(); + // //remove the cache now that it has changed SD: I'm leaving this here even though it + // // is taken care of by events as well, I think unit tests may rely on it being cleared here. + // _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + // } + // } + // } + //} - //read in the xml file containing trees and convert them all to ApplicationTree instances - LoadXml(doc => - { - foreach (var addElement in doc.Root.Elements("add").OrderBy(x => - { - var sortOrderAttr = x.Attribute("sortOrder"); - return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; - })) - { - var applicationAlias = (string)addElement.Attribute("application"); - var type = (string)addElement.Attribute("type"); - var assembly = (string)addElement.Attribute("assembly"); + //private List ReadFromXmlAndSort() + //{ + // var list = new List(); - var clrType = Type.GetType(type); - if (clrType == null) - { - _logger.Warn("The tree definition: {AddElement} could not be resolved to a .Net object type", addElement); - continue; - } + // //read in the xml file containing trees and convert them all to ApplicationTree instances + // LoadXml(doc => + // { + // foreach (var addElement in doc.Root.Elements("add").OrderBy(x => + // { + // var sortOrderAttr = x.Attribute("sortOrder"); + // return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; + // })) + // { + // var applicationAlias = (string)addElement.Attribute("application"); + // var type = (string)addElement.Attribute("type"); + // var assembly = (string)addElement.Attribute("assembly"); - //check if the tree definition (applicationAlias + type + assembly) is already in the list + // var clrType = Type.GetType(type); + // if (clrType == null) + // { + // _logger.Warn("The tree definition: {AddElement} could not be resolved to a .Net object type", addElement); + // continue; + // } - if (list.Any(tree => tree.ApplicationAlias.InvariantEquals(applicationAlias) && tree.GetRuntimeType() == clrType) == false) - { - list.Add(new ApplicationTree( - addElement.Attribute("initialize") == null || Convert.ToBoolean(addElement.Attribute("initialize").Value), - addElement.Attribute("sortOrder") != null - ? Convert.ToByte(addElement.Attribute("sortOrder").Value) - : (byte)0, - (string)addElement.Attribute("application"), - (string)addElement.Attribute("alias"), - (string)addElement.Attribute("title"), - (string)addElement.Attribute("iconClosed"), - (string)addElement.Attribute("iconOpen"), - (string)addElement.Attribute("type"))); - } - } + // //check if the tree definition (applicationAlias + type + assembly) is already in the list - return false; + // if (list.Any(tree => tree.ApplicationAlias.InvariantEquals(applicationAlias) && tree.GetRuntimeType() == clrType) == false) + // { + // list.Add(new ApplicationTree( + // addElement.Attribute("initialize") == null || Convert.ToBoolean(addElement.Attribute("initialize").Value), + // addElement.Attribute("sortOrder") != null + // ? Convert.ToByte(addElement.Attribute("sortOrder").Value) + // : (byte)0, + // (string)addElement.Attribute("application"), + // (string)addElement.Attribute("alias"), + // (string)addElement.Attribute("title"), + // (string)addElement.Attribute("iconClosed"), + // (string)addElement.Attribute("iconOpen"), + // (string)addElement.Attribute("type"))); + // } + // } - }, false); + // return false; - return list; - } + // }, false); + + // return list; + //} - internal static event TypedEventHandler Deleted; - private static void OnDeleted(ApplicationTree app, EventArgs args) - { - if (Deleted != null) - { - Deleted(app, args); - } - } + //internal static event TypedEventHandler Deleted; + //private static void OnDeleted(ApplicationTree app, EventArgs args) + //{ + // if (Deleted != null) + // { + // Deleted(app, args); + // } + //} - internal static event TypedEventHandler New; - private static void OnNew(ApplicationTree app, EventArgs args) - { - if (New != null) - { - New(app, args); - } - } + //internal static event TypedEventHandler New; + //private static void OnNew(ApplicationTree app, EventArgs args) + //{ + // if (New != null) + // { + // New(app, args); + // } + //} - internal static event TypedEventHandler Updated; - private static void OnUpdated(ApplicationTree app, EventArgs args) - { - if (Updated != null) - { - Updated(app, args); - } - } + //internal static event TypedEventHandler Updated; + //private static void OnUpdated(ApplicationTree app, EventArgs args) + //{ + // if (Updated != null) + // { + // Updated(app, args); + // } + //} - /// - /// This class is here so that we can provide lazy access to tree scanning for when it is needed - /// - private class LazyEnumerableTrees : IEnumerable - { - public LazyEnumerableTrees(TypeLoader typeLoader) - { - _lazyTrees = new Lazy>(() => - { - var added = new List(); + ///// + ///// This class is here so that we can provide lazy access to tree scanning for when it is needed + ///// + //private class LazyEnumerableTrees : IEnumerable + //{ + // public LazyEnumerableTrees(TypeLoader typeLoader) + // { + // _lazyTrees = new Lazy>(() => + // { + // var added = new List(); - // Load all Controller Trees by attribute - var types = typeLoader.GetTypesWithAttribute(); // fixme inject - //convert them to ApplicationTree instances - var items = types - .Select(x => (tree: x, treeAttribute: x.GetCustomAttributes(false).Single())) - .Select(x => new ApplicationTree(x.treeAttribute.Initialize, x.treeAttribute.SortOrder, x.treeAttribute.ApplicationAlias, x.treeAttribute.Alias, x.treeAttribute.Title, x.treeAttribute.IconClosed, x.treeAttribute.IconOpen, x.tree.GetFullNameWithAssembly())) - .ToArray(); + // // Load all Controller Trees by attribute + // var types = typeLoader.GetTypesWithAttribute(); // fixme inject + // //convert them to ApplicationTree instances + // var items = types + // .Select(x => (tree: x, treeAttribute: x.GetCustomAttributes(false).Single())) + // .Select(x => new ApplicationTree(x.treeAttribute.Initialize, x.treeAttribute.SortOrder, x.treeAttribute.ApplicationAlias, x.treeAttribute.Alias, x.treeAttribute.Title, x.treeAttribute.IconClosed, x.treeAttribute.IconOpen, x.tree.GetFullNameWithAssembly())) + // .ToArray(); - added.AddRange(items.Select(x => x.Alias)); + // added.AddRange(items.Select(x => x.Alias)); - return items.ToArray(); - }); - } + // return items.ToArray(); + // }); + // } - private readonly Lazy> _lazyTrees; - - /// - /// Returns an enumerator that iterates through the collection. - /// - /// - /// A that can be used to iterate through the collection. - /// - public IEnumerator GetEnumerator() - { - return _lazyTrees.Value.GetEnumerator(); - } + // private readonly Lazy> _lazyTrees; - /// - /// Returns an enumerator that iterates through a collection. - /// - /// - /// An object that can be used to iterate through the collection. - /// - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } + // /// + // /// Returns an enumerator that iterates through the collection. + // /// + // /// + // /// A that can be used to iterate through the collection. + // /// + // public IEnumerator GetEnumerator() + // { + // return _lazyTrees.Value.GetEnumerator(); + // } + + // /// + // /// Returns an enumerator that iterates through a collection. + // /// + // /// + // /// An object that can be used to iterate through the collection. + // /// + // IEnumerator IEnumerable.GetEnumerator() + // { + // return GetEnumerator(); + // } + //} } } diff --git a/src/Umbraco.Core/Services/IApplicationTreeService.cs b/src/Umbraco.Web/Services/IApplicationTreeService.cs similarity index 52% rename from src/Umbraco.Core/Services/IApplicationTreeService.cs rename to src/Umbraco.Web/Services/IApplicationTreeService.cs index 691a3a0b63..1fd7bc939a 100644 --- a/src/Umbraco.Core/Services/IApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/IApplicationTreeService.cs @@ -2,33 +2,35 @@ using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; -namespace Umbraco.Core.Services +namespace Umbraco.Web.Services { public interface IApplicationTreeService { - /// - /// Creates a new application tree. - /// - /// if set to true [initialize]. - /// The sort order. - /// The application alias. - /// The alias. - /// The title. - /// The icon closed. - /// The icon opened. - /// The type. - void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type); + ///// + ///// Creates a new application tree. + ///// + ///// if set to true [initialize]. + ///// The sort order. + ///// The application alias. + ///// The alias. + ///// The title. + ///// The icon closed. + ///// The icon opened. + ///// The type. + //void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type); - /// - /// Saves this instance. - /// - void SaveTree(ApplicationTree tree); + ///// + ///// Saves this instance. + ///// + //void SaveTree(ApplicationTree tree); - /// - /// Deletes this instance. - /// - void DeleteTree(ApplicationTree tree); + ///// + ///// Deletes this instance. + ///// + //void DeleteTree(ApplicationTree tree); /// /// Gets an ApplicationTree by it's tree alias. @@ -50,21 +52,20 @@ namespace Umbraco.Core.Services /// Returns a ApplicationTree Array IEnumerable GetApplicationTrees(string applicationAlias); - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// - /// Returns a ApplicationTree Array - IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized); + ///// + ///// Gets the application tree for the applcation with the specified alias + ///// + ///// The application alias. + ///// + ///// Returns a ApplicationTree Array + //IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized); /// /// Gets the grouped application trees for the application with the specified alias /// /// - /// /// - IDictionary> GetGroupedApplicationTrees(string applicationAlias, bool onlyInitialized); + IDictionary> GetGroupedApplicationTrees(string applicationAlias); } /// @@ -72,37 +73,37 @@ namespace Umbraco.Core.Services /// internal class EmptyApplicationTreeService : IApplicationTreeService { - /// - /// Creates a new application tree. - /// - /// if set to true [initialize]. - /// The sort order. - /// The application alias. - /// The alias. - /// The title. - /// The icon closed. - /// The icon opened. - /// The type. - public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - { - throw new System.NotImplementedException(); - } + ///// + ///// Creates a new application tree. + ///// + ///// if set to true [initialize]. + ///// The sort order. + ///// The application alias. + ///// The alias. + ///// The title. + ///// The icon closed. + ///// The icon opened. + ///// The type. + //public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) + //{ + // throw new System.NotImplementedException(); + //} - /// - /// Saves this instance. - /// - public void SaveTree(ApplicationTree tree) - { - throw new System.NotImplementedException(); - } + ///// + ///// Saves this instance. + ///// + //public void SaveTree(ApplicationTree tree) + //{ + // throw new System.NotImplementedException(); + //} - /// - /// Deletes this instance. - /// - public void DeleteTree(ApplicationTree tree) - { - throw new System.NotImplementedException(); - } + ///// + ///// Deletes this instance. + ///// + //public void DeleteTree(ApplicationTree tree) + //{ + // throw new System.NotImplementedException(); + //} /// /// Gets an ApplicationTree by it's tree alias. @@ -123,7 +124,7 @@ namespace Umbraco.Core.Services throw new System.NotImplementedException(); } - public IDictionary> GetGroupedApplicationTrees(string applicationAlias, bool onlyInitialized) + public IDictionary> GetGroupedApplicationTrees(string applicationAlias) { throw new System.NotImplementedException(); } diff --git a/src/Umbraco.Web/Services/ISectionService.cs b/src/Umbraco.Web/Services/ISectionService.cs new file mode 100644 index 0000000000..560805634f --- /dev/null +++ b/src/Umbraco.Web/Services/ISectionService.cs @@ -0,0 +1,116 @@ +using System.Collections.Generic; +using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; + +namespace Umbraco.Web.Services +{ + public interface ISectionService + { + /// + /// The cache storage for all applications + /// + IEnumerable GetSections(); + + /// + /// Get the user group's allowed sections + /// + /// + /// + IEnumerable GetAllowedSections(int userId); + + /// + /// Gets the application by its alias. + /// + /// The application alias. + /// + IBackOfficeSection GetByAlias(string appAlias); + + ///// + ///// Creates a new applcation if no application with the specified alias is found. + ///// + ///// The application name. + ///// The application alias. + ///// The application icon, which has to be located in umbraco/images/tray folder. + //void MakeNew(string name, string alias, string icon); + + ///// + ///// Makes the new. + ///// + ///// The name. + ///// The alias. + ///// The icon. + ///// The sort order. + //void MakeNew(string name, string alias, string icon, int sortOrder); + + ///// + ///// Deletes the section + ///// + //void DeleteSection(Section section); + } + + /// + /// Purely used to allow a service context to create the default services + /// + internal class EmptySectionService : ISectionService + { + /// + /// The cache storage for all applications + /// + public IEnumerable GetSections() + { + throw new System.NotImplementedException(); + } + + /// + /// Get the user's allowed sections + /// + /// + /// + public IEnumerable GetAllowedSections(int userId) + { + throw new System.NotImplementedException(); + } + + /// + /// Gets the application by its alias. + /// + /// The application alias. + /// + public IBackOfficeSection GetByAlias(string appAlias) + { + throw new System.NotImplementedException(); + } + + ///// + ///// Creates a new applcation if no application with the specified alias is found. + ///// + ///// The application name. + ///// The application alias. + ///// The application icon, which has to be located in umbraco/images/tray folder. + //public void MakeNew(string name, string alias, string icon) + //{ + // throw new System.NotImplementedException(); + //} + + ///// + ///// Makes the new. + ///// + ///// The name. + ///// The alias. + ///// The icon. + ///// The sort order. + //public void MakeNew(string name, string alias, string icon, int sortOrder) + //{ + // throw new System.NotImplementedException(); + //} + + ///// + ///// Deletes the section + ///// + //public void DeleteSection(IBackOfficeSection section) + //{ + // throw new System.NotImplementedException(); + //} + } +} diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index 6337db67f9..bb154976f0 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -10,9 +10,12 @@ using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Composing; +using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Scoping; using Umbraco.Core.Services; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Trees; +using Umbraco.Web.Trees; using File = System.IO.File; namespace Umbraco.Web.Services @@ -20,130 +23,90 @@ namespace Umbraco.Web.Services internal class SectionService : ISectionService { private readonly IUserService _userService; - private readonly Lazy> _allAvailableSections; - private readonly IApplicationTreeService _applicationTreeService; - private readonly IScopeProvider _scopeProvider; + private readonly BackOfficeSectionCollection _sectionCollection; + + private readonly Lazy> _allAvailableSections; + //private readonly IApplicationTreeService _applicationTreeService; + //private readonly IScopeProvider _scopeProvider; private readonly CacheHelper _cache; - internal const string AppConfigFileName = "applications.config"; - private static string _appConfig; - private static readonly object Locker = new object(); + //internal const string AppConfigFileName = "applications.config"; + //private static string _appConfig; + //private static readonly object Locker = new object(); public SectionService( IUserService userService, - IApplicationTreeService applicationTreeService, - IScopeProvider scopeProvider, + BackOfficeSectionCollection sectionCollection, CacheHelper cache) { - _applicationTreeService = applicationTreeService ?? throw new ArgumentNullException(nameof(applicationTreeService)); + //_applicationTreeService = applicationTreeService ?? throw new ArgumentNullException(nameof(applicationTreeService)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _userService = userService; - _scopeProvider = scopeProvider; - _allAvailableSections = new Lazy>(() => new LazyEnumerableSections()); + _sectionCollection = sectionCollection; + //_scopeProvider = scopeProvider; + //_allAvailableSections = new Lazy>(() => new LazyEnumerableSections()); } - /// - /// gets/sets the application.config file path - /// - /// - /// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath - /// - internal static string AppConfigFilePath - { - get - { - if (string.IsNullOrWhiteSpace(_appConfig)) - { - _appConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + AppConfigFileName); - } - return _appConfig; - } - set => _appConfig = value; - } + ///// + ///// gets/sets the application.config file path + ///// + ///// + ///// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath + ///// + //internal static string AppConfigFilePath + //{ + // get + // { + // if (string.IsNullOrWhiteSpace(_appConfig)) + // { + // _appConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + AppConfigFileName); + // } + // return _appConfig; + // } + // set => _appConfig = value; + //} /// /// The cache storage for all applications /// - public IEnumerable
GetSections() + public IEnumerable GetSections() { - return _cache.RuntimeCache.GetCacheItem>( - CacheKeys.ApplicationsCacheKey, - () => - { - var list = ReadFromXmlAndSort(); - var hasChanges = false; - var localCopyList = list; - - LoadXml(doc => - { - //Now, load in the xml structure and update it with anything that is not declared there and save the file. - //NOTE: On the first iteration here, it will lazily scan all apps, etc... this is because this ienumerable is lazy - //Get all the trees not registered in the config - - var unregistered = _allAvailableSections.Value - .Where(x => localCopyList.Any(l => l.Alias == x.Alias) == false) - .ToArray(); - - hasChanges = unregistered.Any(); - - var count = 0; - foreach (var attr in unregistered) - { - doc.Root.Add(new XElement("add", - new XAttribute("alias", attr.Alias), - new XAttribute("name", attr.Name), - new XAttribute("sortOrder", attr.SortOrder))); - count++; - } - - //don't save if there's no changes - return count > 0; - }, true); - - if (hasChanges) - { - //If there were changes, we need to re-read the structures from the XML - list = ReadFromXmlAndSort(); - } - - return list; - - }, new TimeSpan(0, 10, 0)); + return _sectionCollection; } - internal void LoadXml(Func callback, bool saveAfterCallbackIfChanged) - { - lock (Locker) - { - var doc = File.Exists(AppConfigFilePath) - ? XDocument.Load(AppConfigFilePath) - : XDocument.Parse(""); + //internal void LoadXml(Func callback, bool saveAfterCallbackIfChanged) + //{ + // lock (Locker) + // { + // var doc = File.Exists(AppConfigFilePath) + // ? XDocument.Load(AppConfigFilePath) + // : XDocument.Parse(""); - if (doc.Root != null) - { - var changed = callback.Invoke(doc); + // if (doc.Root != null) + // { + // var changed = callback.Invoke(doc); - if (saveAfterCallbackIfChanged && changed) - { - //ensure the folder is created! - Directory.CreateDirectory(Path.GetDirectoryName(AppConfigFilePath)); + // if (saveAfterCallbackIfChanged && changed) + // { + // //ensure the folder is created! + // Directory.CreateDirectory(Path.GetDirectoryName(AppConfigFilePath)); - doc.Save(AppConfigFilePath); + // doc.Save(AppConfigFilePath); - //remove the cache so it gets re-read ... SD: I'm leaving this here even though it - // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); - } - } - } - } + // //remove the cache so it gets re-read ... SD: I'm leaving this here even though it + // // is taken care of by events as well, I think unit tests may rely on it being cleared here. + // _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + // } + // } + // } + //} /// /// Get the user's allowed sections /// /// /// - public IEnumerable
GetAllowedSections(int userId) + public IEnumerable GetAllowedSections(int userId) { var user = _userService.GetUserById(userId); @@ -160,172 +123,172 @@ namespace Umbraco.Web.Services ///
/// The application alias. /// - public Section GetByAlias(string appAlias) + public IBackOfficeSection GetByAlias(string appAlias) { return GetSections().FirstOrDefault(t => t.Alias == appAlias); } - /// - /// Creates a new applcation if no application with the specified alias is found. - /// - /// The application name. - /// The application alias. - /// The application icon, which has to be located in umbraco/images/tray folder. - public void MakeNew(string name, string alias, string icon) - { - var sections = GetSections(); - var nextSortOrder = sections.Any() ? sections.Max(x => x.SortOrder) + 1 : 1; - MakeNew(name, alias, icon, nextSortOrder); - } + ///// + ///// Creates a new applcation if no application with the specified alias is found. + ///// + ///// The application name. + ///// The application alias. + ///// The application icon, which has to be located in umbraco/images/tray folder. + //public void MakeNew(string name, string alias, string icon) + //{ + // var sections = GetSections(); + // var nextSortOrder = sections.Any() ? sections.Max(x => x.SortOrder) + 1 : 1; + // MakeNew(name, alias, icon, nextSortOrder); + //} - /// - /// Makes the new. - /// - /// The name. - /// The alias. - /// The icon. - /// The sort order. - public void MakeNew(string name, string alias, string icon, int sortOrder) - { - if (GetSections().All(x => x.Alias != alias)) - { - LoadXml(doc => - { - doc.Root.Add(new XElement("add", - new XAttribute("alias", alias), - new XAttribute("name", name), - new XAttribute("icon", icon), - new XAttribute("sortOrder", sortOrder))); - return true; - }, true); + ///// + ///// Makes the new. + ///// + ///// The name. + ///// The alias. + ///// The icon. + ///// The sort order. + //public void MakeNew(string name, string alias, string icon, int sortOrder) + //{ + // if (GetSections().All(x => x.Alias != alias)) + // { + // LoadXml(doc => + // { + // doc.Root.Add(new XElement("add", + // new XAttribute("alias", alias), + // new XAttribute("name", name), + // new XAttribute("icon", icon), + // new XAttribute("sortOrder", sortOrder))); + // return true; + // }, true); - //raise event - OnNew(this /*new Section(name, alias, sortOrder)*/, new EventArgs()); - } - } + // //raise event + // OnNew(this /*new Section(name, alias, sortOrder)*/, new EventArgs()); + // } + //} - /// - /// Deletes the section - /// - public void DeleteSection(Section section) - { - lock (Locker) - { - //delete the assigned applications - using (var scope = _scopeProvider.CreateScope()) - { - scope.Database.Execute("delete from umbracoUserGroup2App where app = @appAlias", - new { appAlias = section.Alias }); - scope.Complete(); - } + ///// + ///// Deletes the section + ///// + //public void DeleteSection(Section section) + //{ + // lock (Locker) + // { + // //delete the assigned applications + // using (var scope = _scopeProvider.CreateScope()) + // { + // scope.Database.Execute("delete from umbracoUserGroup2App where app = @appAlias", + // new { appAlias = section.Alias }); + // scope.Complete(); + // } - //delete the assigned trees - var trees = _applicationTreeService.GetApplicationTrees(section.Alias); - foreach (var t in trees) - { - _applicationTreeService.DeleteTree(t); - } + // //delete the assigned trees + // var trees = _applicationTreeService.GetApplicationTrees(section.Alias); + // foreach (var t in trees) + // { + // _applicationTreeService.DeleteTree(t); + // } - LoadXml(doc => - { - doc.Root.Elements("add").Where(x => x.Attribute("alias") != null && x.Attribute("alias").Value == section.Alias) - .Remove(); + // LoadXml(doc => + // { + // doc.Root.Elements("add").Where(x => x.Attribute("alias") != null && x.Attribute("alias").Value == section.Alias) + // .Remove(); - return true; - }, true); + // return true; + // }, true); - //raise event - OnDeleted(this, new EventArgs()); - } - } + // //raise event + // OnDeleted(this, new EventArgs()); + // } + //} - private List
ReadFromXmlAndSort() - { - var tmp = new List
(); + //private List
ReadFromXmlAndSort() + //{ + // var tmp = new List
(); - LoadXml(doc => - { - foreach (var addElement in doc.Root.Elements("add").OrderBy(x => - { - var sortOrderAttr = x.Attribute("sortOrder"); - return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; - })) - { - var sortOrderAttr = addElement.Attribute("sortOrder"); - tmp.Add(new Section(addElement.Attribute("name").Value, - addElement.Attribute("alias").Value, - sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0)); - } - return false; - }, false); + // LoadXml(doc => + // { + // foreach (var addElement in doc.Root.Elements("add").OrderBy(x => + // { + // var sortOrderAttr = x.Attribute("sortOrder"); + // return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; + // })) + // { + // var sortOrderAttr = addElement.Attribute("sortOrder"); + // tmp.Add(new Section(addElement.Attribute("name").Value, + // addElement.Attribute("alias").Value, + // sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0)); + // } + // return false; + // }, false); - return tmp; - } + // return tmp; + //} - internal static event TypedEventHandler Deleted; - private static void OnDeleted(ISectionService app, EventArgs args) - { - if (Deleted != null) - { - Deleted(app, args); - } - } + //internal static event TypedEventHandler Deleted; + //private static void OnDeleted(ISectionService app, EventArgs args) + //{ + // if (Deleted != null) + // { + // Deleted(app, args); + // } + //} - internal static event TypedEventHandler New; - private static void OnNew(ISectionService app, EventArgs args) - { - if (New != null) - { - New(app, args); - } - } + //internal static event TypedEventHandler New; + //private static void OnNew(ISectionService app, EventArgs args) + //{ + // if (New != null) + // { + // New(app, args); + // } + //} - /// - /// This class is here so that we can provide lazy access to tree scanning for when it is needed - /// - private class LazyEnumerableSections : IEnumerable
- { - public LazyEnumerableSections() - { - _lazySections = new Lazy>(() => - { - // Load all Applications by attribute and add them to the XML config + ///// + ///// This class is here so that we can provide lazy access to tree scanning for when it is needed + ///// + //private class LazyEnumerableSections : IEnumerable
+ //{ + // public LazyEnumerableSections() + // { + // _lazySections = new Lazy>(() => + // { + // // Load all Applications by attribute and add them to the XML config - //don't cache the result of this because it is only used once during app startup, caching will just add a bit more mem overhead for no reason - var types = Current.TypeLoader.GetTypesWithAttribute(cache: false); // fixme - inject + // //don't cache the result of this because it is only used once during app startup, caching will just add a bit more mem overhead for no reason + // var types = Current.TypeLoader.GetTypesWithAttribute(cache: false); // fixme - inject - //since applications don't populate their metadata from the attribute and because it is an interface, - //we need to interrogate the attributes for the data. Would be better to have a base class that contains - //metadata populated by the attribute. Oh well i guess. - var attrs = types.Select(x => x.GetCustomAttributes(false).Single()); - return attrs.Select(x => new Section(x.Name, x.Alias, x.SortOrder)).ToArray(); - }); - } + // //since applications don't populate their metadata from the attribute and because it is an interface, + // //we need to interrogate the attributes for the data. Would be better to have a base class that contains + // //metadata populated by the attribute. Oh well i guess. + // var attrs = types.Select(x => x.GetCustomAttributes(false).Single()); + // return attrs.Select(x => new Section(x.Name, x.Alias, x.SortOrder)).ToArray(); + // }); + // } - private readonly Lazy> _lazySections; + // private readonly Lazy> _lazySections; - /// - /// Returns an enumerator that iterates through the collection. - /// - /// - /// A that can be used to iterate through the collection. - /// - public IEnumerator
GetEnumerator() - { - return _lazySections.Value.GetEnumerator(); - } + // /// + // /// Returns an enumerator that iterates through the collection. + // /// + // /// + // /// A that can be used to iterate through the collection. + // /// + // public IEnumerator
GetEnumerator() + // { + // return _lazySections.Value.GetEnumerator(); + // } - /// - /// Returns an enumerator that iterates through a collection. - /// - /// - /// An object that can be used to iterate through the collection. - /// - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } + // /// + // /// Returns an enumerator that iterates through a collection. + // /// + // /// + // /// An object that can be used to iterate through the collection. + // /// + // IEnumerator IEnumerable.GetEnumerator() + // { + // return GetEnumerator(); + // } + //} } } diff --git a/src/Umbraco.Web/Trees/ApplicationTreeController.cs b/src/Umbraco.Web/Trees/ApplicationTreeController.cs index 0454155772..7e7c77d607 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web/Trees/ApplicationTreeController.cs @@ -7,10 +7,17 @@ using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Http; using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration; +using Umbraco.Core.Logging; using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Core.Persistence; using Umbraco.Core.Services; +using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; +using Umbraco.Web.Services; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; @@ -20,7 +27,19 @@ namespace Umbraco.Web.Trees [AngularJsonOnlyConfiguration] [PluginController("UmbracoTrees")] public class ApplicationTreeController : UmbracoAuthorizedApiController - { + { + private readonly TreeControllerResolver _treeControllerResolver; + private readonly IApplicationTreeService _treeService; + + public ApplicationTreeController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, + ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, + IRuntimeState runtimeState, TreeControllerResolver treeControllerResolver, IApplicationTreeService treeService) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) + { + _treeControllerResolver = treeControllerResolver; + _treeService = treeService; + } + /// /// Returns the tree nodes for an application /// @@ -30,14 +49,14 @@ namespace Umbraco.Web.Trees /// An optional bool (defaults to true), if set to false it will also load uninitialized trees /// [HttpQueryStringFilter("queryStrings")] - public async Task GetApplicationTrees(string application, string tree, FormDataCollection queryStrings, bool onlyInitialized = true) + public async Task GetApplicationTrees(string application, string tree, FormDataCollection queryStrings/*, bool onlyInitialized = true*/) { application = application.CleanForXss(); if (string.IsNullOrEmpty(application)) throw new HttpResponseException(HttpStatusCode.NotFound); //find all tree definitions that have the current application alias - var groupedTrees = Services.ApplicationTreeService.GetGroupedApplicationTrees(application, onlyInitialized); + var groupedTrees = _treeService.GetGroupedApplicationTrees(application); var allTrees = groupedTrees.Values.SelectMany(x => x).ToList(); if (string.IsNullOrEmpty(tree) == false || allTrees.Count == 1) @@ -142,7 +161,7 @@ namespace Umbraco.Web.Trees if (configTree == null) throw new ArgumentNullException(nameof(configTree)); try { - var byControllerAttempt = await configTree.TryGetRootNodeFromControllerTree(queryStrings, ControllerContext); + var byControllerAttempt = await _treeControllerResolver.TryGetRootNodeFromControllerTree(configTree, queryStrings, ControllerContext); if (byControllerAttempt.Success) { return byControllerAttempt.Result; @@ -170,17 +189,17 @@ namespace Umbraco.Web.Trees { var rootId = Constants.System.Root.ToString(CultureInfo.InvariantCulture); if (configTree == null) throw new ArgumentNullException(nameof(configTree)); - var byControllerAttempt = configTree.TryLoadFromControllerTree(id, queryStrings, ControllerContext); + var byControllerAttempt = _treeControllerResolver.TryLoadFromControllerTree(configTree, id, queryStrings, ControllerContext); if (byControllerAttempt.Success) { - var rootNode = await configTree.TryGetRootNodeFromControllerTree(queryStrings, ControllerContext); + var rootNode = await _treeControllerResolver.TryGetRootNodeFromControllerTree(configTree, queryStrings, ControllerContext); if (rootNode.Success == false) { //This should really never happen if we've successfully got the children above. throw new InvalidOperationException("Could not create root node for tree " + configTree.Alias); } - var treeAttribute = configTree.GetTreeAttribute(); + var treeAttribute = _treeControllerResolver.GetTreeAttribute(configTree); var sectionRoot = TreeRootNode.CreateSingleTreeRoot( rootId, diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs new file mode 100644 index 0000000000..2b5a78d758 --- /dev/null +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using Umbraco.Core.Composing; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; + +namespace Umbraco.Web.Trees +{ + public class BackOfficeSectionCollection : BuilderCollectionBase + { + public BackOfficeSectionCollection(IEnumerable items) + : base(items) + { } + } + + public class BackOfficeSectionCollectionBuilder : LazyCollectionBuilderBase + { + protected override BackOfficeSectionCollectionBuilder This => this; + + //TODO: can we allow for re-ordering OOTB without exposing other methods? + } +} diff --git a/src/Umbraco.Web/Trees/TreeCollection.cs b/src/Umbraco.Web/Trees/TreeCollection.cs new file mode 100644 index 0000000000..8f913fb2d7 --- /dev/null +++ b/src/Umbraco.Web/Trees/TreeCollection.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Umbraco.Core.Composing; +using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; + +namespace Umbraco.Web.Trees +{ + public class TreeCollection : BuilderCollectionBase + { + public TreeCollection(IEnumerable items) + : base(items) + { } + } + + public class TreeCollectionBuilder : LazyCollectionBuilderBase + { + protected override TreeCollectionBuilder This => this; + + //TODO: can we allow for re-ordering OOTB without exposing other methods? + } + +} diff --git a/src/Umbraco.Web/Trees/TreeController.cs b/src/Umbraco.Web/Trees/TreeController.cs index 1c37307db5..102671ec29 100644 --- a/src/Umbraco.Web/Trees/TreeController.cs +++ b/src/Umbraco.Web/Trees/TreeController.cs @@ -1,4 +1,12 @@ -namespace Umbraco.Web.Trees +using System; +using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration; +using Umbraco.Core.Logging; +using Umbraco.Core.Persistence; +using Umbraco.Core.Services; + +namespace Umbraco.Web.Trees { /// /// The base controller for all tree requests @@ -8,6 +16,10 @@ private TreeAttribute _attribute; private string _rootNodeDisplayName; + protected TreeController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) + { + } + protected TreeController() { Initialize(); @@ -17,21 +29,25 @@ /// The name to display on the root node /// public override string RootNodeDisplayName - => _rootNodeDisplayName - ?? (_rootNodeDisplayName = Services.ApplicationTreeService.GetByAlias(_attribute.Alias) - ?.GetRootNodeDisplayName(Services.TextService)); + { + get + { + throw new NotImplementedException(); + //return _rootNodeDisplayName + // ?? (_rootNodeDisplayName = Services.ApplicationTreeService.GetByAlias(_attribute.Alias) + // ?.GetRootNodeDisplayName(Services.TextService)); + } + } /// /// Gets the current tree alias from the attribute assigned to it. /// - public override string TreeAlias - { - get { return _attribute.Alias; } - } + public override string TreeAlias => _attribute.Alias; private void Initialize() { - _attribute = GetType().GetTreeAttribute(); + throw new NotImplementedException(); + //_attribute = GetType().GetTreeAttribute(); } } } diff --git a/src/Umbraco.Web/Trees/TreeControllerBase.cs b/src/Umbraco.Web/Trees/TreeControllerBase.cs index ffdcac4479..c00d6053c8 100644 --- a/src/Umbraco.Web/Trees/TreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/TreeControllerBase.cs @@ -4,9 +4,14 @@ using System.Linq; using System.Net.Http.Formatting; using System.Web.Http.Routing; using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Configuration; using Umbraco.Core.Events; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; +using Umbraco.Core.Persistence; +using Umbraco.Core.Services; using Umbraco.Web.Models.Trees; using Umbraco.Web.WebApi; using Umbraco.Web.WebApi.Filters; @@ -14,12 +19,23 @@ using Umbraco.Web.WebApi.Filters; namespace Umbraco.Web.Trees { /// - /// A base controller reference for non-attributed trees (un-registered). Developers should inherit from - /// TreeController. + /// A base controller reference for non-attributed trees (un-registered). /// + /// + /// Developers should generally inherit from TreeController. + /// [AngularJsonOnlyConfiguration] public abstract class TreeControllerBase : UmbracoAuthorizedApiController { + protected TreeControllerBase() + { + } + + protected TreeControllerBase(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) + { + } + + /// /// The method called to render the contents of the tree structure /// @@ -351,7 +367,7 @@ namespace Umbraco.Web.Trees private static void OnTreeNodesRendering(TreeControllerBase instance, TreeNodesRenderingEventArgs e) { var handler = TreeNodesRendering; - if (handler != null) handler(instance, e); + handler?.Invoke(instance, e); } /// @@ -363,7 +379,7 @@ namespace Umbraco.Web.Trees internal static void OnRootNodeRendering(TreeControllerBase instance, TreeNodeRenderingEventArgs e) { var handler = RootNodeRendering; - if (handler != null) handler(instance, e); + handler?.Invoke(instance, e); } /// @@ -377,80 +393,8 @@ namespace Umbraco.Web.Trees private static void OnMenuRendering(TreeControllerBase instance, MenuRenderingEventArgs e) { var handler = MenuRendering; - if (handler != null) handler(instance, e); + handler?.Invoke(instance, e); } } - internal class TreeControllerBaseStuffForLegacy - { - private readonly string _treeAlias; - private readonly string _rootNodeDisplayName; - private readonly UrlHelper _url; - - public TreeControllerBaseStuffForLegacy(string treeAlias, string rootNodeDisplayName, UrlHelper url) - { - _treeAlias = treeAlias; - _rootNodeDisplayName = rootNodeDisplayName; - _url = url; - } - - public TreeNode GetRootNode(FormDataCollection queryStrings) - { - if (queryStrings == null) queryStrings = new FormDataCollection(""); - var node = CreateRootNode(queryStrings); - - //add the tree alias to the root - node.AdditionalData["treeAlias"] = _treeAlias; - - AddQueryStringsToAdditionalData(node, queryStrings); - - //check if the tree is searchable and add that to the meta data as well - if (this is ISearchableTree) - { - node.AdditionalData.Add("searchable", "true"); - } - - //now update all data based on some of the query strings, like if we are running in dialog mode - if (IsDialog(queryStrings)) - { - node.RoutePath = "#"; - } - - TreeControllerBase.OnRootNodeRendering(null, new TreeNodeRenderingEventArgs(node, queryStrings)); - - return node; - } - - protected virtual TreeNode CreateRootNode(FormDataCollection queryStrings) - { - var rootNodeAsString = Constants.System.Root.ToString(CultureInfo.InvariantCulture); - var currApp = queryStrings.GetValue(TreeQueryStringParameters.Application); - - var node = new TreeNode( - rootNodeAsString, - null, //this is a root node, there is no parent - _url.GetTreeUrl(GetType(), rootNodeAsString, queryStrings), - _url.GetMenuUrl(GetType(), rootNodeAsString, queryStrings)) - { - HasChildren = true, - RoutePath = currApp, - Name = _rootNodeDisplayName - }; - - return node; - } - - protected void AddQueryStringsToAdditionalData(TreeNode node, FormDataCollection queryStrings) - { - foreach (var q in queryStrings.Where(x => node.AdditionalData.ContainsKey(x.Key) == false)) - { - node.AdditionalData.Add(q.Key, q.Value); - } - } - - protected bool IsDialog(FormDataCollection queryStrings) - { - return queryStrings.GetValue(TreeQueryStringParameters.IsDialog); - } - } } diff --git a/src/Umbraco.Web/Trees/ApplicationTreeExtensions.cs b/src/Umbraco.Web/Trees/TreeControllerResolver.cs similarity index 56% rename from src/Umbraco.Web/Trees/ApplicationTreeExtensions.cs rename to src/Umbraco.Web/Trees/TreeControllerResolver.cs index 2c43cbd5dc..62cafbb5dd 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeExtensions.cs +++ b/src/Umbraco.Web/Trees/TreeControllerResolver.cs @@ -14,16 +14,25 @@ using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using Umbraco.Core.Composing; -using Current = Umbraco.Web.Composing.Current; -using ApplicationTree = Umbraco.Core.Models.ApplicationTree; +using ApplicationTree = Umbraco.Web.Models.ContentEditing.ApplicationTree; namespace Umbraco.Web.Trees { - internal static class ApplicationTreeExtensions + public class TreeControllerResolver { - private static readonly ConcurrentDictionary TreeAttributeCache = new ConcurrentDictionary(); + private readonly TreeCollection _trees; + private readonly UmbracoApiControllerTypeCollection _apiControllers; - internal static TreeAttribute GetTreeAttribute(this Type treeControllerType) + public TreeControllerResolver(TreeCollection trees, UmbracoApiControllerTypeCollection apiControllers) + { + _trees = trees; + _apiControllers = apiControllers; + } + + private static readonly ConcurrentDictionary TreeAttributeCache = new ConcurrentDictionary(); + private static readonly ConcurrentDictionary ResolvedControllerTypes = new ConcurrentDictionary(); + + private TreeAttribute GetTreeAttribute(Type treeControllerType) { return TreeAttributeCache.GetOrAdd(treeControllerType, type => { @@ -42,25 +51,41 @@ namespace Umbraco.Web.Trees }); } - internal static TreeAttribute GetTreeAttribute(this ApplicationTree tree) + internal TreeAttribute GetTreeAttribute(ApplicationTree tree) { - return tree.GetRuntimeType().GetTreeAttribute(); + throw new NotImplementedException(); + //return ResolvedControllerTypes.GetOrAdd(tree.Alias, s => + //{ + // var controllerType = _apiControllers + // .OfType() + // .FirstOrDefault(x => x.) + //}); + + //return GetTreeAttribute(tree.GetRuntimeType()); } - internal static Attempt TryGetControllerTree(this ApplicationTree appTree) + private Type GetControllerType(ApplicationTree tree) { - //get reference to all TreeApiControllers - var controllerTrees = Current.UmbracoApiControllerTypes - .Where(TypeHelper.IsTypeAssignableFrom) - .ToArray(); + throw new NotImplementedException(); + } + - //find the one we're looking for - var foundControllerTree = controllerTrees.FirstOrDefault(x => x == appTree.GetRuntimeType()); - if (foundControllerTree == null) - { - return Attempt.Fail(new InstanceNotFoundException("Could not find tree of type " + appTree.Type + " in any loaded DLLs")); - } - return Attempt.Succeed(foundControllerTree); + internal Attempt TryGetControllerTree(ApplicationTree appTree) + { + throw new NotImplementedException(); + + ////get reference to all TreeApiControllers + //var controllerTrees = _apiControllers + // .Where(TypeHelper.IsTypeAssignableFrom) + // .ToArray(); + + ////find the one we're looking for + //var foundControllerTree = controllerTrees.FirstOrDefault(x => x == appTree.GetRuntimeType()); + //if (foundControllerTree == null) + //{ + // return Attempt.Fail(new InstanceNotFoundException("Could not find tree of type " + appTree.Type + " in any loaded DLLs")); + //} + //return Attempt.Succeed(foundControllerTree); } /// @@ -73,9 +98,9 @@ namespace Umbraco.Web.Trees /// /// This ensures that authorization filters are applied to the sub request /// - internal static async Task> TryGetRootNodeFromControllerTree(this ApplicationTree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) + internal async Task> TryGetRootNodeFromControllerTree(ApplicationTree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) { - var foundControllerTreeAttempt = appTree.TryGetControllerTree(); + var foundControllerTreeAttempt = TryGetControllerTree(appTree); if (foundControllerTreeAttempt.Success == false) { return Attempt.Fail(foundControllerTreeAttempt.Exception); @@ -110,12 +135,15 @@ namespace Umbraco.Web.Trees if (WebApiVersionCheck.WebApiVersion >= Version.Parse("5.0.0")) { - //In WebApi2, this is required to be set: - // proxiedControllerContext.RequestContext = controllerContext.RequestContext - // but we need to do this with reflection because of codebase changes between version 4/5 - //NOTE: Use TypeHelper here since the reflection is cached - var controllerContextRequestContext = TypeHelper.GetProperty(controllerContext.GetType(), "RequestContext").GetValue(controllerContext); - TypeHelper.GetProperty(proxiedControllerContext.GetType(), "RequestContext").SetValue(proxiedControllerContext, controllerContextRequestContext); + //fixme - will this 'just' work now? + proxiedControllerContext.RequestContext = controllerContext.RequestContext; + + ////In WebApi2, this is required to be set: + //// proxiedControllerContext.RequestContext = controllerContext.RequestContext + //// but we need to do this with reflection because of codebase changes between version 4/5 + ////NOTE: Use TypeHelper here since the reflection is cached + //var controllerContextRequestContext = TypeHelper.GetProperty(controllerContext.GetType(), "RequestContext").GetValue(controllerContext); + //TypeHelper.GetProperty(proxiedControllerContext.GetType(), "RequestContext").SetValue(proxiedControllerContext, controllerContextRequestContext); } instance.ControllerContext = proxiedControllerContext; @@ -123,13 +151,17 @@ namespace Umbraco.Web.Trees if (WebApiVersionCheck.WebApiVersion >= Version.Parse("5.0.0")) { - //now we can change the request context's route data to be the proxied route data - NOTE: we cannot do this directly above - // because it will detect that the request context is different throw an exception. This is a change in webapi2 and we need to set - // this with reflection due to codebase changes between version 4/5 - // instance.RequestContext.RouteData = proxiedRouteData; - //NOTE: Use TypeHelper here since the reflection is cached - var instanceRequestContext = TypeHelper.GetProperty(typeof(ApiController), "RequestContext").GetValue(instance); - TypeHelper.GetProperty(instanceRequestContext.GetType(), "RouteData").SetValue(instanceRequestContext, proxiedRouteData); + + //fixme - will this 'just' work now? + instance.RequestContext.RouteData = proxiedRouteData; + + ////now we can change the request context's route data to be the proxied route data - NOTE: we cannot do this directly above + //// because it will detect that the request context is different throw an exception. This is a change in webapi2 and we need to set + //// this with reflection due to codebase changes between version 4/5 + //// instance.RequestContext.RouteData = proxiedRouteData; + ////NOTE: Use TypeHelper here since the reflection is cached + //var instanceRequestContext = TypeHelper.GetProperty(typeof(ApiController), "RequestContext").GetValue(instance); + //TypeHelper.GetProperty(instanceRequestContext.GetType(), "RouteData").SetValue(instanceRequestContext, proxiedRouteData); } //invoke auth filters for this sub request @@ -143,13 +175,13 @@ namespace Umbraco.Web.Trees //return the root var node = instance.GetRootNode(formCollection); return node == null - ? Attempt.Fail(new InvalidOperationException("Could not return a root node for tree " + appTree.Type)) + ? Attempt.Fail(new InvalidOperationException("Could not return a root node for tree " + appTree.Alias)) : Attempt.Succeed(node); } - internal static Attempt TryLoadFromControllerTree(this ApplicationTree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) + internal Attempt TryLoadFromControllerTree(ApplicationTree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) { - var foundControllerTreeAttempt = appTree.TryGetControllerTree(); + var foundControllerTreeAttempt = TryGetControllerTree(appTree); if (foundControllerTreeAttempt.Success == false) return Attempt.Fail(foundControllerTreeAttempt.Exception); diff --git a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs index bb9ce3c421..9e632eabc9 100644 --- a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs +++ b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs @@ -29,12 +29,14 @@ namespace Umbraco.Web.UI.Pages var treeAuth = this.GetType().GetCustomAttribute(true); if (treeAuth != null) { - var treeByAlias = Current.Services.ApplicationTreeService - .GetByAlias(treeAuth.TreeAlias); - if (treeByAlias != null) - { - CurrentApp = treeByAlias.ApplicationAlias; - } + throw new NotImplementedException(); + + //var treeByAlias = Current.Services.ApplicationTreeService + // .GetByAlias(treeAuth.TreeAlias); + //if (treeByAlias != null) + //{ + // CurrentApp = treeByAlias.ApplicationAlias; + //} } } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index b0142771d2..f1d15e9ea6 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -166,6 +166,8 @@ + + @@ -181,6 +183,9 @@ + + + @@ -217,6 +222,7 @@ + @@ -585,9 +591,7 @@ - - @@ -890,7 +894,6 @@ - @@ -969,7 +972,7 @@ - + @@ -1236,7 +1239,7 @@ True Reference.map - + diff --git a/src/Umbraco.Web/UrlHelperExtensions.cs b/src/Umbraco.Web/UrlHelperExtensions.cs index 9b1c282aab..0a04539967 100644 --- a/src/Umbraco.Web/UrlHelperExtensions.cs +++ b/src/Umbraco.Web/UrlHelperExtensions.cs @@ -13,7 +13,6 @@ using Umbraco.Web.Composing; using Umbraco.Web.Editors; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; -using Umbraco.Web.WebServices; namespace Umbraco.Web { diff --git a/src/Umbraco.Web/WebApi/Filters/LegacyTreeAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/Filters/LegacyTreeAuthorizeAttribute.cs deleted file mode 100644 index 5d1b90a09d..0000000000 --- a/src/Umbraco.Web/WebApi/Filters/LegacyTreeAuthorizeAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Web.Http; -using System.Web.Http.Controllers; -using Umbraco.Core; -using Umbraco.Web.Composing; - -namespace Umbraco.Web.WebApi.Filters -{ - internal class LegacyTreeAuthorizeAttribute : AuthorizeAttribute - { - protected override bool IsAuthorized(HttpActionContext actionContext) - { - var httpContext = actionContext.Request.TryGetHttpContext(); - if (httpContext) - { - var treeRequest = httpContext.Result.Request.QueryString["treeType"]; - if (treeRequest.IsNullOrWhiteSpace()) return false; - - var tree = Current.Services.ApplicationTreeService.GetByAlias(treeRequest); - if (tree == null) return false; - - return UmbracoContext.Current.Security.CurrentUser != null - && UmbracoContext.Current.Security.UserHasSectionAccess(tree.ApplicationAlias, UmbracoContext.Current.Security.CurrentUser); - } - return false; - - - } - } -} diff --git a/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs index 7318c9d9b8..cc483db416 100644 --- a/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using System.Web.Http.Controllers; using System.Web.Http.Filters; using Umbraco.Core; @@ -40,16 +41,18 @@ namespace Umbraco.Web.WebApi.Filters return true; } - var apps = _treeAliases.Select(x => Current.Services.ApplicationTreeService - .GetByAlias(x)) - .WhereNotNull() - .Select(x => x.ApplicationAlias) - .Distinct() - .ToArray(); + throw new NotImplementedException(); - return Current.UmbracoContext.Security.CurrentUser != null - && apps.Any(app => Current.UmbracoContext.Security.UserHasSectionAccess( - app, Current.UmbracoContext.Security.CurrentUser)); + //var apps = _treeAliases.Select(x => Current.Services.ApplicationTreeService + // .GetByAlias(x)) + // .WhereNotNull() + // .Select(x => x.ApplicationAlias) + // .Distinct() + // .ToArray(); + + //return Current.UmbracoContext.Security.CurrentUser != null + // && apps.Any(app => Current.UmbracoContext.Security.UserHasSectionAccess( + // app, Current.UmbracoContext.Security.CurrentUser)); } } } diff --git a/src/Umbraco.Web/WebApi/UmbracoApiController.cs b/src/Umbraco.Web/WebApi/UmbracoApiController.cs index 3db3610cc2..586160cfa0 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiController.cs @@ -23,8 +23,8 @@ namespace Umbraco.Web.WebApi /// /// Initialize a new instance of the with all its dependencies. /// - protected UmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected UmbracoApiController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } } } diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs index 21b88cc919..106ef60e0b 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs @@ -21,7 +21,6 @@ namespace Umbraco.Web.WebApi [FeatureAuthorize] public abstract class UmbracoApiControllerBase : ApiController { - private readonly IUmbracoContextAccessor _umbracoContextAccessor; private UmbracoHelper _umbracoHelper; // note: all Umbraco controllers have two constructors: one with all dependencies, which should be used, @@ -36,7 +35,7 @@ namespace Umbraco.Web.WebApi protected UmbracoApiControllerBase() : this( Current.Factory.GetInstance(), - Current.Factory.GetInstance(), + Current.Factory.GetInstance().UmbracoContext, Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), @@ -48,15 +47,15 @@ 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, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + protected UmbracoApiControllerBase(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) { GlobalSettings = globalSettings; - _umbracoContextAccessor = umbracoContextAccessor; SqlContext = sqlContext; Services = services; ApplicationCache = applicationCache; Logger = logger; RuntimeState = runtimeState; + UmbracoContext = umbracoContext; } /// @@ -73,8 +72,8 @@ namespace Umbraco.Web.WebApi /// /// Gets the Umbraco context. /// - public virtual UmbracoContext UmbracoContext => _umbracoContextAccessor.UmbracoContext; - + public virtual UmbracoContext UmbracoContext { get; } + /// /// Gets the sql context. /// diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs index cdb1aa2f51..d84ab3fe4a 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs @@ -8,6 +8,8 @@ namespace Umbraco.Web.WebApi // which we are not doing at the moment // we can inherit from BuilderCollectionBase and just be enumerable + //fixme: this should be LazyCollectionBuilderBase ? + public class UmbracoApiControllerTypeCollection : BuilderCollectionBase { public UmbracoApiControllerTypeCollection(IEnumerable items) diff --git a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs index 4ae9c00a47..e8c0a3c674 100644 --- a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs @@ -40,8 +40,8 @@ namespace Umbraco.Web.WebApi /// /// Initializes a new instance of the class with all its dependencies. /// - protected UmbracoAuthorizedApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) - : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected UmbracoAuthorizedApiController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { } /// diff --git a/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs b/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs index 26116820e6..c6d5ba30d9 100644 --- a/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs +++ b/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs @@ -1,61 +1,61 @@ -using System; -using System.Xml; -using System.Xml.Linq; -using Umbraco.Core; -using Umbraco.Core._Legacy.PackageActions; -using Umbraco.Web.Composing; +//using System; +//using System.Xml; +//using System.Xml.Linq; +//using Umbraco.Core; +//using Umbraco.Core._Legacy.PackageActions; +//using Umbraco.Web.Composing; -namespace Umbraco.Web._Legacy.PackageActions -{ - /// - /// This class implements the IPackageAction Interface, used to execute code when packages are installed. - /// All IPackageActions only takes a PackageName and a XmlNode as input, and executes based on the data in the xmlnode. - /// - public class AddApplication : IPackageAction - { +//namespace Umbraco.Web._Legacy.PackageActions +//{ +// /// +// /// This class implements the IPackageAction Interface, used to execute code when packages are installed. +// /// All IPackageActions only takes a PackageName and a XmlNode as input, and executes based on the data in the xmlnode. +// /// +// public class AddApplication : IPackageAction +// { - #region IPackageAction Members +// #region IPackageAction Members - /// - /// Installs a new application in umbraco. - /// - /// Name of the package. - /// The XML data. - /// - /// - /// - /// true if successfull - public bool Execute(string packageName, XElement xmlData) - { - string name = xmlData.AttributeValue("appName"); - string alias = xmlData.AttributeValue("appAlias"); - string icon = xmlData.AttributeValue("appIcon"); +// /// +// /// Installs a new application in umbraco. +// /// +// /// Name of the package. +// /// The XML data. +// /// +// /// +// /// +// /// true if successfull +// public bool Execute(string packageName, XElement xmlData) +// { +// string name = xmlData.AttributeValue("appName"); +// string alias = xmlData.AttributeValue("appAlias"); +// string icon = xmlData.AttributeValue("appIcon"); - Current.Services.SectionService.MakeNew(name, alias, icon); +// Current.Services.SectionService.MakeNew(name, alias, icon); - return true; - } +// return true; +// } - public bool Undo(string packageName, XElement xmlData) - { - string alias = xmlData.AttributeValue("appAlias"); - var section = Current.Services.SectionService.GetByAlias(alias); - if (section != null) - { - Current.Services.SectionService.DeleteSection(section); - } - return true; - } - /// - /// Action alias. - /// - /// - public string Alias() - { - return "addApplication"; - } +// public bool Undo(string packageName, XElement xmlData) +// { +// string alias = xmlData.AttributeValue("appAlias"); +// var section = Current.Services.SectionService.GetByAlias(alias); +// if (section != null) +// { +// Current.Services.SectionService.DeleteSection(section); +// } +// return true; +// } +// /// +// /// Action alias. +// /// +// /// +// public string Alias() +// { +// return "addApplication"; +// } - #endregion +// #endregion - } -} +// } +//} From cfe1b17eecc5a06b56530610d9e04158033e66a4 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 16:40:11 +1100 Subject: [PATCH 26/70] Gets trees and sections loading now in a much more simplified way without any xml, now to cleanup --- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 2 +- src/Umbraco.Web/Composing/Current.cs | 7 + .../Editors/BackOfficeServerVariables.cs | 2 +- src/Umbraco.Web/Editors/EntityController.cs | 6 +- src/Umbraco.Web/Editors/SectionController.cs | 8 +- .../Models/ContentEditing/ApplicationTree.cs | 177 --------------- .../Mvc/SurfaceControllerTypeCollection.cs | 4 +- src/Umbraco.Web/Runtime/WebRuntimeComposer.cs | 13 +- .../Search/SearchableTreeCollection.cs | 8 +- .../Services/IApplicationTreeService.cs | 153 ------------- src/Umbraco.Web/Services/ISectionService.cs | 89 +------- src/Umbraco.Web/Services/ITreeService.cs | 49 +++++ ...plicationTreeService.cs => TreeService.cs} | 40 ++-- src/Umbraco.Web/Trees/ApplicationTree.cs | 69 ++++++ .../Trees/ApplicationTreeController.cs | 173 +++++++++++---- src/Umbraco.Web/Trees/ITree.cs | 31 +++ src/Umbraco.Web/Trees/TreeAttribute.cs | 35 +-- src/Umbraco.Web/Trees/TreeCollection.cs | 21 +- src/Umbraco.Web/Trees/TreeController.cs | 55 +++-- src/Umbraco.Web/Trees/TreeControllerBase.cs | 14 +- .../Trees/TreeControllerResolver.cs | 203 ------------------ .../Trees/UserPermissionsTreeController.cs | 52 ----- src/Umbraco.Web/Umbraco.Web.csproj | 10 +- .../Filters/UmbracoTreeAuthorizeAttribute.cs | 20 +- src/Umbraco.Web/WebApi/MvcVersionCheck.cs | 10 - .../UmbracoApiControllerTypeCollection.cs | 2 - 26 files changed, 425 insertions(+), 828 deletions(-) delete mode 100644 src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs delete mode 100644 src/Umbraco.Web/Services/IApplicationTreeService.cs create mode 100644 src/Umbraco.Web/Services/ITreeService.cs rename src/Umbraco.Web/Services/{ApplicationTreeService.cs => TreeService.cs} (95%) create mode 100644 src/Umbraco.Web/Trees/ApplicationTree.cs create mode 100644 src/Umbraco.Web/Trees/ITree.cs delete mode 100644 src/Umbraco.Web/Trees/TreeControllerResolver.cs delete mode 100644 src/Umbraco.Web/Trees/UserPermissionsTreeController.cs delete mode 100644 src/Umbraco.Web/WebApi/MvcVersionCheck.cs diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index a79531af74..0a0999f2dc 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -342,7 +342,7 @@ namespace Umbraco.Tests.Testing Composition.ComposeServices(); // composition root is doing weird things, fix - Composition.RegisterUnique(); + Composition.RegisterUnique(); Composition.RegisterUnique(); // somehow property editor ends up wanting this diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 1e8f3d17f7..d887720063 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -25,6 +25,7 @@ using Umbraco.Web.HealthCheck; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; +using Umbraco.Web.Services; using Umbraco.Web.WebApi; using CoreCurrent = Umbraco.Core.Composing.Current; @@ -135,6 +136,12 @@ namespace Umbraco.Web.Composing internal static IPublishedSnapshotService PublishedSnapshotService => Factory.GetInstance(); + public static ITreeService TreeService + => Factory.GetInstance(); + + public static ISectionService SectionService + => Factory.GetInstance(); + #endregion #region Web Constants diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index 65ab27d76a..1525dd5808 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -408,7 +408,7 @@ namespace Umbraco.Web.Editors let pluginAttr = p.attributes.OfType().Single() select new Dictionary { - {"alias", treeAttr.Alias}, {"packageFolder", pluginAttr.AreaName} + {"alias", treeAttr.TreeAlias}, {"packageFolder", pluginAttr.AreaName} }).ToArray(); } diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index c8368d11b0..ca1a6a12bb 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -42,10 +42,10 @@ namespace Umbraco.Web.Editors [PluginController("UmbracoApi")] public class EntityController : UmbracoAuthorizedJsonController { - private readonly IApplicationTreeService _treeService; + private readonly ITreeService _treeService; public EntityController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, - IApplicationTreeService treeService) + ITreeService treeService) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _treeService = treeService; @@ -148,7 +148,7 @@ namespace Umbraco.Web.Editors var searchableTreeAttribute = searchableTree.Value.SearchableTree.GetType().GetCustomAttribute(false); - result[tree.GetRootNodeDisplayName(Services.TextService)] = new TreeSearchResult + result[ApplicationTree.GetRootNodeDisplayName(tree, Services.TextService)] = new TreeSearchResult { Results = searchableTree.Value.SearchableTree.Search(query, 200, 0, out var total), TreeAlias = searchableTree.Key, diff --git a/src/Umbraco.Web/Editors/SectionController.cs b/src/Umbraco.Web/Editors/SectionController.cs index 7b484b09b1..d68f062f61 100644 --- a/src/Umbraco.Web/Editors/SectionController.cs +++ b/src/Umbraco.Web/Editors/SectionController.cs @@ -24,16 +24,14 @@ namespace Umbraco.Web.Editors { private readonly Dashboards _dashboards; private readonly ISectionService _sectionService; - private readonly TreeControllerResolver _treeControllerResolver; - private readonly IApplicationTreeService _treeService; + private readonly ITreeService _treeService; public SectionController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, - Dashboards dashboards, ISectionService sectionService, TreeControllerResolver treeControllerResolver, IApplicationTreeService treeService) + Dashboards dashboards, ISectionService sectionService, ITreeService treeService) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { _dashboards = dashboards; _sectionService = sectionService; - _treeControllerResolver = treeControllerResolver; _treeService = treeService; } @@ -45,7 +43,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, UmbracoContext, SqlContext, Services, ApplicationCache, Logger, RuntimeState, _treeControllerResolver, _treeService) + var appTreeController = new ApplicationTreeController(GlobalSettings, UmbracoContext, SqlContext, Services, ApplicationCache, Logger, RuntimeState, _treeService) { ControllerContext = ControllerContext }; diff --git a/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs b/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs deleted file mode 100644 index e9befb0e27..0000000000 --- a/src/Umbraco.Web/Models/ContentEditing/ApplicationTree.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -using System.Diagnostics; -using Umbraco.Core.Services; - -namespace Umbraco.Web.Models.ContentEditing -{ - [DebuggerDisplay("Tree - {Alias} ({ApplicationAlias})")] - public class ApplicationTree - { - //private static readonly ConcurrentDictionary ResolvedTypes = new ConcurrentDictionary(); - - ///// - ///// Initializes a new instance of the class. - ///// - //public ApplicationTree() { } - - ///// - ///// Initializes a new instance of the class. - ///// - ///// if set to true [initialize]. - ///// The sort order. - ///// The application alias. - ///// The tree alias. - ///// The tree title. - ///// The icon closed. - ///// The icon opened. - ///// The tree type. - //public ApplicationTree(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - //{ - // //Initialize = initialize; - // SortOrder = sortOrder; - // ApplicationAlias = applicationAlias; - // Alias = alias; - // Title = title; - // IconClosed = iconClosed; - // IconOpened = iconOpened; - // Type = type; - - //} - - public ApplicationTree(int sortOrder, string applicationAlias, string alias, string title) - { - SortOrder = sortOrder; - ApplicationAlias = applicationAlias; - Alias = alias; - Title = title; - } - - ///// - ///// Gets or sets a value indicating whether this should initialize. - ///// - ///// true if initialize; otherwise, false. - //public bool Initialize { get; set; } - - /// - /// Gets or sets the sort order. - /// - /// The sort order. - public int SortOrder { get; set; } - - /// - /// Gets the application alias. - /// - /// The application alias. - public string ApplicationAlias { get; } - - /// - /// Gets the tree alias. - /// - /// The alias. - public string Alias { get; } - - /// - /// Gets or sets the tree title (fallback if the tree alias isn't localized) - /// - /// The title. - public string Title { get; set; } - - ///// - ///// Gets or sets the icon closed. - ///// - ///// The icon closed. - //public string IconClosed { get; set; } - - ///// - ///// Gets or sets the icon opened. - ///// - ///// The icon opened. - //public string IconOpened { get; set; } - - ///// - ///// Gets or sets the tree type assembly name. - ///// - ///// The type. - //public string Type { get; set; } - - /// - /// Returns the localized root node display name - /// - /// - /// - public string GetRootNodeDisplayName(ILocalizedTextService textService) - { - var label = $"[{Alias}]"; - - // try to look up a the localized tree header matching the tree alias - var localizedLabel = textService.Localize("treeHeaders/" + Alias); - - // if the localizedLabel returns [alias] then return the title if it's defined - if (localizedLabel != null && localizedLabel.Equals(label, StringComparison.InvariantCultureIgnoreCase)) - { - if (string.IsNullOrEmpty(Title) == false) - label = Title; - } - else - { - // the localizedLabel translated into something that's not just [alias], so use the translation - label = localizedLabel; - } - - return label; - } - - //private Type _runtimeType; - - ///// - ///// Returns the CLR type based on it's assembly name stored in the config - ///// - ///// - //public Type GetRuntimeType() - //{ - // return _runtimeType ?? (_runtimeType = System.Type.GetType(Type)); - //} - - ///// - ///// Used to try to get and cache the tree type - ///// - ///// - ///// - //internal static Type TryGetType(string type) - //{ - // try - // { - // return ResolvedTypes.GetOrAdd(type, s => - // { - // var result = System.Type.GetType(type); - // if (result != null) - // { - // return result; - // } - - // //we need to implement a bit of a hack here due to some trees being renamed and backwards compat - // var parts = type.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - // if (parts.Length != 2) - // throw new InvalidOperationException("Could not resolve type"); - // if (parts[1].Trim() != "Umbraco.Web" || parts[0].StartsWith("Umbraco.Web.Trees") == false || parts[0].EndsWith("Controller")) - // throw new InvalidOperationException("Could not resolve type"); - - // //if it's one of our controllers but it's not suffixed with "Controller" then add it and try again - // var tempType = parts[0] + "Controller, Umbraco.Web"; - - // result = System.Type.GetType(tempType); - // if (result != null) - // return result; - - // throw new InvalidOperationException("Could not resolve type"); - // }); - // } - // catch (InvalidOperationException) - // { - // //swallow, this is our own exception, couldn't find the type - // // fixme bad use of exceptions here! - // return null; - // } - //} - } -} diff --git a/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs b/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs index eef6ab1ca2..d9577417cc 100644 --- a/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs +++ b/src/Umbraco.Web/Mvc/SurfaceControllerTypeCollection.cs @@ -7,9 +7,7 @@ namespace Umbraco.Web.Mvc // unless we want to modify the content of the collection // which we are not doing at the moment // we can inherit from BuilderCollectionBase and just be enumerable - - //fixme: this should be LazyCollectionBuilderBase ? - + public class SurfaceControllerTypeCollection : BuilderCollectionBase { public SurfaceControllerTypeCollection(IEnumerable items) diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs index 0ef9adddb7..047d080a88 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs @@ -95,7 +95,7 @@ namespace Umbraco.Web.Runtime // replace some services composition.RegisterUnique(); composition.RegisterUnique(); - composition.RegisterUnique(); + composition.RegisterUnique(); composition.RegisterUnique(); composition.RegisterUnique(factory => ExamineManager.Instance); @@ -125,9 +125,11 @@ namespace Umbraco.Web.Runtime composition.WithCollectionBuilder() .Add(() => composition.TypeLoader.GetTypes()); + //we need to eagerly scan controller types since they will need to be routed var surfaceControllerTypes = new SurfaceControllerTypeCollection(composition.TypeLoader.GetSurfaceControllers()); composition.RegisterUnique(surfaceControllerTypes); + //we need to eagerly scan controller types since they will need to be routed var umbracoApiControllerTypes = new UmbracoApiControllerTypeCollection(composition.TypeLoader.GetUmbracoApiControllers()); composition.RegisterUnique(umbracoApiControllerTypes); @@ -198,8 +200,13 @@ namespace Umbraco.Web.Runtime .Add(() => composition.TypeLoader.GetTypes()); // register back office trees - composition.WithCollectionBuilder() - .Add(() => composition.TypeLoader.GetTypes()); + foreach (var treeControllerType in umbracoApiControllerTypes) + { + var attribute = treeControllerType.GetCustomAttribute(false); + if (attribute == null) continue; + var tree = new ApplicationTree(attribute.SortOrder, attribute.ApplicationAlias, attribute.TreeAlias, attribute.TreeTitle, treeControllerType, attribute.IsSingleNodeTree); + composition.WithCollectionBuilder().AddTree(tree); + } } } } diff --git a/src/Umbraco.Web/Search/SearchableTreeCollection.cs b/src/Umbraco.Web/Search/SearchableTreeCollection.cs index 2b1baa5194..032782b466 100644 --- a/src/Umbraco.Web/Search/SearchableTreeCollection.cs +++ b/src/Umbraco.Web/Search/SearchableTreeCollection.cs @@ -14,13 +14,13 @@ namespace Umbraco.Web.Search { private readonly Dictionary _dictionary; - public SearchableTreeCollection(IEnumerable items, IApplicationTreeService treeService) + public SearchableTreeCollection(IEnumerable items, ITreeService treeService) : base(items) { _dictionary = CreateDictionary(treeService); } - private Dictionary CreateDictionary(IApplicationTreeService treeService) + private Dictionary CreateDictionary(ITreeService treeService) { var appTrees = treeService.GetAll() .OrderBy(x => x.SortOrder) @@ -29,10 +29,10 @@ namespace Umbraco.Web.Search var searchableTrees = this.ToArray(); foreach (var appTree in appTrees) { - var found = searchableTrees.FirstOrDefault(x => x.TreeAlias.InvariantEquals(appTree.Alias)); + var found = searchableTrees.FirstOrDefault(x => x.TreeAlias.InvariantEquals(appTree.TreeAlias)); if (found != null) { - dictionary[found.TreeAlias] = new SearchableApplicationTree(appTree.ApplicationAlias, appTree.Alias, found); + dictionary[found.TreeAlias] = new SearchableApplicationTree(appTree.ApplicationAlias, appTree.TreeAlias, found); } } return dictionary; diff --git a/src/Umbraco.Web/Services/IApplicationTreeService.cs b/src/Umbraco.Web/Services/IApplicationTreeService.cs deleted file mode 100644 index 1fd7bc939a..0000000000 --- a/src/Umbraco.Web/Services/IApplicationTreeService.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core.Models; -using Umbraco.Core.Models.ContentEditing; -using Umbraco.Web.Models.ContentEditing; - -namespace Umbraco.Web.Services -{ - public interface IApplicationTreeService - { - ///// - ///// Creates a new application tree. - ///// - ///// if set to true [initialize]. - ///// The sort order. - ///// The application alias. - ///// The alias. - ///// The title. - ///// The icon closed. - ///// The icon opened. - ///// The type. - //void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type); - - ///// - ///// Saves this instance. - ///// - //void SaveTree(ApplicationTree tree); - - ///// - ///// Deletes this instance. - ///// - //void DeleteTree(ApplicationTree tree); - - /// - /// Gets an ApplicationTree by it's tree alias. - /// - /// The tree alias. - /// An ApplicationTree instance - ApplicationTree GetByAlias(string treeAlias); - - /// - /// Gets all applicationTrees registered in umbraco from the umbracoAppTree table.. - /// - /// Returns a ApplicationTree Array - IEnumerable GetAll(); - - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// Returns a ApplicationTree Array - IEnumerable GetApplicationTrees(string applicationAlias); - - ///// - ///// Gets the application tree for the applcation with the specified alias - ///// - ///// The application alias. - ///// - ///// Returns a ApplicationTree Array - //IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized); - - /// - /// Gets the grouped application trees for the application with the specified alias - /// - /// - /// - IDictionary> GetGroupedApplicationTrees(string applicationAlias); - } - - /// - /// Purely used to allow a service context to create the default services - /// - internal class EmptyApplicationTreeService : IApplicationTreeService - { - ///// - ///// Creates a new application tree. - ///// - ///// if set to true [initialize]. - ///// The sort order. - ///// The application alias. - ///// The alias. - ///// The title. - ///// The icon closed. - ///// The icon opened. - ///// The type. - //public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - //{ - // throw new System.NotImplementedException(); - //} - - ///// - ///// Saves this instance. - ///// - //public void SaveTree(ApplicationTree tree) - //{ - // throw new System.NotImplementedException(); - //} - - ///// - ///// Deletes this instance. - ///// - //public void DeleteTree(ApplicationTree tree) - //{ - // throw new System.NotImplementedException(); - //} - - /// - /// Gets an ApplicationTree by it's tree alias. - /// - /// The tree alias. - /// An ApplicationTree instance - public ApplicationTree GetByAlias(string treeAlias) - { - throw new System.NotImplementedException(); - } - - /// - /// Gets all applicationTrees registered in umbraco from the umbracoAppTree table.. - /// - /// Returns a ApplicationTree Array - public IEnumerable GetAll() - { - throw new System.NotImplementedException(); - } - - public IDictionary> GetGroupedApplicationTrees(string applicationAlias) - { - throw new System.NotImplementedException(); - } - - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// Returns a ApplicationTree Array - public IEnumerable GetApplicationTrees(string applicationAlias) - { - throw new System.NotImplementedException(); - } - - /// - /// Gets the application tree for the applcation with the specified alias - /// - /// The application alias. - /// - /// Returns a ApplicationTree Array - public IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized) - { - throw new System.NotImplementedException(); - } - } -} diff --git a/src/Umbraco.Web/Services/ISectionService.cs b/src/Umbraco.Web/Services/ISectionService.cs index 560805634f..c325020cf1 100644 --- a/src/Umbraco.Web/Services/ISectionService.cs +++ b/src/Umbraco.Web/Services/ISectionService.cs @@ -25,92 +25,7 @@ namespace Umbraco.Web.Services /// The application alias. /// IBackOfficeSection GetByAlias(string appAlias); - - ///// - ///// Creates a new applcation if no application with the specified alias is found. - ///// - ///// The application name. - ///// The application alias. - ///// The application icon, which has to be located in umbraco/images/tray folder. - //void MakeNew(string name, string alias, string icon); - - ///// - ///// Makes the new. - ///// - ///// The name. - ///// The alias. - ///// The icon. - ///// The sort order. - //void MakeNew(string name, string alias, string icon, int sortOrder); - - ///// - ///// Deletes the section - ///// - //void DeleteSection(Section section); - } - - /// - /// Purely used to allow a service context to create the default services - /// - internal class EmptySectionService : ISectionService - { - /// - /// The cache storage for all applications - /// - public IEnumerable GetSections() - { - throw new System.NotImplementedException(); - } - - /// - /// Get the user's allowed sections - /// - /// - /// - public IEnumerable GetAllowedSections(int userId) - { - throw new System.NotImplementedException(); - } - - /// - /// Gets the application by its alias. - /// - /// The application alias. - /// - public IBackOfficeSection GetByAlias(string appAlias) - { - throw new System.NotImplementedException(); - } - - ///// - ///// Creates a new applcation if no application with the specified alias is found. - ///// - ///// The application name. - ///// The application alias. - ///// The application icon, which has to be located in umbraco/images/tray folder. - //public void MakeNew(string name, string alias, string icon) - //{ - // throw new System.NotImplementedException(); - //} - - ///// - ///// Makes the new. - ///// - ///// The name. - ///// The alias. - ///// The icon. - ///// The sort order. - //public void MakeNew(string name, string alias, string icon, int sortOrder) - //{ - // throw new System.NotImplementedException(); - //} - - ///// - ///// Deletes the section - ///// - //public void DeleteSection(IBackOfficeSection section) - //{ - // throw new System.NotImplementedException(); - //} + } + } diff --git a/src/Umbraco.Web/Services/ITreeService.cs b/src/Umbraco.Web/Services/ITreeService.cs new file mode 100644 index 0000000000..ce734cc5e4 --- /dev/null +++ b/src/Umbraco.Web/Services/ITreeService.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Umbraco.Core.Models; +using Umbraco.Core.Models.ContentEditing; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Trees; + +namespace Umbraco.Web.Services +{ + public interface ITreeService + { + /// + /// Gets an ApplicationTree by it's tree alias. + /// + /// The tree alias. + /// An ApplicationTree instance + ApplicationTree GetByAlias(string treeAlias); + + /// + /// Gets all applicationTrees registered in umbraco from the umbracoAppTree table.. + /// + /// Returns a ApplicationTree Array + IEnumerable GetAll(); + + /// + /// Gets the application tree for the applcation with the specified alias + /// + /// The application alias. + /// Returns a ApplicationTree Array + IEnumerable GetApplicationTrees(string applicationAlias); + + ///// + ///// Gets the application tree for the applcation with the specified alias + ///// + ///// The application alias. + ///// + ///// Returns a ApplicationTree Array + //IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized); + + /// + /// Gets the grouped application trees for the application with the specified alias + /// + /// + /// + IDictionary> GetGroupedApplicationTrees(string applicationAlias); + } + +} diff --git a/src/Umbraco.Web/Services/ApplicationTreeService.cs b/src/Umbraco.Web/Services/TreeService.cs similarity index 95% rename from src/Umbraco.Web/Services/ApplicationTreeService.cs rename to src/Umbraco.Web/Services/TreeService.cs index 72b26e26d3..cf010f1480 100644 --- a/src/Umbraco.Web/Services/ApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/TreeService.cs @@ -18,18 +18,18 @@ using Umbraco.Web.Trees; namespace Umbraco.Web.Services { - internal class ApplicationTreeService : IApplicationTreeService + internal class TreeService : ITreeService { private readonly ILogger _logger; private readonly TreeCollection _treeCollection; private static readonly object Locker = new object(); private readonly Lazy>> _groupedTrees; - public ApplicationTreeService(ILogger logger, TreeCollection treeCollection) + public TreeService(ILogger logger, TreeCollection treeCollection) { _logger = logger; _treeCollection = treeCollection; - //_groupedTrees = new Lazy>>(InitGroupedTrees); + _groupedTrees = new Lazy>>(InitGroupedTrees); } ///// @@ -233,7 +233,7 @@ namespace Umbraco.Web.Services //} /// - public ApplicationTree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.Alias == treeAlias); + public ApplicationTree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.TreeAlias == treeAlias); /// public IEnumerable GetAll() => _treeCollection; @@ -273,7 +273,7 @@ namespace Umbraco.Web.Services { foreach(var treeAliasInGroup in treeGroup) { - if (tree.Alias == treeAliasInGroup) + if (tree.TreeAlias == treeAliasInGroup) { if (resultGroup == null) resultGroup = new List(); resultGroup.Add(tree); @@ -286,21 +286,21 @@ namespace Umbraco.Web.Services return result; } - ///// - ///// Creates a group of all tree groups and their tree aliases - ///// - ///// - ///// - ///// Used to initialize the field - ///// - //private IReadOnlyCollection> InitGroupedTrees() - //{ - // var result = GetAll() - // .Select(x => (treeAlias: x.Alias, treeGroup: x.GetRuntimeType().GetCustomAttribute(false)?.TreeGroup)) - // .GroupBy(x => x.treeGroup, x => x.treeAlias) - // .ToList(); - // return result; - //} + /// + /// Creates a group of all tree groups and their tree aliases + /// + /// + /// + /// Used to initialize the field + /// + private IReadOnlyCollection> InitGroupedTrees() + { + var result = GetAll() + .Select(x => (treeAlias: x.TreeAlias, treeGroup: x.TreeControllerType.GetCustomAttribute(false)?.TreeGroup)) + .GroupBy(x => x.treeGroup, x => x.treeAlias) + .ToList(); + return result; + } ///// ///// Loads in the xml structure from disk if one is found, otherwise loads in an empty xml structure, calls the diff --git a/src/Umbraco.Web/Trees/ApplicationTree.cs b/src/Umbraco.Web/Trees/ApplicationTree.cs new file mode 100644 index 0000000000..5ed9847be3 --- /dev/null +++ b/src/Umbraco.Web/Trees/ApplicationTree.cs @@ -0,0 +1,69 @@ +using System; +using System.Diagnostics; +using Umbraco.Core.Services; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + [DebuggerDisplay("Tree - {TreeAlias} ({ApplicationAlias})")] + public class ApplicationTree : ITree + { + public ApplicationTree(int sortOrder, string applicationAlias, string alias, string title, Type treeControllerType, bool isSingleNodeTree) + { + SortOrder = sortOrder; + ApplicationAlias = applicationAlias; + TreeAlias = alias; + TreeTitle = title; + TreeControllerType = treeControllerType; + IsSingleNodeTree = isSingleNodeTree; + } + + /// + /// + /// Gets or sets the sort order. + /// + public int SortOrder { get; set; } + + /// + /// Gets the application alias. + /// + public string ApplicationAlias { get; set; } + + /// + public string TreeAlias { get; } + + /// + /// + /// Gets or sets the tree title (fallback if the tree alias isn't localized) + /// + /// The title. + public string TreeTitle { get; set; } + + public bool IsSingleNodeTree { get; } + + public Type TreeControllerType { get; } + + public static string GetRootNodeDisplayName(ITree tree, ILocalizedTextService textService) + { + var label = $"[{tree.TreeAlias}]"; + + // try to look up a the localized tree header matching the tree alias + var localizedLabel = textService.Localize("treeHeaders/" + tree.TreeAlias); + + // if the localizedLabel returns [alias] then return the title if it's defined + if (localizedLabel != null && localizedLabel.Equals(label, StringComparison.InvariantCultureIgnoreCase)) + { + if (string.IsNullOrEmpty(tree.TreeTitle) == false) + label = tree.TreeTitle; + } + else + { + // the localizedLabel translated into something that's not just [alias], so use the translation + label = localizedLabel; + } + + return label; + } + + } +} diff --git a/src/Umbraco.Web/Trees/ApplicationTreeController.cs b/src/Umbraco.Web/Trees/ApplicationTreeController.cs index 7e7c77d607..0e405ca3f3 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web/Trees/ApplicationTreeController.cs @@ -3,9 +3,13 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; +using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Http; +using System.Web.Http.Controllers; +using System.Web.Http.Routing; +using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; @@ -24,19 +28,20 @@ using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Trees { + /// + /// Used to return tree root nodes + /// [AngularJsonOnlyConfiguration] [PluginController("UmbracoTrees")] public class ApplicationTreeController : UmbracoAuthorizedApiController { - private readonly TreeControllerResolver _treeControllerResolver; - private readonly IApplicationTreeService _treeService; + private readonly ITreeService _treeService; public ApplicationTreeController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, - IRuntimeState runtimeState, TreeControllerResolver treeControllerResolver, IApplicationTreeService treeService) + IRuntimeState runtimeState, ITreeService treeService) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { - _treeControllerResolver = treeControllerResolver; _treeService = treeService; } @@ -46,10 +51,9 @@ namespace Umbraco.Web.Trees /// The application to load tree for /// An optional single tree alias, if specified will only load the single tree for the request app /// - /// An optional bool (defaults to true), if set to false it will also load uninitialized trees /// [HttpQueryStringFilter("queryStrings")] - public async Task GetApplicationTrees(string application, string tree, FormDataCollection queryStrings/*, bool onlyInitialized = true*/) + public async Task GetApplicationTrees(string application, string tree, FormDataCollection queryStrings) { application = application.CleanForXss(); @@ -62,7 +66,7 @@ namespace Umbraco.Web.Trees if (string.IsNullOrEmpty(tree) == false || allTrees.Count == 1) { var apptree = !tree.IsNullOrWhiteSpace() - ? allTrees.FirstOrDefault(x => x.Alias == tree) + ? allTrees.FirstOrDefault(x => x.TreeAlias == tree) : allTrees.FirstOrDefault(); if (apptree == null) throw new HttpResponseException(HttpStatusCode.NotFound); @@ -153,15 +157,15 @@ namespace Umbraco.Web.Trees /// /// Get the root node for an application with multiple trees /// - /// + /// /// /// - private async Task GetRootForMultipleAppTree(ApplicationTree configTree, FormDataCollection queryStrings) + private async Task GetRootForMultipleAppTree(ApplicationTree tree, FormDataCollection queryStrings) { - if (configTree == null) throw new ArgumentNullException(nameof(configTree)); + if (tree == null) throw new ArgumentNullException(nameof(tree)); try { - var byControllerAttempt = await _treeControllerResolver.TryGetRootNodeFromControllerTree(configTree, queryStrings, ControllerContext); + var byControllerAttempt = await TryGetRootNodeFromControllerTree(tree, queryStrings, ControllerContext); if (byControllerAttempt.Success) { return byControllerAttempt.Result; @@ -174,54 +178,133 @@ namespace Umbraco.Web.Trees return null; } - throw new ApplicationException("Could not get root node for tree type " + configTree.Alias); + throw new ApplicationException("Could not get root node for tree type " + tree.TreeAlias); } /// /// Get the root node for an application with one tree /// - /// + /// /// /// /// /// - private async Task GetRootForSingleAppTree(ApplicationTree configTree, string id, FormDataCollection queryStrings, string application) + private async Task GetRootForSingleAppTree(ApplicationTree tree, string id, FormDataCollection queryStrings, string application) { var rootId = Constants.System.Root.ToString(CultureInfo.InvariantCulture); - if (configTree == null) throw new ArgumentNullException(nameof(configTree)); - var byControllerAttempt = _treeControllerResolver.TryLoadFromControllerTree(configTree, id, queryStrings, ControllerContext); - if (byControllerAttempt.Success) + if (tree == null) throw new ArgumentNullException(nameof(tree)); + var byControllerAttempt = TryLoadFromControllerTree(tree, id, queryStrings, ControllerContext); + if (!byControllerAttempt.Success) + throw new ApplicationException("Could not render a tree for type " + tree.TreeAlias); + + var rootNode = await TryGetRootNodeFromControllerTree(tree, queryStrings, ControllerContext); + if (rootNode.Success == false) { - var rootNode = await _treeControllerResolver.TryGetRootNodeFromControllerTree(configTree, queryStrings, ControllerContext); - if (rootNode.Success == false) - { - //This should really never happen if we've successfully got the children above. - throw new InvalidOperationException("Could not create root node for tree " + configTree.Alias); - } - - var treeAttribute = _treeControllerResolver.GetTreeAttribute(configTree); - - var sectionRoot = TreeRootNode.CreateSingleTreeRoot( - rootId, - rootNode.Result.ChildNodesUrl, - rootNode.Result.MenuUrl, - rootNode.Result.Name, - byControllerAttempt.Result, - treeAttribute.IsSingleNodeTree); - - //assign the route path based on the root node, this means it will route there when the section is navigated to - //and no dashboards will be available for this section - sectionRoot.RoutePath = rootNode.Result.RoutePath; - - foreach (var d in rootNode.Result.AdditionalData) - { - sectionRoot.AdditionalData[d.Key] = d.Value; - } - return sectionRoot; - + //This should really never happen if we've successfully got the children above. + throw new InvalidOperationException("Could not create root node for tree " + tree.TreeAlias); } - throw new ApplicationException("Could not render a tree for type " + configTree.Alias); + var sectionRoot = TreeRootNode.CreateSingleTreeRoot( + rootId, + rootNode.Result.ChildNodesUrl, + rootNode.Result.MenuUrl, + rootNode.Result.Name, + byControllerAttempt.Result, + tree.IsSingleNodeTree); + + //assign the route path based on the root node, this means it will route there when the section is navigated to + //and no dashboards will be available for this section + sectionRoot.RoutePath = rootNode.Result.RoutePath; + + foreach (var d in rootNode.Result.AdditionalData) + { + sectionRoot.AdditionalData[d.Key] = d.Value; + } + return sectionRoot; + } + + /// + /// Proxies a request to the destination tree controller to get it's root tree node + /// + /// + /// + /// + /// + /// + /// This ensures that authorization filters are applied to the sub request + /// + private async Task> TryGetRootNodeFromControllerTree(ApplicationTree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) + { + //instantiate it, since we are proxying, we need to setup the instance with our current context + var instance = (TreeController)DependencyResolver.Current.GetService(appTree.TreeControllerType); + + //NOTE: This is all required in order to execute the auth-filters for the sub request, we + // need to "trick" web-api into thinking that it is actually executing the proxied controller. + + var urlHelper = controllerContext.Request.GetUrlHelper(); + //create the proxied URL for the controller action + var proxiedUrl = controllerContext.Request.RequestUri.GetLeftPart(UriPartial.Authority) + + urlHelper.GetUmbracoApiService("GetRootNode", instance.GetType()); + //add the query strings to it + proxiedUrl += "?" + formCollection.ToQueryString(); + //create proxy route data specifying the action / controller to execute + var proxiedRouteData = new HttpRouteData( + controllerContext.RouteData.Route, + new HttpRouteValueDictionary(new { action = "GetRootNode", controller = ControllerExtensions.GetControllerName(instance.GetType()) })); + + //create a proxied controller context + var proxiedControllerContext = new HttpControllerContext( + controllerContext.Configuration, + proxiedRouteData, + new HttpRequestMessage(HttpMethod.Get, proxiedUrl)) + { + ControllerDescriptor = new HttpControllerDescriptor(controllerContext.ControllerDescriptor.Configuration, ControllerExtensions.GetControllerName(instance.GetType()), instance.GetType()), + RequestContext = controllerContext.RequestContext + }; + + instance.ControllerContext = proxiedControllerContext; + instance.Request = controllerContext.Request; + instance.RequestContext.RouteData = proxiedRouteData; + + //invoke auth filters for this sub request + var result = await instance.ControllerContext.InvokeAuthorizationFiltersForRequest(); + //if a result is returned it means they are unauthorized, just throw the response. + if (result != null) + { + throw new HttpResponseException(result); + } + + //return the root + var node = instance.GetRootNode(formCollection); + return node == null + ? Attempt.Fail(new InvalidOperationException("Could not return a root node for tree " + appTree.TreeAlias)) + : Attempt.Succeed(node); + } + + /// + /// Proxies a request to the destination tree controller to get it's tree node collection + /// + /// + /// + /// + /// + /// + private Attempt TryLoadFromControllerTree(ApplicationTree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) + { + // instantiate it, since we are proxying, we need to setup the instance with our current context + var instance = (TreeController)DependencyResolver.Current.GetService(appTree.TreeControllerType); + if (instance == null) + throw new Exception("Failed to create tree " + appTree.TreeControllerType + "."); + + //TODO: Shouldn't we be applying the same proxying logic as above so that filters work? seems like an oversight + + instance.ControllerContext = controllerContext; + instance.Request = controllerContext.Request; + + // return its data + return Attempt.Succeed(instance.GetNodes(id, formCollection)); + } + } } diff --git a/src/Umbraco.Web/Trees/ITree.cs b/src/Umbraco.Web/Trees/ITree.cs new file mode 100644 index 0000000000..40be7338b0 --- /dev/null +++ b/src/Umbraco.Web/Trees/ITree.cs @@ -0,0 +1,31 @@ +namespace Umbraco.Web.Trees +{ + public interface ITree + { + /// + /// Gets or sets the sort order. + /// + /// The sort order. + int SortOrder { get; } + + /// + /// Gets the section alias. + /// + string ApplicationAlias { get; } + + /// + /// Gets the tree alias. + /// + string TreeAlias { get; } + + /// + /// Gets or sets the tree title (fallback if the tree alias isn't localized) + /// + string TreeTitle { get; } + + /// + /// Flag to define if this tree is a single node tree (will never contain child nodes, full screen app) + /// + bool IsSingleNodeTree { get; } + } +} diff --git a/src/Umbraco.Web/Trees/TreeAttribute.cs b/src/Umbraco.Web/Trees/TreeAttribute.cs index 1cf23c549f..dd63f8c172 100644 --- a/src/Umbraco.Web/Trees/TreeAttribute.cs +++ b/src/Umbraco.Web/Trees/TreeAttribute.cs @@ -1,4 +1,5 @@ using System; +using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Trees { @@ -6,15 +7,15 @@ namespace Umbraco.Web.Trees /// Identifies an application tree /// [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class TreeAttribute : Attribute + public class TreeAttribute : Attribute, ITree { /// /// Initializes a new instance of the class. /// /// The app alias. - /// The alias. + /// public TreeAttribute(string appAlias, - string alias) : this(appAlias, alias, null) + string treeAlias) : this(appAlias, treeAlias, null) { } @@ -22,16 +23,16 @@ namespace Umbraco.Web.Trees /// Initializes a new instance of the class. /// /// The app alias. - /// The alias. - /// The title. + /// + /// /// The icon closed. /// The icon open. /// if set to true [initialize]. /// The sort order. /// Flag to define if this tree is a single node tree (will never contain child nodes, full screen app) public TreeAttribute(string appAlias, - string alias, - string title, + string treeAlias, + string treeTitle, string iconClosed = "icon-folder", string iconOpen = "icon-folder-open", bool initialize = true, @@ -39,8 +40,8 @@ namespace Umbraco.Web.Trees bool isSingleNodeTree = false) { ApplicationAlias = appAlias; - Alias = alias; - Title = title; + TreeAlias = treeAlias; + TreeTitle = treeTitle; IconClosed = iconClosed; IconOpen = iconOpen; Initialize = initialize; @@ -48,17 +49,17 @@ namespace Umbraco.Web.Trees IsSingleNodeTree = isSingleNodeTree; } - public string ApplicationAlias { get; private set; } - public string Alias { get; private set; } - public string Title { get; private set; } - public string IconClosed { get; private set; } - public string IconOpen { get; private set; } - public bool Initialize { get; private set; } - public int SortOrder { get; private set; } + public string ApplicationAlias { get; } + public string TreeAlias { get; } + public string TreeTitle { get; } + public string IconClosed { get; } + public string IconOpen { get; } + public bool Initialize { get; } + public int SortOrder { get; } /// /// Flag to define if this tree is a single node tree (will never contain child nodes, full screen app) /// - public bool IsSingleNodeTree { get; private set; } + public bool IsSingleNodeTree { get; } } } diff --git a/src/Umbraco.Web/Trees/TreeCollection.cs b/src/Umbraco.Web/Trees/TreeCollection.cs index 8f913fb2d7..c7b60dea16 100644 --- a/src/Umbraco.Web/Trees/TreeCollection.cs +++ b/src/Umbraco.Web/Trees/TreeCollection.cs @@ -21,7 +21,26 @@ namespace Umbraco.Web.Trees { protected override TreeCollectionBuilder This => this; - //TODO: can we allow for re-ordering OOTB without exposing other methods? + private readonly List _instances = new List(); + + public void AddTree(ApplicationTree tree) + { + _instances.Add(tree); + } + + protected override IEnumerable CreateItems(IFactory factory) + { + return _instances; + + //var items = base.CreateItems(factory).ToList(); + //throw new NotImplementedException(); + ////validate the items, no actions should exist that do not either expose notifications or permissions + //var invalidItems = items.Where(x => !x.CanBePermissionAssigned && !x.ShowInNotifier).ToList(); + //if (invalidItems.Count == 0) return items; + + //var invalidActions = string.Join(", ", invalidItems.Select(x => "'" + x.Alias + "'")); + //throw new InvalidOperationException($"Invalid actions {invalidActions}'. All {typeof(IAction)} implementations must be true for either {nameof(IAction.CanBePermissionAssigned)} or {nameof(IAction.ShowInNotifier)}."); + } } } diff --git a/src/Umbraco.Web/Trees/TreeController.cs b/src/Umbraco.Web/Trees/TreeController.cs index 102671ec29..63e8f5aad5 100644 --- a/src/Umbraco.Web/Trees/TreeController.cs +++ b/src/Umbraco.Web/Trees/TreeController.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Concurrent; +using System.Linq; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; @@ -14,10 +16,10 @@ namespace Umbraco.Web.Trees public abstract class TreeController : TreeControllerBase { private TreeAttribute _attribute; - private string _rootNodeDisplayName; protected TreeController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContext, sqlContext, services, applicationCache, logger, runtimeState) { + Initialize(); } protected TreeController() @@ -25,29 +27,42 @@ namespace Umbraco.Web.Trees Initialize(); } - /// - /// The name to display on the root node - /// - public override string RootNodeDisplayName - { - get - { - throw new NotImplementedException(); - //return _rootNodeDisplayName - // ?? (_rootNodeDisplayName = Services.ApplicationTreeService.GetByAlias(_attribute.Alias) - // ?.GetRootNodeDisplayName(Services.TextService)); - } - } + /// + public override string RootNodeDisplayName => ApplicationTree.GetRootNodeDisplayName(this, Services.TextService); - /// - /// Gets the current tree alias from the attribute assigned to it. - /// - public override string TreeAlias => _attribute.Alias; + /// + public override string TreeAlias => _attribute.TreeAlias; + /// + public override string TreeTitle => _attribute.TreeTitle; + /// + public override string ApplicationAlias => _attribute.ApplicationAlias; + /// + public override int SortOrder => _attribute.SortOrder; + /// + public override bool IsSingleNodeTree => _attribute.IsSingleNodeTree; private void Initialize() { - throw new NotImplementedException(); - //_attribute = GetType().GetTreeAttribute(); + _attribute = GetTreeAttribute(); + } + + private static readonly ConcurrentDictionary TreeAttributeCache = new ConcurrentDictionary(); + + private TreeAttribute GetTreeAttribute() + { + return TreeAttributeCache.GetOrAdd(GetType(), type => + { + //Locate the tree attribute + var treeAttributes = type + .GetCustomAttributes(false) + .ToArray(); + + if (treeAttributes.Length == 0) + throw new InvalidOperationException("The Tree controller is missing the " + typeof(TreeAttribute).FullName + " attribute"); + + //assign the properties of this object to those of the metadata attribute + return treeAttributes[0]; + }); } } } diff --git a/src/Umbraco.Web/Trees/TreeControllerBase.cs b/src/Umbraco.Web/Trees/TreeControllerBase.cs index c00d6053c8..7a027033fc 100644 --- a/src/Umbraco.Web/Trees/TreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/TreeControllerBase.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Trees /// Developers should generally inherit from TreeController. /// [AngularJsonOnlyConfiguration] - public abstract class TreeControllerBase : UmbracoAuthorizedApiController + public abstract class TreeControllerBase : UmbracoAuthorizedApiController, ITree { protected TreeControllerBase() { @@ -62,10 +62,16 @@ namespace Umbraco.Web.Trees /// public abstract string RootNodeDisplayName { get; } - /// - /// Gets the current tree alias from the attribute assigned to it. - /// + /// public abstract string TreeAlias { get; } + /// + public abstract string TreeTitle { get; } + /// + public abstract string ApplicationAlias { get; } + /// + public abstract int SortOrder { get; } + /// + public abstract bool IsSingleNodeTree { get; } /// /// Returns the root node for the tree diff --git a/src/Umbraco.Web/Trees/TreeControllerResolver.cs b/src/Umbraco.Web/Trees/TreeControllerResolver.cs deleted file mode 100644 index 62cafbb5dd..0000000000 --- a/src/Umbraco.Web/Trees/TreeControllerResolver.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Linq; -using System.Management.Instrumentation; -using System.Net.Http; -using System.Net.Http.Formatting; -using System.Threading.Tasks; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Routing; -using System.Web.Mvc; -using Umbraco.Core; -using Umbraco.Web.Models.Trees; -using Umbraco.Web.Mvc; -using Umbraco.Web.WebApi; -using Umbraco.Core.Composing; -using ApplicationTree = Umbraco.Web.Models.ContentEditing.ApplicationTree; - -namespace Umbraco.Web.Trees -{ - public class TreeControllerResolver - { - private readonly TreeCollection _trees; - private readonly UmbracoApiControllerTypeCollection _apiControllers; - - public TreeControllerResolver(TreeCollection trees, UmbracoApiControllerTypeCollection apiControllers) - { - _trees = trees; - _apiControllers = apiControllers; - } - - private static readonly ConcurrentDictionary TreeAttributeCache = new ConcurrentDictionary(); - private static readonly ConcurrentDictionary ResolvedControllerTypes = new ConcurrentDictionary(); - - private TreeAttribute GetTreeAttribute(Type treeControllerType) - { - return TreeAttributeCache.GetOrAdd(treeControllerType, type => - { - //Locate the tree attribute - var treeAttributes = type - .GetCustomAttributes(false) - .ToArray(); - - if (treeAttributes.Length == 0) - { - throw new InvalidOperationException("The Tree controller is missing the " + typeof(TreeAttribute).FullName + " attribute"); - } - - //assign the properties of this object to those of the metadata attribute - return treeAttributes[0]; - }); - } - - internal TreeAttribute GetTreeAttribute(ApplicationTree tree) - { - throw new NotImplementedException(); - //return ResolvedControllerTypes.GetOrAdd(tree.Alias, s => - //{ - // var controllerType = _apiControllers - // .OfType() - // .FirstOrDefault(x => x.) - //}); - - //return GetTreeAttribute(tree.GetRuntimeType()); - } - - private Type GetControllerType(ApplicationTree tree) - { - throw new NotImplementedException(); - } - - - internal Attempt TryGetControllerTree(ApplicationTree appTree) - { - throw new NotImplementedException(); - - ////get reference to all TreeApiControllers - //var controllerTrees = _apiControllers - // .Where(TypeHelper.IsTypeAssignableFrom) - // .ToArray(); - - ////find the one we're looking for - //var foundControllerTree = controllerTrees.FirstOrDefault(x => x == appTree.GetRuntimeType()); - //if (foundControllerTree == null) - //{ - // return Attempt.Fail(new InstanceNotFoundException("Could not find tree of type " + appTree.Type + " in any loaded DLLs")); - //} - //return Attempt.Succeed(foundControllerTree); - } - - /// - /// This will go and get the root node from a controller tree by executing the tree's GetRootNode method - /// - /// - /// - /// - /// - /// - /// This ensures that authorization filters are applied to the sub request - /// - internal async Task> TryGetRootNodeFromControllerTree(ApplicationTree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) - { - var foundControllerTreeAttempt = TryGetControllerTree(appTree); - if (foundControllerTreeAttempt.Success == false) - { - return Attempt.Fail(foundControllerTreeAttempt.Exception); - } - - var foundControllerTree = foundControllerTreeAttempt.Result; - //instantiate it, since we are proxying, we need to setup the instance with our current context - var instance = (TreeController)DependencyResolver.Current.GetService(foundControllerTree); - - //NOTE: This is all required in order to execute the auth-filters for the sub request, we - // need to "trick" web-api into thinking that it is actually executing the proxied controller. - - var urlHelper = controllerContext.Request.GetUrlHelper(); - //create the proxied URL for the controller action - var proxiedUrl = controllerContext.Request.RequestUri.GetLeftPart(UriPartial.Authority) + - urlHelper.GetUmbracoApiService("GetRootNode", instance.GetType()); - //add the query strings to it - proxiedUrl += "?" + formCollection.ToQueryString(); - //create proxy route data specifying the action / controller to execute - var proxiedRouteData = new HttpRouteData( - controllerContext.RouteData.Route, - new HttpRouteValueDictionary(new {action = "GetRootNode", controller = ControllerExtensions.GetControllerName(instance.GetType())})); - - //create a proxied controller context - var proxiedControllerContext = new HttpControllerContext( - controllerContext.Configuration, - proxiedRouteData, - new HttpRequestMessage(HttpMethod.Get, proxiedUrl)) - { - ControllerDescriptor = new HttpControllerDescriptor(controllerContext.ControllerDescriptor.Configuration, ControllerExtensions.GetControllerName(instance.GetType()), instance.GetType()) - }; - - if (WebApiVersionCheck.WebApiVersion >= Version.Parse("5.0.0")) - { - //fixme - will this 'just' work now? - proxiedControllerContext.RequestContext = controllerContext.RequestContext; - - ////In WebApi2, this is required to be set: - //// proxiedControllerContext.RequestContext = controllerContext.RequestContext - //// but we need to do this with reflection because of codebase changes between version 4/5 - ////NOTE: Use TypeHelper here since the reflection is cached - //var controllerContextRequestContext = TypeHelper.GetProperty(controllerContext.GetType(), "RequestContext").GetValue(controllerContext); - //TypeHelper.GetProperty(proxiedControllerContext.GetType(), "RequestContext").SetValue(proxiedControllerContext, controllerContextRequestContext); - } - - instance.ControllerContext = proxiedControllerContext; - instance.Request = controllerContext.Request; - - if (WebApiVersionCheck.WebApiVersion >= Version.Parse("5.0.0")) - { - - //fixme - will this 'just' work now? - instance.RequestContext.RouteData = proxiedRouteData; - - ////now we can change the request context's route data to be the proxied route data - NOTE: we cannot do this directly above - //// because it will detect that the request context is different throw an exception. This is a change in webapi2 and we need to set - //// this with reflection due to codebase changes between version 4/5 - //// instance.RequestContext.RouteData = proxiedRouteData; - ////NOTE: Use TypeHelper here since the reflection is cached - //var instanceRequestContext = TypeHelper.GetProperty(typeof(ApiController), "RequestContext").GetValue(instance); - //TypeHelper.GetProperty(instanceRequestContext.GetType(), "RouteData").SetValue(instanceRequestContext, proxiedRouteData); - } - - //invoke auth filters for this sub request - var result = await instance.ControllerContext.InvokeAuthorizationFiltersForRequest(); - //if a result is returned it means they are unauthorized, just throw the response. - if (result != null) - { - throw new HttpResponseException(result); - } - - //return the root - var node = instance.GetRootNode(formCollection); - return node == null - ? Attempt.Fail(new InvalidOperationException("Could not return a root node for tree " + appTree.Alias)) - : Attempt.Succeed(node); - } - - internal Attempt TryLoadFromControllerTree(ApplicationTree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) - { - var foundControllerTreeAttempt = TryGetControllerTree(appTree); - if (foundControllerTreeAttempt.Success == false) - return Attempt.Fail(foundControllerTreeAttempt.Exception); - - // instantiate it, since we are proxying, we need to setup the instance with our current context - var foundControllerTree = foundControllerTreeAttempt.Result; - var instance = (TreeController) DependencyResolver.Current.GetService(foundControllerTree); - if (instance == null) - throw new Exception("Failed to get tree " + foundControllerTree.FullName + "."); - - instance.ControllerContext = controllerContext; - instance.Request = controllerContext.Request; - - // return its data - return Attempt.Succeed(instance.GetNodes(id, formCollection)); - } - - } - -} diff --git a/src/Umbraco.Web/Trees/UserPermissionsTreeController.cs b/src/Umbraco.Web/Trees/UserPermissionsTreeController.cs deleted file mode 100644 index 5473fee7bb..0000000000 --- a/src/Umbraco.Web/Trees/UserPermissionsTreeController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Linq; -using System.Net.Http.Formatting; -using Umbraco.Core; -using Umbraco.Web.Models.Trees; -using Umbraco.Web.Mvc; -using Umbraco.Web.WebApi.Filters; - -using Constants = Umbraco.Core.Constants; - -namespace Umbraco.Web.Trees -{ - [UmbracoTreeAuthorize(Constants.Trees.UserPermissions)] - [Tree(Constants.Applications.Users, Constants.Trees.UserPermissions, null, sortOrder: 2)] - [PluginController("UmbracoTrees")] - [CoreTree] - public class UserPermissionsTreeController : TreeController - { - protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) - { - var nodes = new TreeNodeCollection(); - long totalUsers; - nodes.AddRange( - Services.UserService.GetAll(0, int.MaxValue, out totalUsers) - .Where(x => x.Id != Constants.Security.SuperUserId && x.IsApproved) - .Select(x => CreateTreeNode(x.Id.ToString(), - id, - queryStrings, - x.Name, - "icon-user", - false, - "/" + queryStrings.GetValue("application") + "/framed/" - + Uri.EscapeDataString("users/PermissionEditor.aspx?id=" + x.Id)))); - - return nodes; - } - - protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) - { - var menu = new MenuItemCollection(); - - if (id == Constants.System.Root.ToInvariantString()) - { - // root actions - menu.Items.Add(new RefreshNode(Services.TextService, true)); - return menu; - } - - return menu; - } - } -} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index f1d15e9ea6..0b1603c9e3 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -166,8 +166,9 @@ - + + @@ -183,7 +184,7 @@ - + @@ -551,7 +552,6 @@ - @@ -649,7 +649,7 @@ - + @@ -972,7 +972,6 @@ - @@ -1056,7 +1055,6 @@ - diff --git a/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs index cc483db416..5ad3da7f4d 100644 --- a/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/UmbracoTreeAuthorizeAttribute.cs @@ -41,18 +41,16 @@ namespace Umbraco.Web.WebApi.Filters return true; } - throw new NotImplementedException(); + var apps = _treeAliases.Select(x => Current.TreeService + .GetByAlias(x)) + .WhereNotNull() + .Select(x => x.ApplicationAlias) + .Distinct() + .ToArray(); - //var apps = _treeAliases.Select(x => Current.Services.ApplicationTreeService - // .GetByAlias(x)) - // .WhereNotNull() - // .Select(x => x.ApplicationAlias) - // .Distinct() - // .ToArray(); - - //return Current.UmbracoContext.Security.CurrentUser != null - // && apps.Any(app => Current.UmbracoContext.Security.UserHasSectionAccess( - // app, Current.UmbracoContext.Security.CurrentUser)); + return Current.UmbracoContext.Security.CurrentUser != null + && apps.Any(app => Current.UmbracoContext.Security.UserHasSectionAccess( + app, Current.UmbracoContext.Security.CurrentUser)); } } } diff --git a/src/Umbraco.Web/WebApi/MvcVersionCheck.cs b/src/Umbraco.Web/WebApi/MvcVersionCheck.cs deleted file mode 100644 index 3c84fa91ce..0000000000 --- a/src/Umbraco.Web/WebApi/MvcVersionCheck.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Umbraco.Web.WebApi -{ - internal class WebApiVersionCheck - { - public static System.Version WebApiVersion - { - get { return typeof(System.Web.Http.ApiController).Assembly.GetName().Version; } - } - } -} diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs index d84ab3fe4a..cdb1aa2f51 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerTypeCollection.cs @@ -8,8 +8,6 @@ namespace Umbraco.Web.WebApi // which we are not doing at the moment // we can inherit from BuilderCollectionBase and just be enumerable - //fixme: this should be LazyCollectionBuilderBase ? - public class UmbracoApiControllerTypeCollection : BuilderCollectionBase { public UmbracoApiControllerTypeCollection(IEnumerable items) From 0160f141f4104c1048cf96f498b2dc1cc4a20e06 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:04:53 +1100 Subject: [PATCH 27/70] cleanup and explicitly registering sections --- .../Services/SectionServiceTests.cs | 2 +- .../TreesAndSections/ApplicationTreeTest.cs | 397 ----------------- .../ResourceFiles.Designer.cs | 91 ---- .../TreesAndSections/ResourceFiles.resx | 127 ------ .../TreesAndSections/SectionTests.cs | 252 ----------- .../TreesAndSections/applications.config | 16 - .../TreesAndSections/trees.config | 8 - src/Umbraco.Tests/Umbraco.Tests.csproj | 13 - .../Cache/ApplicationTreeCacheRefresher.cs | 46 -- .../Cache/DistributedCacheBinder_Handlers.cs | 47 -- .../Cache/DistributedCacheExtensions.cs | 19 - .../ContentEditing/IBackOfficeSection.cs | 15 - .../Models/Mapping/SectionMapperProfile.cs | 1 + .../Models/Trees/ApplicationDefinitions.cs | 77 ---- .../Models/Trees/IBackOfficeSection.cs | 12 + .../{SectionRootNode.cs => TreeRootNode.cs} | 0 src/Umbraco.Web/Runtime/WebRuntimeComposer.cs | 11 +- src/Umbraco.Web/Services/ISectionService.cs | 1 + src/Umbraco.Web/Services/ITreeService.cs | 10 +- src/Umbraco.Web/Services/SectionService.cs | 253 +---------- src/Umbraco.Web/Services/TreeService.cs | 410 +----------------- .../Trees/BackOfficeSectionCollection.cs | 8 +- .../BackOfficeSectionCollectionBuilder.cs | 10 + .../Trees/ContentBackOfficeSection.cs | 15 + src/Umbraco.Web/Trees/ITree.cs | 1 + .../Trees/MediaBackOfficeSection.cs | 15 + .../Trees/MembersBackOfficeSection.cs | 15 + .../Trees/PackagesBackOfficeSection.cs | 15 + .../Trees/SettingsBackOfficeSection.cs | 15 + .../Trees/TranslationBackOfficeSection.cs | 15 + src/Umbraco.Web/Trees/TreeCollection.cs | 27 -- .../Trees/TreeCollectionBuilder.cs | 18 + .../Trees/UsersBackOfficeSection.cs | 15 + src/Umbraco.Web/Umbraco.Web.csproj | 15 +- 34 files changed, 183 insertions(+), 1809 deletions(-) delete mode 100644 src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs delete mode 100644 src/Umbraco.Tests/TreesAndSections/ResourceFiles.Designer.cs delete mode 100644 src/Umbraco.Tests/TreesAndSections/ResourceFiles.resx delete mode 100644 src/Umbraco.Tests/TreesAndSections/SectionTests.cs delete mode 100644 src/Umbraco.Tests/TreesAndSections/applications.config delete mode 100644 src/Umbraco.Tests/TreesAndSections/trees.config delete mode 100644 src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs delete mode 100644 src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs delete mode 100644 src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs create mode 100644 src/Umbraco.Web/Models/Trees/IBackOfficeSection.cs rename src/Umbraco.Web/Models/Trees/{SectionRootNode.cs => TreeRootNode.cs} (100%) create mode 100644 src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs create mode 100644 src/Umbraco.Web/Trees/ContentBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/MediaBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/MembersBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/PackagesBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/SettingsBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/TranslationBackOfficeSection.cs create mode 100644 src/Umbraco.Web/Trees/TreeCollectionBuilder.cs create mode 100644 src/Umbraco.Web/Trees/UsersBackOfficeSection.cs diff --git a/src/Umbraco.Tests/Services/SectionServiceTests.cs b/src/Umbraco.Tests/Services/SectionServiceTests.cs index 206c99ffbf..9211755251 100644 --- a/src/Umbraco.Tests/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests/Services/SectionServiceTests.cs @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Services public class SectionServiceTests : TestWithSomeContentBase { //fixme - private ISectionService SectionService => new SectionService(ServiceContext.UserService, null, null); + private ISectionService SectionService => new SectionService(ServiceContext.UserService, null); [Test] diff --git a/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs b/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs deleted file mode 100644 index 95d90f1463..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/ApplicationTreeTest.cs +++ /dev/null @@ -1,397 +0,0 @@ -//using System.IO; -//using NUnit.Framework; -//using Umbraco.Core.Services; -//using Umbraco.Tests.TestHelpers; -//using System; -//using System.Linq; -//using System.Threading; -//using Umbraco.Tests.Testing; -//using Umbraco.Web.Services; -//using Current = Umbraco.Web.Composing.Current; - -//namespace Umbraco.Tests.TreesAndSections -//{ - - -// /// -// ///This is a test class for ApplicationTreeTest and is intended -// ///to contain all ApplicationTreeTest Unit Tests -// /// -// [TestFixture] -// [Apartment(ApartmentState.STA)] -// [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] -// public class ApplicationTreeTest : TestWithDatabaseBase -// { -// public override void SetUp() -// { -// base.SetUp(); - -// var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); -// var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); -// Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); -// using (var writer = File.CreateText(treesConfig)) -// { -// writer.Write(ResourceFiles.trees); -// } -// using (var writer = File.CreateText(appConfig)) -// { -// writer.Write(ResourceFiles.applications); -// } - -// //ApplicationTreeService.TreeConfigFilePath = treesConfig; -// SectionService.AppConfigFilePath = appConfig; -// } - -// public override void TearDown() -// { -// base.TearDown(); - -// if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) -// { -// Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); -// } -// //ApplicationTreeService.TreeConfigFilePath = null; -// SectionService.AppConfigFilePath = null; -// } - -// ///// -// ///// Creates a new app tree linked to an application, then delete the application and make sure the tree is gone as well -// ///// -// //[Test()] -// //public void ApplicationTree_Make_New_Then_Delete_App() -// //{ -// // //create new app -// // var appName = Guid.NewGuid().ToString("N"); -// // var treeName = Guid.NewGuid().ToString("N"); -// // Current.Services.SectionService.MakeNew(appName, appName, "icon.jpg"); - -// // //check if it exists -// // var app = Current.Services.SectionService.GetByAlias(appName); -// // Assert.IsNotNull(app); - -// // //create the new app tree assigned to the new app -// // Current.Services.ApplicationTreeService.MakeNew(false, 0, app.Alias, treeName, treeName, "icon.jpg", "icon.jpg", "Umbraco.Web.Trees.ContentTreeController, Umbraco.Web"); -// // var tree = Current.Services.ApplicationTreeService.GetByAlias(treeName); -// // Assert.IsNotNull(tree); - -// // //now delete the app -// // Current.Services.SectionService.DeleteSection(app); - -// // //check that the tree is gone -// // Assert.AreEqual(0, Current.Services.ApplicationTreeService.GetApplicationTrees(treeName).Count()); -// //} - - -// #region Tests to write -// ///// -// /////A test for ApplicationTree Constructor -// ///// -// //[TestMethod()] -// //public void ApplicationTreeConstructorTest() -// //{ -// // bool silent = false; // TODO: Initialize to an appropriate value -// // bool initialize = false; // TODO: Initialize to an appropriate value -// // byte sortOrder = 0; // TODO: Initialize to an appropriate value -// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value -// // string alias = string.Empty; // TODO: Initialize to an appropriate value -// // string title = string.Empty; // TODO: Initialize to an appropriate value -// // string iconClosed = string.Empty; // TODO: Initialize to an appropriate value -// // string iconOpened = string.Empty; // TODO: Initialize to an appropriate value -// // string assemblyName = string.Empty; // TODO: Initialize to an appropriate value -// // string type = string.Empty; // TODO: Initialize to an appropriate value -// // string action = string.Empty; // TODO: Initialize to an appropriate value -// // ApplicationTree target = new ApplicationTree(silent, initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, assemblyName, type, action); -// // Assert.Inconclusive("TODO: Implement code to verify target"); -// //} - -// ///// -// /////A test for ApplicationTree Constructor -// ///// -// //[TestMethod()] -// //public void ApplicationTreeConstructorTest1() -// //{ -// // ApplicationTree target = new ApplicationTree(); -// // Assert.Inconclusive("TODO: Implement code to verify target"); -// //} - -// ///// -// /////A test for Delete -// ///// -// //[TestMethod()] -// //public void DeleteTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // target.Delete(); -// // Assert.Inconclusive("A method that does not return a value cannot be verified."); -// //} - - -// ///// -// /////A test for Save -// ///// -// //[TestMethod()] -// //public void SaveTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // target.Save(); -// // Assert.Inconclusive("A method that does not return a value cannot be verified."); -// //} - -// ///// -// /////A test for getAll -// ///// -// //[TestMethod()] -// //public void getAllTest() -// //{ -// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value -// // ApplicationTree[] actual; -// // actual = ApplicationTree.getAll(); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for getApplicationTree -// ///// -// //[TestMethod()] -// //public void getApplicationTreeTest() -// //{ -// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value -// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value -// // ApplicationTree[] actual; -// // actual = ApplicationTree.getApplicationTree(applicationAlias); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for getApplicationTree -// ///// -// //[TestMethod()] -// //public void getApplicationTreeTest1() -// //{ -// // string applicationAlias = string.Empty; // TODO: Initialize to an appropriate value -// // bool onlyInitializedApplications = false; // TODO: Initialize to an appropriate value -// // ApplicationTree[] expected = null; // TODO: Initialize to an appropriate value -// // ApplicationTree[] actual; -// // actual = ApplicationTree.getApplicationTree(applicationAlias, onlyInitializedApplications); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for getByAlias -// ///// -// //[TestMethod()] -// //public void getByAliasTest() -// //{ -// // string treeAlias = string.Empty; // TODO: Initialize to an appropriate value -// // ApplicationTree expected = null; // TODO: Initialize to an appropriate value -// // ApplicationTree actual; -// // actual = ApplicationTree.getByAlias(treeAlias); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Action -// ///// -// //[TestMethod()] -// //public void ActionTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.Action = expected; -// // actual = target.Action; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Alias -// ///// -// //[TestMethod()] -// //public void AliasTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string actual; -// // actual = target.Alias; -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for ApplicationAlias -// ///// -// //[TestMethod()] -// //public void ApplicationAliasTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string actual; -// // actual = target.ApplicationAlias; -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for AssemblyName -// ///// -// //[TestMethod()] -// //public void AssemblyNameTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.AssemblyName = expected; -// // actual = target.AssemblyName; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for IconClosed -// ///// -// //[TestMethod()] -// //public void IconClosedTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.IconClosed = expected; -// // actual = target.IconClosed; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for IconOpened -// ///// -// //[TestMethod()] -// //public void IconOpenedTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.IconOpened = expected; -// // actual = target.IconOpened; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Initialize -// ///// -// //[TestMethod()] -// //public void InitializeTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // bool expected = false; // TODO: Initialize to an appropriate value -// // bool actual; -// // target.Initialize = expected; -// // actual = target.Initialize; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Silent -// ///// -// //[TestMethod()] -// //public void SilentTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // bool expected = false; // TODO: Initialize to an appropriate value -// // bool actual; -// // target.Silent = expected; -// // actual = target.Silent; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for SortOrder -// ///// -// //[TestMethod()] -// //public void SortOrderTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // byte expected = 0; // TODO: Initialize to an appropriate value -// // byte actual; -// // target.SortOrder = expected; -// // actual = target.SortOrder; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for SqlHelper -// ///// -// //[TestMethod()] -// //public void SqlHelperTest() -// //{ -// // ISqlHelper actual; -// // actual = ApplicationTree.SqlHelper; -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Title -// ///// -// //[TestMethod()] -// //public void TitleTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.Title = expected; -// // actual = target.Title; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for Type -// ///// -// //[TestMethod()] -// //public void TypeTest() -// //{ -// // ApplicationTree target = new ApplicationTree(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.Type = expected; -// // actual = target.Type; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} -// #endregion - -// #region Additional test attributes -// // -// //You can use the following additional attributes as you write your tests: -// // -// //Use ClassInitialize to run code before running the first test in the class -// //[ClassInitialize()] -// //public static void MyClassInitialize(TestContext testContext) -// //{ -// //} -// // -// //Use ClassCleanup to run code after all tests in a class have run -// //[ClassCleanup()] -// //public static void MyClassCleanup() -// //{ -// //} -// // -// //Use TestInitialize to run code before running each test -// //[TestInitialize()] -// //public void MyTestInitialize() -// //{ -// //} -// // -// //Use TestCleanup to run code after each test has run -// //[TestCleanup()] -// //public void MyTestCleanup() -// //{ -// //} -// // -// #endregion -// } -//} diff --git a/src/Umbraco.Tests/TreesAndSections/ResourceFiles.Designer.cs b/src/Umbraco.Tests/TreesAndSections/ResourceFiles.Designer.cs deleted file mode 100644 index 02bc84649e..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/ResourceFiles.Designer.cs +++ /dev/null @@ -1,91 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Umbraco.Tests.TreesAndSections { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class ResourceFiles { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal ResourceFiles() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Umbraco.Tests.TreesAndSections.ResourceFiles", typeof(ResourceFiles).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?> - ///<applications> - /// <add alias="content" name="content" icon="file" sortOrder="0" /> - /// <add alias="0b486ac9c0f1456996192c6ed1f03e57" name="0b486ac9c0f1456996192c6ed1f03e57" icon="icon.jpg" sortOrder="1" /> - /// <add alias="1ffbc301744c4e75ae3054d741954c7b" name="1ffbc301744c4e75ae3054d741954c7b" icon="icon.jpg" sortOrder="2" /> - /// <add alias="1838c3e1591f4008bbafe59a06a00a31" name="1838c3e1591f4008bbafe59a06a00a31" icon="icon.jpg" sortOrder="3" /> - /// <add alias="e5badae2 [rest of string was truncated]";. - /// - internal static string applications { - get { - return ResourceManager.GetString("applications", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to <?xml version="1.0" encoding="utf-8"?> - ///<trees> - /// <add initialize="false" sortOrder="0" alias="1838c3e1591f4008bbafe59a06a00a31" application="1838c3e1591f4008bbafe59a06a00a31" title="1838c3e1591f4008bbafe59a06a00a31" iconClosed="icon.jpg" iconOpen="icon.jpg" type="nulltype" /> - /// <add initialize="false" sortOrder="0" alias="e5badae2fc5e4cd7acb3700320e33b8b" application="e5badae2fc5e4cd7acb3700320e33b8b" title="e5badae2fc5e4cd7acb3700320e33b8b" iconClosed="icon.jpg" iconOpen="icon.jpg" type="nulltype" /> - /// [rest of string was truncated]";. - /// - internal static string trees { - get { - return ResourceManager.GetString("trees", resourceCulture); - } - } - } -} diff --git a/src/Umbraco.Tests/TreesAndSections/ResourceFiles.resx b/src/Umbraco.Tests/TreesAndSections/ResourceFiles.resx deleted file mode 100644 index fac58dc842..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/ResourceFiles.resx +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - applications.config;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - - trees.config;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - \ No newline at end of file diff --git a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs b/src/Umbraco.Tests/TreesAndSections/SectionTests.cs deleted file mode 100644 index 83de6c4479..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/SectionTests.cs +++ /dev/null @@ -1,252 +0,0 @@ -//using System.IO; -//using NUnit.Framework; -//using Umbraco.Core.Services; -//using Umbraco.Tests.TestHelpers; -//using System; -//using Umbraco.Core.Composing; -//using Umbraco.Tests.Testing; -//using Umbraco.Web.Services; - -//namespace Umbraco.Tests.TreesAndSections -//{ -// /// -// ///This is a test class for ApplicationTest and is intended -// ///to contain all ApplicationTest Unit Tests -// /// -// [TestFixture] -// [UmbracoTest(AutoMapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)] -// public class SectionTests : TestWithDatabaseBase -// { -// protected override void Compose() -// { -// base.Compose(); -// Composition.RegisterUnique(); -// } - -// public override void SetUp() -// { -// base.SetUp(); - -// var treesConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/trees.config"); -// var appConfig = TestHelper.MapPathForTest("~/TEMP/TreesAndSections/applications.config"); -// Directory.CreateDirectory(TestHelper.MapPathForTest("~/TEMP/TreesAndSections")); -// using (var writer = File.CreateText(treesConfig)) -// { -// writer.Write(ResourceFiles.trees); -// } -// using (var writer = File.CreateText(appConfig)) -// { -// writer.Write(ResourceFiles.applications); -// } - -// ApplicationTreeService.TreeConfigFilePath = treesConfig; -// SectionService.AppConfigFilePath = appConfig; -// } - -// public override void TearDown() -// { -// base.TearDown(); - -// if (Directory.Exists(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"))) -// { -// Directory.Delete(TestHelper.MapPathForTest("~/TEMP/TreesAndSections"), true); -// } -// ApplicationTreeService.TreeConfigFilePath = null; -// SectionService.AppConfigFilePath = null; -// } - -// ///// -// ///// Create a new application and delete it -// ///// -// //[Test()] -// //public void Application_Make_New() -// //{ -// // var name = Guid.NewGuid().ToString("N"); -// // ServiceContext.SectionService.MakeNew(name, name, "icon.jpg"); - -// // //check if it exists -// // var app = ServiceContext.SectionService.GetByAlias(name); -// // Assert.IsNotNull(app); - -// // //now remove it -// // ServiceContext.SectionService.DeleteSection(app); -// // Assert.IsNull(ServiceContext.SectionService.GetByAlias(name)); -// //} - -// #region Tests to write - - -// ///// -// /////A test for Application Constructor -// ///// -// //[TestMethod()] -// //public void ApplicationConstructorTest() -// //{ -// // string name = string.Empty; // TODO: Initialize to an appropriate value -// // string alias = string.Empty; // TODO: Initialize to an appropriate value -// // string icon = string.Empty; // TODO: Initialize to an appropriate value -// // Application target = new Application(name, alias, icon); -// // Assert.Inconclusive("TODO: Implement code to verify target"); -// //} - -// ///// -// /////A test for Application Constructor -// ///// -// //[TestMethod()] -// //public void ApplicationConstructorTest1() -// //{ -// // Application target = new Application(); -// // Assert.Inconclusive("TODO: Implement code to verify target"); -// //} - -// ///// -// /////A test for Delete -// ///// -// //[TestMethod()] -// //public void DeleteTest() -// //{ -// // Application target = new Application(); // TODO: Initialize to an appropriate value -// // target.Delete(); -// // Assert.Inconclusive("A method that does not return a value cannot be verified."); -// //} - - - -// ///// -// /////A test for MakeNew -// ///// -// //[TestMethod()] -// //public void MakeNewTest1() -// //{ -// // string name = string.Empty; // TODO: Initialize to an appropriate value -// // string alias = string.Empty; // TODO: Initialize to an appropriate value -// // string icon = string.Empty; // TODO: Initialize to an appropriate value -// // Application.MakeNew(name, alias, icon); -// // Assert.Inconclusive("A method that does not return a value cannot be verified."); -// //} - -// ///// -// /////A test for RegisterIApplications -// ///// -// //[TestMethod()] -// //public void RegisterIApplicationsTest() -// //{ -// // Application.RegisterIApplications(); -// // Assert.Inconclusive("A method that does not return a value cannot be verified."); -// //} - -// ///// -// /////A test for getAll -// ///// -// //[TestMethod()] -// //public void getAllTest() -// //{ -// // List expected = null; // TODO: Initialize to an appropriate value -// // List actual; -// // actual = Application.getAll(); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for getByAlias -// ///// -// //[TestMethod()] -// //public void getByAliasTest() -// //{ -// // string appAlias = string.Empty; // TODO: Initialize to an appropriate value -// // Application expected = null; // TODO: Initialize to an appropriate value -// // Application actual; -// // actual = Application.getByAlias(appAlias); -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for SqlHelper -// ///// -// //[TestMethod()] -// //public void SqlHelperTest() -// //{ -// // ISqlHelper actual; -// // actual = Application.SqlHelper; -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for alias -// ///// -// //[TestMethod()] -// //public void aliasTest() -// //{ -// // Application target = new Application(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.alias = expected; -// // actual = target.alias; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for icon -// ///// -// //[TestMethod()] -// //public void iconTest() -// //{ -// // Application target = new Application(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.icon = expected; -// // actual = target.icon; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} - -// ///// -// /////A test for name -// ///// -// //[TestMethod()] -// //public void nameTest() -// //{ -// // Application target = new Application(); // TODO: Initialize to an appropriate value -// // string expected = string.Empty; // TODO: Initialize to an appropriate value -// // string actual; -// // target.name = expected; -// // actual = target.name; -// // Assert.AreEqual(expected, actual); -// // Assert.Inconclusive("Verify the correctness of this test method."); -// //} -// #endregion - -// #region Additional test attributes -// // -// //You can use the following additional attributes as you write your tests: -// // -// //Use ClassInitialize to run code before running the first test in the class -// //[ClassInitialize()] -// //public static void MyClassInitialize(TestContext testContext) -// //{ -// //} -// // -// //Use ClassCleanup to run code after all tests in a class have run -// //[ClassCleanup()] -// //public static void MyClassCleanup() -// //{ -// //} -// // -// //Use TestInitialize to run code before running each test -// //[TestInitialize()] -// //public void MyTestInitialize() -// //{ -// //} -// // -// //Use TestCleanup to run code after each test has run -// //[TestCleanup()] -// //public void MyTestCleanup() -// //{ -// //} -// // -// #endregion -// } -//} diff --git a/src/Umbraco.Tests/TreesAndSections/applications.config b/src/Umbraco.Tests/TreesAndSections/applications.config deleted file mode 100644 index aadd1c5407..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/applications.config +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Tests/TreesAndSections/trees.config b/src/Umbraco.Tests/TreesAndSections/trees.config deleted file mode 100644 index d21fea28a9..0000000000 --- a/src/Umbraco.Tests/TreesAndSections/trees.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index e49ba250fa..408b0f96ca 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -423,13 +423,6 @@ - - True - True - ResourceFiles.resx - - - @@ -525,8 +518,6 @@ Designer Always - - Designer @@ -561,10 +552,6 @@ ImportResources.Designer.cs Designer - - ResXFileCodeGenerator - ResourceFiles.Designer.cs - ResXFileCodeGenerator TestFiles.Designer.cs diff --git a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs deleted file mode 100644 index 4d6740a0b1..0000000000 --- a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs +++ /dev/null @@ -1,46 +0,0 @@ -//using System; -//using Umbraco.Core.Cache; - -//namespace Umbraco.Web.Cache -//{ -// public sealed class ApplicationTreeCacheRefresher : CacheRefresherBase -// { -// public ApplicationTreeCacheRefresher(CacheHelper cacheHelper) -// : base(cacheHelper) -// { } - -// #region Define - -// protected override ApplicationTreeCacheRefresher This => this; - -// public static readonly Guid UniqueId = Guid.Parse("0AC6C028-9860-4EA4-958D-14D39F45886E"); - -// public override Guid RefresherUniqueId => UniqueId; - -// public override string Name => "Application Tree Cache Refresher"; - -// #endregion - -// #region Refresher - -// public override void RefreshAll() -// { -// CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); -// base.RefreshAll(); -// } - -// public override void Refresh(int id) -// { -// Remove(id); -// base.Refresh(id); -// } - -// public override void Remove(int id) -// { -// CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); -// base.Remove(id); -// } - -// #endregion -// } -//} diff --git a/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs b/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs index 421eb546a4..3a3eb1b8fb 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheBinder_Handlers.cs @@ -46,20 +46,6 @@ namespace Umbraco.Web.Cache _logger.Info("Initializing Umbraco internal event handlers for cache refreshing."); - //// bind to application tree events - //Bind(() => ApplicationTreeService.Deleted += ApplicationTreeService_Deleted, - // () => ApplicationTreeService.Deleted -= ApplicationTreeService_Deleted); - //Bind(() => ApplicationTreeService.Updated += ApplicationTreeService_Updated, - // () => ApplicationTreeService.Updated -= ApplicationTreeService_Updated); - //Bind(() => ApplicationTreeService.New += ApplicationTreeService_New, - // () => ApplicationTreeService.New -= ApplicationTreeService_New); - - //// bind to application events - //Bind(() => SectionService.Deleted += SectionService_Deleted, - // () => SectionService.Deleted -= SectionService_Deleted); - //Bind(() => SectionService.New += SectionService_New, - // () => SectionService.New -= SectionService_New); - // bind to user and user group events Bind(() => UserService.SavedUserGroup += UserService_SavedUserGroup, () => UserService.SavedUserGroup -= UserService_SavedUserGroup); @@ -231,39 +217,6 @@ namespace Umbraco.Web.Cache #endregion - //#region ApplicationTreeService - - //private void ApplicationTreeService_New(ApplicationTree sender, EventArgs e) - //{ - // _distributedCache.RefreshAllApplicationTreeCache(); - //} - - //private void ApplicationTreeService_Updated(ApplicationTree sender, EventArgs e) - //{ - // _distributedCache.RefreshAllApplicationTreeCache(); - //} - - //private void ApplicationTreeService_Deleted(ApplicationTree sender, EventArgs e) - //{ - // _distributedCache.RefreshAllApplicationTreeCache(); - //} - - //#endregion - - //#region Application event handlers - - //private void SectionService_New(ISectionService sender, EventArgs e) - //{ - // _distributedCache.RefreshAllApplicationCache(); - //} - - //private void SectionService_Deleted(ISectionService sender, EventArgs e) - //{ - // _distributedCache.RefreshAllApplicationCache(); - //} - - //#endregion - #region LocalizationService / Dictionary private void LocalizationService_SavedDictionaryItem(ILocalizationService sender, SaveEventArgs e) diff --git a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs index aab0f9b157..80c49e279c 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs @@ -18,24 +18,6 @@ namespace Umbraco.Web.Cache #endregion - //#region ApplicationTreeCache - - //public static void RefreshAllApplicationTreeCache(this DistributedCache dc) - //{ - // dc.RefreshAll(ApplicationTreeCacheRefresher.UniqueId); - //} - - //#endregion - - //#region ApplicationCache - - //public static void RefreshAllApplicationCache(this DistributedCache dc) - //{ - // dc.RefreshAll(ApplicationCacheRefresher.UniqueId); - //} - - //#endregion - #region User cache public static void RemoveUserCache(this DistributedCache dc, int userId) @@ -74,7 +56,6 @@ namespace Umbraco.Web.Cache #endregion - #region TemplateCache public static void RefreshTemplateCache(this DistributedCache dc, int templateId) diff --git a/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs b/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs deleted file mode 100644 index f27941035a..0000000000 --- a/src/Umbraco.Web/Models/ContentEditing/IBackOfficeSection.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Umbraco.Core.Composing; - -namespace Umbraco.Web.Models.ContentEditing -{ - - /// - /// Defines a back office section - /// - public interface IBackOfficeSection : IDiscoverable - { - string Alias { get; } - string Name { get; } - int SortOrder { get; } - } -} diff --git a/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs index 683fce36e8..5aa99e4652 100644 --- a/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs @@ -3,6 +3,7 @@ using AutoMapper; using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Models.Mapping { diff --git a/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs b/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs deleted file mode 100644 index ba48c9e240..0000000000 --- a/src/Umbraco.Web/Models/Trees/ApplicationDefinitions.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Core.Models.ContentEditing; -using Umbraco.Web.Models.ContentEditing; - -namespace Umbraco.Web.Models.Trees -{ - /// - /// Defines the back office content section - /// - public class ContentBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Content; - public string Name => "Content"; - public int SortOrder => 0; - } - - /// - /// Defines the back office media section - /// - public class MediaBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Media; - public string Name => "Media"; - public int SortOrder => 1; - } - - /// - /// Defines the back office settings section - /// - public class SettingsBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Settings; - public string Name => "Settings"; - public int SortOrder => 2; - } - - /// - /// Defines the back office packages section - /// - public class PackagesBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Packages; - public string Name => "Packages"; - public int SortOrder => 3; - } - - /// - /// Defines the back office users section - /// - public class UsersBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Users; - public string Name => "Users"; - public int SortOrder => 4; - } - - /// - /// Defines the back office members section - /// - public class MembersBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Members; - public string Name => "Members"; - public int SortOrder => 5; - } - - /// - /// Defines the back office translation section - /// - public class TranslationBackOfficeSectionDefinition : IBackOfficeSection - { - public string Alias => Constants.Applications.Translation; - public string Name => "Translation"; - public int SortOrder => 6; - } -} diff --git a/src/Umbraco.Web/Models/Trees/IBackOfficeSection.cs b/src/Umbraco.Web/Models/Trees/IBackOfficeSection.cs new file mode 100644 index 0000000000..0cc505fb19 --- /dev/null +++ b/src/Umbraco.Web/Models/Trees/IBackOfficeSection.cs @@ -0,0 +1,12 @@ +namespace Umbraco.Web.Models.Trees +{ + + /// + /// Defines a back office section + /// + public interface IBackOfficeSection + { + string Alias { get; } + string Name { get; } + } +} diff --git a/src/Umbraco.Web/Models/Trees/SectionRootNode.cs b/src/Umbraco.Web/Models/Trees/TreeRootNode.cs similarity index 100% rename from src/Umbraco.Web/Models/Trees/SectionRootNode.cs rename to src/Umbraco.Web/Models/Trees/TreeRootNode.cs diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs index 047d080a88..134ed7b1d0 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs @@ -25,6 +25,7 @@ using Umbraco.Web.Features; using Umbraco.Web.HealthCheck; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.PublishedContent; +using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; @@ -195,9 +196,15 @@ namespace Umbraco.Web.Runtime .Append() .Append(); - // register back office sections + // register back office sections in the order we want them rendered composition.WithCollectionBuilder() - .Add(() => composition.TypeLoader.GetTypes()); + .Append() + .Append() + .Append() + .Append() + .Append() + .Append() + .Append(); // register back office trees foreach (var treeControllerType in umbracoApiControllerTypes) diff --git a/src/Umbraco.Web/Services/ISectionService.cs b/src/Umbraco.Web/Services/ISectionService.cs index c325020cf1..f0a16dc965 100644 --- a/src/Umbraco.Web/Services/ISectionService.cs +++ b/src/Umbraco.Web/Services/ISectionService.cs @@ -2,6 +2,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.ContentEditing; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Services { diff --git a/src/Umbraco.Web/Services/ITreeService.cs b/src/Umbraco.Web/Services/ITreeService.cs index ce734cc5e4..17998ae1a7 100644 --- a/src/Umbraco.Web/Services/ITreeService.cs +++ b/src/Umbraco.Web/Services/ITreeService.cs @@ -29,15 +29,7 @@ namespace Umbraco.Web.Services /// The application alias. /// Returns a ApplicationTree Array IEnumerable GetApplicationTrees(string applicationAlias); - - ///// - ///// Gets the application tree for the applcation with the specified alias - ///// - ///// The application alias. - ///// - ///// Returns a ApplicationTree Array - //IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized); - + /// /// Gets the grouped application trees for the application with the specified alias /// diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index bb154976f0..e6af27534c 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -25,270 +25,31 @@ namespace Umbraco.Web.Services private readonly IUserService _userService; private readonly BackOfficeSectionCollection _sectionCollection; - private readonly Lazy> _allAvailableSections; - //private readonly IApplicationTreeService _applicationTreeService; - //private readonly IScopeProvider _scopeProvider; - private readonly CacheHelper _cache; - //internal const string AppConfigFileName = "applications.config"; - //private static string _appConfig; - //private static readonly object Locker = new object(); - public SectionService( IUserService userService, - BackOfficeSectionCollection sectionCollection, - CacheHelper cache) + BackOfficeSectionCollection sectionCollection) { - //_applicationTreeService = applicationTreeService ?? throw new ArgumentNullException(nameof(applicationTreeService)); - _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _userService = userService; _sectionCollection = sectionCollection; - //_scopeProvider = scopeProvider; - //_allAvailableSections = new Lazy>(() => new LazyEnumerableSections()); } - - - ///// - ///// gets/sets the application.config file path - ///// - ///// - ///// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath - ///// - //internal static string AppConfigFilePath - //{ - // get - // { - // if (string.IsNullOrWhiteSpace(_appConfig)) - // { - // _appConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + AppConfigFileName); - // } - // return _appConfig; - // } - // set => _appConfig = value; - //} - + /// /// The cache storage for all applications /// - public IEnumerable GetSections() - { - return _sectionCollection; - } + public IEnumerable GetSections() => _sectionCollection; - //internal void LoadXml(Func callback, bool saveAfterCallbackIfChanged) - //{ - // lock (Locker) - // { - // var doc = File.Exists(AppConfigFilePath) - // ? XDocument.Load(AppConfigFilePath) - // : XDocument.Parse(""); - - // if (doc.Root != null) - // { - // var changed = callback.Invoke(doc); - - // if (saveAfterCallbackIfChanged && changed) - // { - // //ensure the folder is created! - // Directory.CreateDirectory(Path.GetDirectoryName(AppConfigFilePath)); - - // doc.Save(AppConfigFilePath); - - // //remove the cache so it gets re-read ... SD: I'm leaving this here even though it - // // is taken care of by events as well, I think unit tests may rely on it being cleared here. - // _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); - // } - // } - // } - //} - - /// - /// Get the user's allowed sections - /// - /// - /// + /// public IEnumerable GetAllowedSections(int userId) { - var user = _userService.GetUserById(userId); if (user == null) - { throw new InvalidOperationException("No user found with id " + userId); - } return GetSections().Where(x => user.AllowedSections.Contains(x.Alias)); } - /// - /// Gets the application by its alias. - /// - /// The application alias. - /// - public IBackOfficeSection GetByAlias(string appAlias) - { - return GetSections().FirstOrDefault(t => t.Alias == appAlias); - } - - ///// - ///// Creates a new applcation if no application with the specified alias is found. - ///// - ///// The application name. - ///// The application alias. - ///// The application icon, which has to be located in umbraco/images/tray folder. - //public void MakeNew(string name, string alias, string icon) - //{ - // var sections = GetSections(); - // var nextSortOrder = sections.Any() ? sections.Max(x => x.SortOrder) + 1 : 1; - // MakeNew(name, alias, icon, nextSortOrder); - //} - - ///// - ///// Makes the new. - ///// - ///// The name. - ///// The alias. - ///// The icon. - ///// The sort order. - //public void MakeNew(string name, string alias, string icon, int sortOrder) - //{ - // if (GetSections().All(x => x.Alias != alias)) - // { - // LoadXml(doc => - // { - // doc.Root.Add(new XElement("add", - // new XAttribute("alias", alias), - // new XAttribute("name", name), - // new XAttribute("icon", icon), - // new XAttribute("sortOrder", sortOrder))); - // return true; - // }, true); - - // //raise event - // OnNew(this /*new Section(name, alias, sortOrder)*/, new EventArgs()); - // } - //} - - ///// - ///// Deletes the section - ///// - //public void DeleteSection(Section section) - //{ - // lock (Locker) - // { - // //delete the assigned applications - // using (var scope = _scopeProvider.CreateScope()) - // { - // scope.Database.Execute("delete from umbracoUserGroup2App where app = @appAlias", - // new { appAlias = section.Alias }); - // scope.Complete(); - // } - - // //delete the assigned trees - // var trees = _applicationTreeService.GetApplicationTrees(section.Alias); - // foreach (var t in trees) - // { - // _applicationTreeService.DeleteTree(t); - // } - - // LoadXml(doc => - // { - // doc.Root.Elements("add").Where(x => x.Attribute("alias") != null && x.Attribute("alias").Value == section.Alias) - // .Remove(); - - // return true; - // }, true); - - // //raise event - // OnDeleted(this, new EventArgs()); - // } - //} - - //private List
ReadFromXmlAndSort() - //{ - // var tmp = new List
(); - - // LoadXml(doc => - // { - // foreach (var addElement in doc.Root.Elements("add").OrderBy(x => - // { - // var sortOrderAttr = x.Attribute("sortOrder"); - // return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; - // })) - // { - // var sortOrderAttr = addElement.Attribute("sortOrder"); - // tmp.Add(new Section(addElement.Attribute("name").Value, - // addElement.Attribute("alias").Value, - // sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0)); - // } - // return false; - // }, false); - - // return tmp; - //} - - //internal static event TypedEventHandler Deleted; - //private static void OnDeleted(ISectionService app, EventArgs args) - //{ - // if (Deleted != null) - // { - // Deleted(app, args); - // } - //} - - //internal static event TypedEventHandler New; - //private static void OnNew(ISectionService app, EventArgs args) - //{ - // if (New != null) - // { - // New(app, args); - // } - //} - - ///// - ///// This class is here so that we can provide lazy access to tree scanning for when it is needed - ///// - //private class LazyEnumerableSections : IEnumerable
- //{ - // public LazyEnumerableSections() - // { - // _lazySections = new Lazy>(() => - // { - // // Load all Applications by attribute and add them to the XML config - - // //don't cache the result of this because it is only used once during app startup, caching will just add a bit more mem overhead for no reason - // var types = Current.TypeLoader.GetTypesWithAttribute(cache: false); // fixme - inject - - // //since applications don't populate their metadata from the attribute and because it is an interface, - // //we need to interrogate the attributes for the data. Would be better to have a base class that contains - // //metadata populated by the attribute. Oh well i guess. - // var attrs = types.Select(x => x.GetCustomAttributes(false).Single()); - // return attrs.Select(x => new Section(x.Name, x.Alias, x.SortOrder)).ToArray(); - // }); - // } - - // private readonly Lazy> _lazySections; - - // /// - // /// Returns an enumerator that iterates through the collection. - // /// - // /// - // /// A that can be used to iterate through the collection. - // /// - // public IEnumerator
GetEnumerator() - // { - // return _lazySections.Value.GetEnumerator(); - // } - - // /// - // /// Returns an enumerator that iterates through a collection. - // /// - // /// - // /// An object that can be used to iterate through the collection. - // /// - // IEnumerator IEnumerable.GetEnumerator() - // { - // return GetEnumerator(); - // } - //} - + /// + public IBackOfficeSection GetByAlias(string appAlias) => GetSections().FirstOrDefault(t => t.Alias == appAlias); + } } diff --git a/src/Umbraco.Web/Services/TreeService.cs b/src/Umbraco.Web/Services/TreeService.cs index cf010f1480..670f57ce49 100644 --- a/src/Umbraco.Web/Services/TreeService.cs +++ b/src/Umbraco.Web/Services/TreeService.cs @@ -1,237 +1,22 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Xml.Linq; using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Events; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.ContentEditing; -using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Trees; namespace Umbraco.Web.Services { internal class TreeService : ITreeService { - private readonly ILogger _logger; private readonly TreeCollection _treeCollection; - private static readonly object Locker = new object(); private readonly Lazy>> _groupedTrees; - public TreeService(ILogger logger, TreeCollection treeCollection) + public TreeService(TreeCollection treeCollection) { - _logger = logger; _treeCollection = treeCollection; _groupedTrees = new Lazy>>(InitGroupedTrees); } - ///// - ///// gets/sets the trees.config file path - ///// - ///// - ///// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath - ///// - //internal static string TreeConfigFilePath - //{ - // get - // { - // if (string.IsNullOrWhiteSpace(_treeConfig)) - // { - // _treeConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + TreeConfigFileName); - // } - // return _treeConfig; - // } - // set { _treeConfig = value; } - //} - - ///// - ///// The main entry point to get application trees - ///// - ///// - ///// This lazily on first access will scan for plugin trees and ensure the trees.config is up-to-date with the plugins. If plugins - ///// haven't changed on disk then the file will not be saved. The trees are all then loaded from this config file into cache and returned. - ///// - //private List GetAppTrees() - //{ - // return _cache.RuntimeCache.GetCacheItem>( - // CacheKeys.ApplicationTreeCacheKey, - // () => - // { - // var list = ReadFromXmlAndSort(); - - // //now we can check the non-volatile flag - // if (_allAvailableTrees != null) - // { - // var hasChanges = false; - - // LoadXml(doc => - // { - // //Now, load in the xml structure and update it with anything that is not declared there and save the file. - - // //NOTE: On the first iteration here, it will lazily scan all trees, etc... this is because this ienumerable is lazy - // // based on the ApplicationTreeRegistrar - and as noted there this is not an ideal way to do things but were stuck like this - // // currently because of the legacy assemblies and types not in the Core. - - // //Get all the trees not registered in the config (those not matching by alias casing will be detected as "unregistered") - // var unregistered = _allAvailableTrees.Value - // .Where(x => list.Any(l => l.Alias == x.Alias) == false) - // .ToArray(); - - // hasChanges = unregistered.Any(); - - // if (hasChanges == false) return false; - - // //add or edit the unregistered ones and re-save the file if any changes were found - // var count = 0; - // foreach (var tree in unregistered) - // { - // var existingElement = doc.Root.Elements("add").SingleOrDefault(x => - // string.Equals(x.Attribute("alias").Value, tree.Alias, - // StringComparison.InvariantCultureIgnoreCase) && - // string.Equals(x.Attribute("application").Value, tree.ApplicationAlias, - // StringComparison.InvariantCultureIgnoreCase)); - // if (existingElement != null) - // { - // existingElement.SetAttributeValue("alias", tree.Alias); - // } - // else - // { - // if (tree.Title.IsNullOrWhiteSpace()) - // { - // doc.Root.Add(new XElement("add", - // new XAttribute("initialize", tree.Initialize), - // new XAttribute("sortOrder", tree.SortOrder), - // new XAttribute("alias", tree.Alias), - // new XAttribute("application", tree.ApplicationAlias), - // new XAttribute("iconClosed", tree.IconClosed), - // new XAttribute("iconOpen", tree.IconOpened), - // new XAttribute("type", tree.Type))); - // } - // else - // { - // doc.Root.Add(new XElement("add", - // new XAttribute("initialize", tree.Initialize), - // new XAttribute("sortOrder", tree.SortOrder), - // new XAttribute("alias", tree.Alias), - // new XAttribute("application", tree.ApplicationAlias), - // new XAttribute("title", tree.Title), - // new XAttribute("iconClosed", tree.IconClosed), - // new XAttribute("iconOpen", tree.IconOpened), - // new XAttribute("type", tree.Type))); - // } - - // } - // count++; - // } - - // //don't save if there's no changes - // return count > 0; - // }, true); - - // if (hasChanges) - // { - // //If there were changes, we need to re-read the structures from the XML - // list = ReadFromXmlAndSort(); - // } - // } - - // return list; - // }, new TimeSpan(0, 10, 0)); - //} - - ///// - ///// Creates a new application tree. - ///// - ///// if set to true [initialize]. - ///// The sort order. - ///// The application alias. - ///// The alias. - ///// The title. - ///// The icon closed. - ///// The icon opened. - ///// The type. - //public void MakeNew(bool initialize, int sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string type) - //{ - // LoadXml(doc => - // { - // var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == alias && x.Attribute("application").Value == applicationAlias); - - // if (el == null) - // { - // doc.Root.Add(new XElement("add", - // new XAttribute("initialize", initialize), - // new XAttribute("sortOrder", sortOrder), - // new XAttribute("alias", alias), - // new XAttribute("application", applicationAlias), - // new XAttribute("title", title), - // new XAttribute("iconClosed", iconClosed), - // new XAttribute("iconOpen", iconOpened), - // new XAttribute("type", type))); - // } - - // return true; - - // }, true); - - // OnNew(new ApplicationTree(initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, type), new EventArgs()); - //} - - ///// - ///// Saves this instance. - ///// - //public void SaveTree(ApplicationTree tree) - //{ - // LoadXml(doc => - // { - // var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == tree.Alias && x.Attribute("application").Value == tree.ApplicationAlias); - - // if (el != null) - // { - // el.RemoveAttributes(); - - // el.Add(new XAttribute("initialize", tree.Initialize)); - // el.Add(new XAttribute("sortOrder", tree.SortOrder)); - // el.Add(new XAttribute("alias", tree.Alias)); - // el.Add(new XAttribute("application", tree.ApplicationAlias)); - // el.Add(new XAttribute("title", tree.Title)); - // el.Add(new XAttribute("iconClosed", tree.IconClosed)); - // el.Add(new XAttribute("iconOpen", tree.IconOpened)); - // el.Add(new XAttribute("type", tree.Type)); - // } - - // return true; - - // }, true); - - // OnUpdated(tree, new EventArgs()); - //} - - ///// - ///// Deletes this instance. - ///// - //public void DeleteTree(ApplicationTree tree) - //{ - // LoadXml(doc => - // { - // doc.Root.Elements("add") - // .Where(x => x.Attribute("application") != null - // && x.Attribute("application").Value == tree.ApplicationAlias - // && x.Attribute("alias") != null && x.Attribute("alias").Value == tree.Alias).Remove(); - - // return true; - - // }, true); - - // OnDeleted(tree, new EventArgs()); - //} - /// public ApplicationTree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.TreeAlias == treeAlias); @@ -242,26 +27,6 @@ namespace Umbraco.Web.Services public IEnumerable GetApplicationTrees(string applicationAlias) => GetAll().Where(x => x.ApplicationAlias.InvariantEquals(applicationAlias)).OrderBy(x => x.SortOrder).ToList(); - ///// - ///// Gets the application tree for the applcation with the specified alias - ///// - ///// The application alias. - ///// - ///// Returns a ApplicationTree Array - //public IEnumerable GetApplicationTrees(string applicationAlias, bool onlyInitialized) - //{ - // var list = GetAppTrees().FindAll( - // t => - // { - // if (onlyInitialized) - // return (t.ApplicationAlias == applicationAlias && t.Initialize); - // return (t.ApplicationAlias == applicationAlias); - // } - // ); - - // return list.OrderBy(x => x.SortOrder).ToArray(); - //} - public IDictionary> GetGroupedApplicationTrees(string applicationAlias) { var result = new Dictionary>(); @@ -273,11 +38,10 @@ namespace Umbraco.Web.Services { foreach(var treeAliasInGroup in treeGroup) { - if (tree.TreeAlias == treeAliasInGroup) - { - if (resultGroup == null) resultGroup = new List(); - resultGroup.Add(tree); - } + if (tree.TreeAlias != treeAliasInGroup) continue; + + if (resultGroup == null) resultGroup = new List(); + resultGroup.Add(tree); } } if (resultGroup != null) @@ -302,169 +66,5 @@ namespace Umbraco.Web.Services return result; } - ///// - ///// Loads in the xml structure from disk if one is found, otherwise loads in an empty xml structure, calls the - ///// callback with the xml document and saves the structure back to disk if saveAfterCallback is true. - ///// - ///// - ///// - //internal void LoadXml(Func callback, bool saveAfterCallbackIfChanges) - //{ - // lock (Locker) - // { - // var doc = System.IO.File.Exists(TreeConfigFilePath) - // ? XDocument.Load(TreeConfigFilePath) - // : XDocument.Parse(""); - - // if (doc.Root != null) - // { - // var hasChanges = callback.Invoke(doc); - - // if (saveAfterCallbackIfChanges && hasChanges - // //Don't save it if it is empty, in some very rare cases if the app domain get's killed in the middle of this process - // // in some insane way the file saved will be empty. I'm pretty sure it's not actually anything to do with the xml doc and - // // more about the IO trying to save the XML doc, but it doesn't hurt to check. - // && doc.Root != null && doc.Root.Elements().Any()) - // { - // //ensures the folder exists - // Directory.CreateDirectory(Path.GetDirectoryName(TreeConfigFilePath)); - - // //saves it - // doc.Save(TreeConfigFilePath); - - // //remove the cache now that it has changed SD: I'm leaving this here even though it - // // is taken care of by events as well, I think unit tests may rely on it being cleared here. - // _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); - // } - // } - // } - //} - - //private List ReadFromXmlAndSort() - //{ - // var list = new List(); - - // //read in the xml file containing trees and convert them all to ApplicationTree instances - // LoadXml(doc => - // { - // foreach (var addElement in doc.Root.Elements("add").OrderBy(x => - // { - // var sortOrderAttr = x.Attribute("sortOrder"); - // return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0; - // })) - // { - // var applicationAlias = (string)addElement.Attribute("application"); - // var type = (string)addElement.Attribute("type"); - // var assembly = (string)addElement.Attribute("assembly"); - - // var clrType = Type.GetType(type); - // if (clrType == null) - // { - // _logger.Warn("The tree definition: {AddElement} could not be resolved to a .Net object type", addElement); - // continue; - // } - - // //check if the tree definition (applicationAlias + type + assembly) is already in the list - - // if (list.Any(tree => tree.ApplicationAlias.InvariantEquals(applicationAlias) && tree.GetRuntimeType() == clrType) == false) - // { - // list.Add(new ApplicationTree( - // addElement.Attribute("initialize") == null || Convert.ToBoolean(addElement.Attribute("initialize").Value), - // addElement.Attribute("sortOrder") != null - // ? Convert.ToByte(addElement.Attribute("sortOrder").Value) - // : (byte)0, - // (string)addElement.Attribute("application"), - // (string)addElement.Attribute("alias"), - // (string)addElement.Attribute("title"), - // (string)addElement.Attribute("iconClosed"), - // (string)addElement.Attribute("iconOpen"), - // (string)addElement.Attribute("type"))); - // } - // } - - // return false; - - // }, false); - - // return list; - //} - - - //internal static event TypedEventHandler Deleted; - //private static void OnDeleted(ApplicationTree app, EventArgs args) - //{ - // if (Deleted != null) - // { - // Deleted(app, args); - // } - //} - - //internal static event TypedEventHandler New; - //private static void OnNew(ApplicationTree app, EventArgs args) - //{ - // if (New != null) - // { - // New(app, args); - // } - //} - - //internal static event TypedEventHandler Updated; - //private static void OnUpdated(ApplicationTree app, EventArgs args) - //{ - // if (Updated != null) - // { - // Updated(app, args); - // } - //} - - ///// - ///// This class is here so that we can provide lazy access to tree scanning for when it is needed - ///// - //private class LazyEnumerableTrees : IEnumerable - //{ - // public LazyEnumerableTrees(TypeLoader typeLoader) - // { - // _lazyTrees = new Lazy>(() => - // { - // var added = new List(); - - // // Load all Controller Trees by attribute - // var types = typeLoader.GetTypesWithAttribute(); // fixme inject - // //convert them to ApplicationTree instances - // var items = types - // .Select(x => (tree: x, treeAttribute: x.GetCustomAttributes(false).Single())) - // .Select(x => new ApplicationTree(x.treeAttribute.Initialize, x.treeAttribute.SortOrder, x.treeAttribute.ApplicationAlias, x.treeAttribute.Alias, x.treeAttribute.Title, x.treeAttribute.IconClosed, x.treeAttribute.IconOpen, x.tree.GetFullNameWithAssembly())) - // .ToArray(); - - // added.AddRange(items.Select(x => x.Alias)); - - // return items.ToArray(); - // }); - // } - - // private readonly Lazy> _lazyTrees; - - // /// - // /// Returns an enumerator that iterates through the collection. - // /// - // /// - // /// A that can be used to iterate through the collection. - // /// - // public IEnumerator GetEnumerator() - // { - // return _lazyTrees.Value.GetEnumerator(); - // } - - // /// - // /// Returns an enumerator that iterates through a collection. - // /// - // /// - // /// An object that can be used to iterate through the collection. - // /// - // IEnumerator IEnumerable.GetEnumerator() - // { - // return GetEnumerator(); - // } - //} } } diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs index 2b5a78d758..54762e73d8 100644 --- a/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs @@ -2,6 +2,7 @@ using Umbraco.Core.Composing; using Umbraco.Core.Models.ContentEditing; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Trees { @@ -11,11 +12,4 @@ namespace Umbraco.Web.Trees : base(items) { } } - - public class BackOfficeSectionCollectionBuilder : LazyCollectionBuilderBase - { - protected override BackOfficeSectionCollectionBuilder This => this; - - //TODO: can we allow for re-ordering OOTB without exposing other methods? - } } diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs new file mode 100644 index 0000000000..62d61a4090 --- /dev/null +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs @@ -0,0 +1,10 @@ +using Umbraco.Core.Composing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + public class BackOfficeSectionCollectionBuilder : OrderedCollectionBuilderBase + { + protected override BackOfficeSectionCollectionBuilder This => this; + } +} diff --git a/src/Umbraco.Web/Trees/ContentBackOfficeSection.cs b/src/Umbraco.Web/Trees/ContentBackOfficeSection.cs new file mode 100644 index 0000000000..0109a6916d --- /dev/null +++ b/src/Umbraco.Web/Trees/ContentBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office content section + /// + public class ContentBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Content; + public string Name => "Content"; + } +} diff --git a/src/Umbraco.Web/Trees/ITree.cs b/src/Umbraco.Web/Trees/ITree.cs index 40be7338b0..f408ce5e60 100644 --- a/src/Umbraco.Web/Trees/ITree.cs +++ b/src/Umbraco.Web/Trees/ITree.cs @@ -1,5 +1,6 @@ namespace Umbraco.Web.Trees { + //fixme - we don't really use this, it is nice to have the treecontroller, attribute and ApplicationTree streamlined to implement this but it's not used public interface ITree { /// diff --git a/src/Umbraco.Web/Trees/MediaBackOfficeSection.cs b/src/Umbraco.Web/Trees/MediaBackOfficeSection.cs new file mode 100644 index 0000000000..aac4fd036f --- /dev/null +++ b/src/Umbraco.Web/Trees/MediaBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office media section + /// + public class MediaBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Media; + public string Name => "Media"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Trees/MembersBackOfficeSection.cs b/src/Umbraco.Web/Trees/MembersBackOfficeSection.cs new file mode 100644 index 0000000000..bfaead33d5 --- /dev/null +++ b/src/Umbraco.Web/Trees/MembersBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office members section + /// + public class MembersBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Members; + public string Name => "Members"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Trees/PackagesBackOfficeSection.cs b/src/Umbraco.Web/Trees/PackagesBackOfficeSection.cs new file mode 100644 index 0000000000..41f049c092 --- /dev/null +++ b/src/Umbraco.Web/Trees/PackagesBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office packages section + /// + public class PackagesBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Packages; + public string Name => "Packages"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Trees/SettingsBackOfficeSection.cs b/src/Umbraco.Web/Trees/SettingsBackOfficeSection.cs new file mode 100644 index 0000000000..623f593c30 --- /dev/null +++ b/src/Umbraco.Web/Trees/SettingsBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office settings section + /// + public class SettingsBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Settings; + public string Name => "Settings"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Trees/TranslationBackOfficeSection.cs b/src/Umbraco.Web/Trees/TranslationBackOfficeSection.cs new file mode 100644 index 0000000000..41254b3179 --- /dev/null +++ b/src/Umbraco.Web/Trees/TranslationBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office translation section + /// + public class TranslationBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Translation; + public string Name => "Translation"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Trees/TreeCollection.cs b/src/Umbraco.Web/Trees/TreeCollection.cs index c7b60dea16..51b79ce67b 100644 --- a/src/Umbraco.Web/Trees/TreeCollection.cs +++ b/src/Umbraco.Web/Trees/TreeCollection.cs @@ -16,31 +16,4 @@ namespace Umbraco.Web.Trees : base(items) { } } - - public class TreeCollectionBuilder : LazyCollectionBuilderBase - { - protected override TreeCollectionBuilder This => this; - - private readonly List _instances = new List(); - - public void AddTree(ApplicationTree tree) - { - _instances.Add(tree); - } - - protected override IEnumerable CreateItems(IFactory factory) - { - return _instances; - - //var items = base.CreateItems(factory).ToList(); - //throw new NotImplementedException(); - ////validate the items, no actions should exist that do not either expose notifications or permissions - //var invalidItems = items.Where(x => !x.CanBePermissionAssigned && !x.ShowInNotifier).ToList(); - //if (invalidItems.Count == 0) return items; - - //var invalidActions = string.Join(", ", invalidItems.Select(x => "'" + x.Alias + "'")); - //throw new InvalidOperationException($"Invalid actions {invalidActions}'. All {typeof(IAction)} implementations must be true for either {nameof(IAction.CanBePermissionAssigned)} or {nameof(IAction.ShowInNotifier)}."); - } - } - } diff --git a/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs new file mode 100644 index 0000000000..2f92e72419 --- /dev/null +++ b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using Umbraco.Core.Composing; + +namespace Umbraco.Web.Trees +{ + //fixme - how will we allow users to modify these items? they will need to be able to change the ApplicationTree's registered (i.e. sort order, section) + public class TreeCollectionBuilder : CollectionBuilderBase + { + private readonly List _instances = new List(); + + public void AddTree(ApplicationTree tree) + { + _instances.Add(tree); + } + + protected override IEnumerable CreateItems(IFactory factory) => _instances; + } +} diff --git a/src/Umbraco.Web/Trees/UsersBackOfficeSection.cs b/src/Umbraco.Web/Trees/UsersBackOfficeSection.cs new file mode 100644 index 0000000000..90a65cb508 --- /dev/null +++ b/src/Umbraco.Web/Trees/UsersBackOfficeSection.cs @@ -0,0 +1,15 @@ +using Umbraco.Core; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Models.Trees; + +namespace Umbraco.Web.Trees +{ + /// + /// Defines the back office users section + /// + public class UsersBackOfficeSection : IBackOfficeSection + { + public string Alias => Constants.Applications.Users; + public string Name => "Users"; + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 0b1603c9e3..161f6c6689 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -166,8 +166,16 @@ + + + + + + + + - + @@ -591,7 +599,7 @@ - + @@ -673,7 +681,6 @@ - @@ -970,7 +977,7 @@ - + From 77dd816c514e13c487ce6b258af0dbdde4d932cb Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:06:22 +1100 Subject: [PATCH 28/70] more cleanup --- .../UI/Pages/UmbracoEnsuredPage.cs | 14 ++--- src/Umbraco.Web/Umbraco.Web.csproj | 1 - .../_Legacy/PackageActions/addApplication.cs | 61 ------------------- 3 files changed, 6 insertions(+), 70 deletions(-) delete mode 100644 src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs diff --git a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs index 9e632eabc9..cafdfb0e04 100644 --- a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs +++ b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs @@ -29,14 +29,12 @@ namespace Umbraco.Web.UI.Pages var treeAuth = this.GetType().GetCustomAttribute(true); if (treeAuth != null) { - throw new NotImplementedException(); - - //var treeByAlias = Current.Services.ApplicationTreeService - // .GetByAlias(treeAuth.TreeAlias); - //if (treeByAlias != null) - //{ - // CurrentApp = treeByAlias.ApplicationAlias; - //} + var treeByAlias = Current.TreeService + .GetByAlias(treeAuth.TreeAlias); + if (treeByAlias != null) + { + CurrentApp = treeByAlias.ApplicationAlias; + } } } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 161f6c6689..8c1a0639c4 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -1138,7 +1138,6 @@ - diff --git a/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs b/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs deleted file mode 100644 index c6d5ba30d9..0000000000 --- a/src/Umbraco.Web/_Legacy/PackageActions/addApplication.cs +++ /dev/null @@ -1,61 +0,0 @@ -//using System; -//using System.Xml; -//using System.Xml.Linq; -//using Umbraco.Core; -//using Umbraco.Core._Legacy.PackageActions; -//using Umbraco.Web.Composing; - -//namespace Umbraco.Web._Legacy.PackageActions -//{ -// /// -// /// This class implements the IPackageAction Interface, used to execute code when packages are installed. -// /// All IPackageActions only takes a PackageName and a XmlNode as input, and executes based on the data in the xmlnode. -// /// -// public class AddApplication : IPackageAction -// { - -// #region IPackageAction Members - -// /// -// /// Installs a new application in umbraco. -// /// -// /// Name of the package. -// /// The XML data. -// /// -// /// -// /// -// /// true if successfull -// public bool Execute(string packageName, XElement xmlData) -// { -// string name = xmlData.AttributeValue("appName"); -// string alias = xmlData.AttributeValue("appAlias"); -// string icon = xmlData.AttributeValue("appIcon"); - -// Current.Services.SectionService.MakeNew(name, alias, icon); - -// return true; -// } - -// public bool Undo(string packageName, XElement xmlData) -// { -// string alias = xmlData.AttributeValue("appAlias"); -// var section = Current.Services.SectionService.GetByAlias(alias); -// if (section != null) -// { -// Current.Services.SectionService.DeleteSection(section); -// } -// return true; -// } -// /// -// /// Action alias. -// /// -// /// -// public string Alias() -// { -// return "addApplication"; -// } - -// #endregion - -// } -//} From 9df1773b78d38a3ff59c65193702ef7e3ba73cfe Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:08:58 +1100 Subject: [PATCH 29/70] more cleanup --- build/NuSpecs/UmbracoCms.nuspec | 2 -- src/Umbraco.Core/Composing/TypeLoader.cs | 4 +-- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 11 ------ .../config/applications.Release.config | 11 ------ src/Umbraco.Web.UI/config/applications.config | 11 ------ .../config/trees.Release.config | 34 ------------------ src/Umbraco.Web.UI/config/trees.config | 36 ------------------- 7 files changed, 1 insertion(+), 108 deletions(-) delete mode 100644 src/Umbraco.Web.UI/config/applications.Release.config delete mode 100644 src/Umbraco.Web.UI/config/applications.config delete mode 100644 src/Umbraco.Web.UI/config/trees.Release.config delete mode 100644 src/Umbraco.Web.UI/config/trees.config diff --git a/build/NuSpecs/UmbracoCms.nuspec b/build/NuSpecs/UmbracoCms.nuspec index 3cb3d0d875..a188377c19 100644 --- a/build/NuSpecs/UmbracoCms.nuspec +++ b/build/NuSpecs/UmbracoCms.nuspec @@ -52,10 +52,8 @@ - - diff --git a/src/Umbraco.Core/Composing/TypeLoader.cs b/src/Umbraco.Core/Composing/TypeLoader.cs index acb12ab575..4c4139848d 100644 --- a/src/Umbraco.Core/Composing/TypeLoader.cs +++ b/src/Umbraco.Core/Composing/TypeLoader.cs @@ -185,9 +185,7 @@ namespace Umbraco.Core.Composing // the app code folder and everything in it new Tuple(new DirectoryInfo(IOHelper.MapPath("~/App_Code")), false), // global.asax (the app domain also monitors this, if it changes will do a full restart) - new Tuple(new FileInfo(IOHelper.MapPath("~/global.asax")), false), - // trees.config - use the contents to create the hash since this gets resaved on every app startup! - new Tuple(new FileInfo(IOHelper.MapPath(SystemDirectories.Config + "/trees.config")), true) + new Tuple(new FileInfo(IOHelper.MapPath("~/global.asax")), false) }, _logger); return _currentAssembliesHash; diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index c21bf7fef6..778ab188cd 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -241,9 +241,6 @@ umbracoSettings.config Designer - - trees.config - tinyMceConfig.config Designer @@ -301,14 +298,6 @@ - - - Designer - - - applications.config - Designer - diff --git a/src/Umbraco.Web.UI/config/applications.Release.config b/src/Umbraco.Web.UI/config/applications.Release.config deleted file mode 100644 index 5c8dee3b8a..0000000000 --- a/src/Umbraco.Web.UI/config/applications.Release.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/config/applications.config b/src/Umbraco.Web.UI/config/applications.config deleted file mode 100644 index 5c8dee3b8a..0000000000 --- a/src/Umbraco.Web.UI/config/applications.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/config/trees.Release.config b/src/Umbraco.Web.UI/config/trees.Release.config deleted file mode 100644 index bd75e97c38..0000000000 --- a/src/Umbraco.Web.UI/config/trees.Release.config +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/config/trees.config b/src/Umbraco.Web.UI/config/trees.config deleted file mode 100644 index 5892545682..0000000000 --- a/src/Umbraco.Web.UI/config/trees.config +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 1a734141f18a6e25493e1b6fef7ab0188b5ec3d6 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:31:29 +1100 Subject: [PATCH 30/70] Allows package manifest to declare a section --- src/Umbraco.Core/Manifest/ManifestParser.cs | 7 +++- src/Umbraco.Core/Manifest/PackageManifest.cs | 7 ++++ .../Manifest/ManifestParserTests.cs | 18 ++++++++++ src/Umbraco.Web/Services/SectionService.cs | 13 ------- .../Trees/BackOfficeSectionCollection.cs | 1 + .../BackOfficeSectionCollectionBuilder.cs | 35 ++++++++++++++++++- 6 files changed, 66 insertions(+), 15 deletions(-) diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index 59753df66a..28493fe20f 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -101,6 +101,7 @@ namespace Umbraco.Core.Manifest var gridEditors = new List(); var contentApps = new List(); var dashboards = new List(); + var sections = new Dictionary(); foreach (var manifest in manifests) { @@ -111,6 +112,9 @@ namespace Umbraco.Core.Manifest if (manifest.GridEditors != null) gridEditors.AddRange(manifest.GridEditors); if (manifest.ContentApps != null) contentApps.AddRange(manifest.ContentApps); if (manifest.Dashboards != null) dashboards.AddRange(manifest.Dashboards); + if (manifest.Sections != null) + foreach (var (key, value) in manifest.Sections) + sections[key] = value; } return new PackageManifest @@ -121,7 +125,8 @@ namespace Umbraco.Core.Manifest ParameterEditors = parameterEditors.ToArray(), GridEditors = gridEditors.ToArray(), ContentApps = contentApps.ToArray(), - Dashboards = dashboards.ToArray() + Dashboards = dashboards.ToArray(), + Sections = sections }; } diff --git a/src/Umbraco.Core/Manifest/PackageManifest.cs b/src/Umbraco.Core/Manifest/PackageManifest.cs index cd806ac847..a0546f3629 100644 --- a/src/Umbraco.Core/Manifest/PackageManifest.cs +++ b/src/Umbraco.Core/Manifest/PackageManifest.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Newtonsoft.Json; using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.PropertyEditors; @@ -30,5 +31,11 @@ namespace Umbraco.Core.Manifest [JsonProperty("dashboards")] public ManifestDashboardDefinition[] Dashboards { get; set; } = Array.Empty(); + + /// + /// Declares the back office sections that this package installs + /// + [JsonProperty("sections")] + public IReadOnlyDictionary Sections { get; set; } = new Dictionary(); } } diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index ce3d1d705c..9970d5f6b0 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -429,5 +429,23 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2 Assert.AreEqual(1, db1.Sections.Length); Assert.AreEqual("forms", db1.Sections[0]); } + + [Test] + public void CanParseManifest_Sections() + { + const string json = @"{'sections': { + 'content': 'Content', + 'hello': 'World' + } +}"; + + var manifest = _parser.ParseManifest(json); + Assert.AreEqual(2, manifest.Sections.Count); + Assert.AreEqual("content", manifest.Sections.Keys.ElementAt(0)); + Assert.AreEqual("hello", manifest.Sections.Keys.ElementAt(1)); + Assert.AreEqual("Content", manifest.Sections["content"]); + Assert.AreEqual("World", manifest.Sections["hello"]); + + } } } diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index e6af27534c..b17b9f965a 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -1,22 +1,9 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Xml.Linq; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Events; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.ContentEditing; -using Umbraco.Core.Scoping; using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Trees; using Umbraco.Web.Trees; -using File = System.IO.File; namespace Umbraco.Web.Services { diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs index 54762e73d8..fdeb812363 100644 --- a/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollection.cs @@ -11,5 +11,6 @@ namespace Umbraco.Web.Trees public BackOfficeSectionCollection(IEnumerable items) : base(items) { } + } } diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs index 62d61a4090..ec5833f79c 100644 --- a/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs @@ -1,10 +1,43 @@ -using Umbraco.Core.Composing; +using System.Collections.Generic; +using System.Linq; +using Umbraco.Core.Composing; +using Umbraco.Core.Manifest; +using Umbraco.Core.Models.ContentEditing; using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Trees { + //fixme: how can a developer re-sort the items in this collection ? public class BackOfficeSectionCollectionBuilder : OrderedCollectionBuilderBase { protected override BackOfficeSectionCollectionBuilder This => this; + + // need to inject dependencies in the collection, so override creation + public override BackOfficeSectionCollection CreateCollection(IFactory factory) + { + return new BackOfficeSectionCollection(CreateItems(factory)); + } + + protected override IEnumerable CreateItems(IFactory factory) + { + // get the manifest parser just-in-time - injecting it in the ctor would mean that + // simply getting the builder in order to configure the collection, would require + // its dependencies too, and that can create cycles or other oddities + var manifestParser = factory.GetInstance(); + + return base.CreateItems(factory).Concat(manifestParser.Manifest.Sections.Select(x => new ManifestBackOfficeSection(x.Key, x.Value))); + } + + private class ManifestBackOfficeSection : IBackOfficeSection + { + public ManifestBackOfficeSection(string @alias, string name) + { + Alias = alias; + Name = name; + } + + public string Alias { get; } + public string Name { get; } + } } } From 356209e013f93cf9b7b890a3c7067ce6830dac42 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:33:38 +1100 Subject: [PATCH 31/70] renames ApplicationTree to just Tree --- src/Umbraco.Web/Editors/EntityController.cs | 2 +- src/Umbraco.Web/Runtime/WebRuntimeComposer.cs | 2 +- src/Umbraco.Web/Services/ITreeService.cs | 8 ++++---- src/Umbraco.Web/Services/TreeService.cs | 14 +++++++------- src/Umbraco.Web/Trees/ApplicationTreeController.cs | 8 ++++---- .../Trees/{ApplicationTree.cs => Tree.cs} | 4 ++-- src/Umbraco.Web/Trees/TreeCollection.cs | 4 ++-- src/Umbraco.Web/Trees/TreeCollectionBuilder.cs | 8 ++++---- src/Umbraco.Web/Trees/TreeController.cs | 2 +- src/Umbraco.Web/Umbraco.Web.csproj | 2 +- 10 files changed, 27 insertions(+), 27 deletions(-) rename src/Umbraco.Web/Trees/{ApplicationTree.cs => Tree.cs} (91%) diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index ca1a6a12bb..e376f9ad5b 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -148,7 +148,7 @@ namespace Umbraco.Web.Editors var searchableTreeAttribute = searchableTree.Value.SearchableTree.GetType().GetCustomAttribute(false); - result[ApplicationTree.GetRootNodeDisplayName(tree, Services.TextService)] = new TreeSearchResult + result[Tree.GetRootNodeDisplayName(tree, Services.TextService)] = new TreeSearchResult { Results = searchableTree.Value.SearchableTree.Search(query, 200, 0, out var total), TreeAlias = searchableTree.Key, diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs index 134ed7b1d0..f21c040a37 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs @@ -211,7 +211,7 @@ namespace Umbraco.Web.Runtime { var attribute = treeControllerType.GetCustomAttribute(false); if (attribute == null) continue; - var tree = new ApplicationTree(attribute.SortOrder, attribute.ApplicationAlias, attribute.TreeAlias, attribute.TreeTitle, treeControllerType, attribute.IsSingleNodeTree); + var tree = new Tree(attribute.SortOrder, attribute.ApplicationAlias, attribute.TreeAlias, attribute.TreeTitle, treeControllerType, attribute.IsSingleNodeTree); composition.WithCollectionBuilder().AddTree(tree); } } diff --git a/src/Umbraco.Web/Services/ITreeService.cs b/src/Umbraco.Web/Services/ITreeService.cs index 17998ae1a7..5172e4b7b7 100644 --- a/src/Umbraco.Web/Services/ITreeService.cs +++ b/src/Umbraco.Web/Services/ITreeService.cs @@ -15,27 +15,27 @@ namespace Umbraco.Web.Services /// /// The tree alias. /// An ApplicationTree instance - ApplicationTree GetByAlias(string treeAlias); + Tree GetByAlias(string treeAlias); /// /// Gets all applicationTrees registered in umbraco from the umbracoAppTree table.. /// /// Returns a ApplicationTree Array - IEnumerable GetAll(); + IEnumerable GetAll(); /// /// Gets the application tree for the applcation with the specified alias /// /// The application alias. /// Returns a ApplicationTree Array - IEnumerable GetApplicationTrees(string applicationAlias); + IEnumerable GetApplicationTrees(string applicationAlias); /// /// Gets the grouped application trees for the application with the specified alias /// /// /// - IDictionary> GetGroupedApplicationTrees(string applicationAlias); + IDictionary> GetGroupedApplicationTrees(string applicationAlias); } } diff --git a/src/Umbraco.Web/Services/TreeService.cs b/src/Umbraco.Web/Services/TreeService.cs index 670f57ce49..8389c27a19 100644 --- a/src/Umbraco.Web/Services/TreeService.cs +++ b/src/Umbraco.Web/Services/TreeService.cs @@ -18,29 +18,29 @@ namespace Umbraco.Web.Services } /// - public ApplicationTree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.TreeAlias == treeAlias); + public Tree GetByAlias(string treeAlias) => _treeCollection.FirstOrDefault(t => t.TreeAlias == treeAlias); /// - public IEnumerable GetAll() => _treeCollection; + public IEnumerable GetAll() => _treeCollection; /// - public IEnumerable GetApplicationTrees(string applicationAlias) + public IEnumerable GetApplicationTrees(string applicationAlias) => GetAll().Where(x => x.ApplicationAlias.InvariantEquals(applicationAlias)).OrderBy(x => x.SortOrder).ToList(); - public IDictionary> GetGroupedApplicationTrees(string applicationAlias) + public IDictionary> GetGroupedApplicationTrees(string applicationAlias) { - var result = new Dictionary>(); + var result = new Dictionary>(); var foundTrees = GetApplicationTrees(applicationAlias).ToList(); foreach(var treeGroup in _groupedTrees.Value) { - List resultGroup = null; + List resultGroup = null; foreach(var tree in foundTrees) { foreach(var treeAliasInGroup in treeGroup) { if (tree.TreeAlias != treeAliasInGroup) continue; - if (resultGroup == null) resultGroup = new List(); + if (resultGroup == null) resultGroup = new List(); resultGroup.Add(tree); } } diff --git a/src/Umbraco.Web/Trees/ApplicationTreeController.cs b/src/Umbraco.Web/Trees/ApplicationTreeController.cs index 0e405ca3f3..5a0f72c8dc 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web/Trees/ApplicationTreeController.cs @@ -160,7 +160,7 @@ namespace Umbraco.Web.Trees /// /// /// - private async Task GetRootForMultipleAppTree(ApplicationTree tree, FormDataCollection queryStrings) + private async Task GetRootForMultipleAppTree(Tree tree, FormDataCollection queryStrings) { if (tree == null) throw new ArgumentNullException(nameof(tree)); try @@ -189,7 +189,7 @@ namespace Umbraco.Web.Trees /// /// /// - private async Task GetRootForSingleAppTree(ApplicationTree tree, string id, FormDataCollection queryStrings, string application) + private async Task GetRootForSingleAppTree(Tree tree, string id, FormDataCollection queryStrings, string application) { var rootId = Constants.System.Root.ToString(CultureInfo.InvariantCulture); if (tree == null) throw new ArgumentNullException(nameof(tree)); @@ -234,7 +234,7 @@ namespace Umbraco.Web.Trees /// /// This ensures that authorization filters are applied to the sub request /// - private async Task> TryGetRootNodeFromControllerTree(ApplicationTree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) + private async Task> TryGetRootNodeFromControllerTree(Tree appTree, FormDataCollection formCollection, HttpControllerContext controllerContext) { //instantiate it, since we are proxying, we need to setup the instance with our current context var instance = (TreeController)DependencyResolver.Current.GetService(appTree.TreeControllerType); @@ -290,7 +290,7 @@ namespace Umbraco.Web.Trees /// /// /// - private Attempt TryLoadFromControllerTree(ApplicationTree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) + private Attempt TryLoadFromControllerTree(Tree appTree, string id, FormDataCollection formCollection, HttpControllerContext controllerContext) { // instantiate it, since we are proxying, we need to setup the instance with our current context var instance = (TreeController)DependencyResolver.Current.GetService(appTree.TreeControllerType); diff --git a/src/Umbraco.Web/Trees/ApplicationTree.cs b/src/Umbraco.Web/Trees/Tree.cs similarity index 91% rename from src/Umbraco.Web/Trees/ApplicationTree.cs rename to src/Umbraco.Web/Trees/Tree.cs index 5ed9847be3..3bac5bae58 100644 --- a/src/Umbraco.Web/Trees/ApplicationTree.cs +++ b/src/Umbraco.Web/Trees/Tree.cs @@ -6,9 +6,9 @@ using Umbraco.Web.Models.Trees; namespace Umbraco.Web.Trees { [DebuggerDisplay("Tree - {TreeAlias} ({ApplicationAlias})")] - public class ApplicationTree : ITree + public class Tree : ITree { - public ApplicationTree(int sortOrder, string applicationAlias, string alias, string title, Type treeControllerType, bool isSingleNodeTree) + public Tree(int sortOrder, string applicationAlias, string alias, string title, Type treeControllerType, bool isSingleNodeTree) { SortOrder = sortOrder; ApplicationAlias = applicationAlias; diff --git a/src/Umbraco.Web/Trees/TreeCollection.cs b/src/Umbraco.Web/Trees/TreeCollection.cs index 51b79ce67b..a7bfe52295 100644 --- a/src/Umbraco.Web/Trees/TreeCollection.cs +++ b/src/Umbraco.Web/Trees/TreeCollection.cs @@ -10,9 +10,9 @@ using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Trees { - public class TreeCollection : BuilderCollectionBase + public class TreeCollection : BuilderCollectionBase { - public TreeCollection(IEnumerable items) + public TreeCollection(IEnumerable items) : base(items) { } } diff --git a/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs index 2f92e72419..143b8e308b 100644 --- a/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs +++ b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs @@ -4,15 +4,15 @@ using Umbraco.Core.Composing; namespace Umbraco.Web.Trees { //fixme - how will we allow users to modify these items? they will need to be able to change the ApplicationTree's registered (i.e. sort order, section) - public class TreeCollectionBuilder : CollectionBuilderBase + public class TreeCollectionBuilder : CollectionBuilderBase { - private readonly List _instances = new List(); + private readonly List _instances = new List(); - public void AddTree(ApplicationTree tree) + public void AddTree(Tree tree) { _instances.Add(tree); } - protected override IEnumerable CreateItems(IFactory factory) => _instances; + protected override IEnumerable CreateItems(IFactory factory) => _instances; } } diff --git a/src/Umbraco.Web/Trees/TreeController.cs b/src/Umbraco.Web/Trees/TreeController.cs index 63e8f5aad5..553cda255e 100644 --- a/src/Umbraco.Web/Trees/TreeController.cs +++ b/src/Umbraco.Web/Trees/TreeController.cs @@ -28,7 +28,7 @@ namespace Umbraco.Web.Trees } /// - public override string RootNodeDisplayName => ApplicationTree.GetRootNodeDisplayName(this, Services.TextService); + public override string RootNodeDisplayName => Tree.GetRootNodeDisplayName(this, Services.TextService); /// public override string TreeAlias => _attribute.TreeAlias; diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 8c1a0639c4..23cbb7a416 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -174,7 +174,7 @@ - + From 6b9ba3c53c806b2943f531bb71e0fc247ee243e3 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:50:59 +1100 Subject: [PATCH 32/70] Fixing tests --- src/Umbraco.Tests/Services/SectionServiceTests.cs | 9 +++------ src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 11 +++++++++++ src/Umbraco.Web/Services/SectionService.cs | 4 ++-- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/Umbraco.Tests/Services/SectionServiceTests.cs b/src/Umbraco.Tests/Services/SectionServiceTests.cs index 9211755251..87fcde34ad 100644 --- a/src/Umbraco.Tests/Services/SectionServiceTests.cs +++ b/src/Umbraco.Tests/Services/SectionServiceTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using System.Linq; using System.Threading; +using Umbraco.Core.Composing; using Umbraco.Core.Models.Membership; using Umbraco.Tests.Testing; using Umbraco.Web.Services; @@ -15,15 +16,11 @@ namespace Umbraco.Tests.Services [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] public class SectionServiceTests : TestWithSomeContentBase { - //fixme - private ISectionService SectionService => new SectionService(ServiceContext.UserService, null); - + private ISectionService SectionService => Factory.GetInstance(); [Test] public void SectionService_Can_Get_Allowed_Sections_For_User() { - //fixme - need to mock - // Arrange var user = CreateTestUser(); @@ -60,7 +57,7 @@ namespace Umbraco.Tests.Services Name = "Group B" }; userGroupB.AddAllowedSection("settings"); - userGroupB.AddAllowedSection("developer"); + userGroupB.AddAllowedSection("member"); ServiceContext.UserService.Save(userGroupB, new[] { user.Id }, false); return ServiceContext.UserService.GetUserById(user.Id); diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 0a0999f2dc..ace50917ba 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -40,6 +40,7 @@ using Umbraco.Web.Composing.Composers; using Umbraco.Web.ContentApps; using Current = Umbraco.Core.Composing.Current; using Umbraco.Web.Routing; +using Umbraco.Web.Trees; namespace Umbraco.Tests.Testing { @@ -216,6 +217,16 @@ namespace Umbraco.Tests.Testing Composition.WithCollectionBuilder(); Composition.RegisterUnique(); Composition.RegisterUnique(); + + // register back office sections in the order we want them rendered + Composition.WithCollectionBuilder().Append() + .Append() + .Append() + .Append() + .Append() + .Append() + .Append(); + Composition.RegisterUnique(); } protected virtual void ComposeWtf() diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index b17b9f965a..089bdc5bd3 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -16,8 +16,8 @@ namespace Umbraco.Web.Services IUserService userService, BackOfficeSectionCollection sectionCollection) { - _userService = userService; - _sectionCollection = sectionCollection; + _userService = userService ?? throw new ArgumentNullException(nameof(userService)); + _sectionCollection = sectionCollection ?? throw new ArgumentNullException(nameof(sectionCollection)); } /// From 3f89558ddbc3d37081eb50ce5360f476839499ed Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 17:51:38 +1100 Subject: [PATCH 33/70] Fixing tests --- src/Umbraco.Tests/Composing/TypeFinderTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Tests/Composing/TypeFinderTests.cs b/src/Umbraco.Tests/Composing/TypeFinderTests.cs index 49c807b19f..2b9474310b 100644 --- a/src/Umbraco.Tests/Composing/TypeFinderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeFinderTests.cs @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Composing Assert.AreEqual(0, typesFound.Count()); // 0 classes in _assemblies are marked with [Tree] typesFound = TypeFinder.FindClassesWithAttribute(new[] { typeof (UmbracoContext).Assembly }); - Assert.AreEqual(22, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] + Assert.AreEqual(21, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] } private static IProfilingLogger GetTestProfilingLogger() From 67e47038217be35969e982195974c5441a518e65 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 17 Jan 2019 08:34:29 +0100 Subject: [PATCH 34/70] CacheHelper becomes AppCaches --- .../Cache/{CacheHelper.cs => AppCaches.cs} | 12 +++--- src/Umbraco.Core/Cache/CacheRefresherBase.cs | 10 ++--- .../Cache/JsonCacheRefresherBase.cs | 4 +- .../Cache/PayloadCacheRefresherBase.cs | 4 +- .../Cache/TypedCacheRefresherBase.cs | 6 +-- .../Composing/Composers/ServicesComposer.cs | 2 +- .../Composing/CompositionExtensions.cs | 4 +- src/Umbraco.Core/Composing/Current.cs | 4 +- .../Implement/AuditEntryRepository.cs | 2 +- .../Repositories/Implement/AuditRepository.cs | 2 +- .../Implement/ConsentRepository.cs | 2 +- .../Implement/ContentRepositoryBase.cs | 2 +- .../Implement/ContentTypeRepository.cs | 2 +- .../Implement/ContentTypeRepositoryBase.cs | 2 +- .../Implement/DataTypeContainerRepository.cs | 2 +- .../Implement/DataTypeRepository.cs | 2 +- .../Implement/DictionaryRepository.cs | 6 +-- .../Implement/DocumentBlueprintRepository.cs | 4 +- .../Implement/DocumentRepository.cs | 14 +++---- .../DocumentTypeContainerRepository.cs | 2 +- .../Implement/DomainRepository.cs | 2 +- .../Implement/EntityContainerRepository.cs | 2 +- .../Implement/ExternalLoginRepository.cs | 2 +- .../Implement/LanguageRepository.cs | 2 +- .../Repositories/Implement/MacroRepository.cs | 2 +- .../Repositories/Implement/MediaRepository.cs | 4 +- .../Implement/MediaTypeContainerRepository.cs | 2 +- .../Implement/MediaTypeRepository.cs | 2 +- .../Implement/MemberGroupRepository.cs | 2 +- .../Implement/MemberRepository.cs | 2 +- .../Implement/MemberTypeRepository.cs | 2 +- .../Implement/NPocoRepositoryBase.cs | 2 +- .../Implement/PermissionRepository.cs | 2 +- .../Implement/PublicAccessRepository.cs | 2 +- .../Implement/RedirectUrlRepository.cs | 2 +- .../Implement/RelationRepository.cs | 2 +- .../Implement/RelationTypeRepository.cs | 2 +- .../Implement/RepositoryBaseOfTIdTEntity.cs | 6 +-- .../Implement/ServerRegistrationRepository.cs | 2 +- .../Implement/SimpleGetRepository.cs | 2 +- .../Repositories/Implement/TagRepository.cs | 2 +- .../Implement/TemplateRepository.cs | 2 +- .../Implement/UserGroupRepository.cs | 10 ++--- .../Repositories/Implement/UserRepository.cs | 10 ++--- src/Umbraco.Core/Runtime/CoreRuntime.cs | 4 +- src/Umbraco.Core/Umbraco.Core.csproj | 2 +- src/Umbraco.Tests/Macros/MacroTests.cs | 2 +- .../Models/Mapping/AutoMapperTests.cs | 2 +- .../Repositories/ContentTypeRepositoryTest.cs | 12 +++--- .../DataTypeDefinitionRepositoryTest.cs | 2 +- .../Repositories/DocumentRepositoryTest.cs | 28 ++++++------- .../Repositories/DomainRepositoryTest.cs | 12 +++--- .../Repositories/LanguageRepositoryTest.cs | 2 +- .../Repositories/MacroRepositoryTest.cs | 36 ++++++++--------- .../Repositories/MediaRepositoryTest.cs | 14 +++---- .../Repositories/MediaTypeRepositoryTest.cs | 4 +- .../Repositories/MemberRepositoryTest.cs | 8 ++-- .../Repositories/MemberTypeRepositoryTest.cs | 2 +- .../PublicAccessRepositoryTest.cs | 24 +++++------ .../RedirectUrlRepositoryTests.cs | 2 +- .../Repositories/RelationRepositoryTest.cs | 4 +- .../RelationTypeRepositoryTest.cs | 4 +- .../ServerRegistrationRepositoryTest.cs | 4 +- .../Repositories/TagRepositoryTest.cs | 18 ++++----- .../Repositories/TemplateRepositoryTest.cs | 10 ++--- .../Repositories/UserGroupRepositoryTest.cs | 4 +- .../Repositories/UserRepositoryTest.cs | 22 +++++----- .../Routing/RenderRouteHandlerTests.cs | 2 +- src/Umbraco.Tests/Runtimes/StandaloneTests.cs | 4 +- .../Scoping/ScopedRepositoryTests.cs | 4 +- .../Services/ContentServicePerformanceTest.cs | 40 +++++++++---------- .../Services/ContentServiceTests.cs | 10 ++--- .../Services/MacroServiceTests.cs | 2 +- .../Templates/TemplateRepositoryTests.cs | 2 +- .../TestControllerActivatorBase.cs | 2 +- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 2 +- .../Testing/TestingTests/MockTests.cs | 4 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 6 +-- .../Web/Mvc/SurfaceControllerTests.cs | 4 +- .../Cache/ApplicationCacheRefresher.cs | 8 ++-- .../Cache/ApplicationTreeCacheRefresher.cs | 8 ++-- .../Cache/ContentCacheRefresher.cs | 20 +++++----- .../Cache/ContentTypeCacheRefresher.cs | 10 ++--- .../Cache/DataTypeCacheRefresher.cs | 6 +-- .../Cache/DictionaryCacheRefresher.cs | 4 +- src/Umbraco.Web/Cache/DomainCacheRefresher.cs | 4 +- .../Cache/LanguageCacheRefresher.cs | 4 +- src/Umbraco.Web/Cache/MacroCacheRefresher.cs | 16 ++++---- src/Umbraco.Web/Cache/MediaCacheRefresher.cs | 10 ++--- src/Umbraco.Web/Cache/MemberCacheRefresher.cs | 12 +++--- .../Cache/MemberGroupCacheRefresher.cs | 6 +-- .../Cache/PublicAccessCacheRefresher.cs | 4 +- .../Cache/RelationTypeCacheRefresher.cs | 8 ++-- .../Cache/TemplateCacheRefresher.cs | 6 +-- src/Umbraco.Web/Cache/UserCacheRefresher.cs | 6 +-- .../Cache/UserGroupCacheRefresher.cs | 8 ++-- .../UserGroupPermissionsCacheRefresher.cs | 4 +- src/Umbraco.Web/CacheHelperExtensions.cs | 12 +++--- src/Umbraco.Web/Composing/Current.cs | 2 +- .../Controllers/UmbLoginController.cs | 2 +- .../Controllers/UmbLoginStatusController.cs | 2 +- .../Controllers/UmbProfileController.cs | 2 +- .../Controllers/UmbRegisterController.cs | 2 +- .../Editors/AuthenticationController.cs | 2 +- .../Editors/BackOfficeController.cs | 2 +- .../Editors/ContentTypeController.cs | 2 +- .../Editors/ContentTypeControllerBase.cs | 2 +- .../Editors/DashboardController.cs | 2 +- .../Editors/MediaTypeController.cs | 2 +- .../Editors/MemberTypeController.cs | 2 +- .../Editors/PackageInstallController.cs | 2 +- .../UmbracoAuthorizedJsonController.cs | 2 +- src/Umbraco.Web/Mvc/PluginController.cs | 6 +-- src/Umbraco.Web/Mvc/RenderMvcController.cs | 2 +- src/Umbraco.Web/Mvc/SurfaceController.cs | 2 +- .../Mvc/UmbracoAuthorizedController.cs | 2 +- src/Umbraco.Web/Mvc/UmbracoController.cs | 6 +-- .../Mvc/UmbracoViewPageOfTModel.cs | 6 +-- src/Umbraco.Web/Runtime/WebRuntime.cs | 2 +- src/Umbraco.Web/Security/MembershipHelper.cs | 4 +- .../Services/ApplicationTreeService.cs | 4 +- src/Umbraco.Web/Services/SectionService.cs | 4 +- src/Umbraco.Web/TagsController.cs | 2 +- .../WebApi/UmbracoApiController.cs | 2 +- .../WebApi/UmbracoApiControllerBase.cs | 6 +-- .../WebApi/UmbracoAuthorizedApiController.cs | 2 +- 126 files changed, 348 insertions(+), 348 deletions(-) rename src/Umbraco.Core/Cache/{CacheHelper.cs => AppCaches.cs} (83%) diff --git a/src/Umbraco.Core/Cache/CacheHelper.cs b/src/Umbraco.Core/Cache/AppCaches.cs similarity index 83% rename from src/Umbraco.Core/Cache/CacheHelper.cs rename to src/Umbraco.Core/Cache/AppCaches.cs index cd2225ae9d..7dd95624ef 100644 --- a/src/Umbraco.Core/Cache/CacheHelper.cs +++ b/src/Umbraco.Core/Cache/AppCaches.cs @@ -6,12 +6,12 @@ namespace Umbraco.Core.Cache /// /// Represents the application-wide caches. /// - public class CacheHelper + public class AppCaches { /// /// Initializes a new instance for use in the web /// - public CacheHelper() + public AppCaches() : this( new HttpRuntimeCacheProvider(HttpRuntime.Cache), new StaticCacheProvider(), @@ -23,7 +23,7 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance for use in the web /// - public CacheHelper(System.Web.Caching.Cache cache) + public AppCaches(System.Web.Caching.Cache cache) : this( new HttpRuntimeCacheProvider(cache), new StaticCacheProvider(), @@ -35,7 +35,7 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance based on the provided providers /// - public CacheHelper( + public AppCaches( IRuntimeCacheProvider httpCacheProvider, ICacheProvider staticCacheProvider, ICacheProvider requestCacheProvider, @@ -54,7 +54,7 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies apply, but the underlying caches do not cache anything. /// Used by tests. /// - public static CacheHelper Disabled { get; } = new CacheHelper(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches Disabled { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); /// /// Gets the special no-cache instance. @@ -63,7 +63,7 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies are bypassed. /// Used by repositories that do no cache. /// - public static CacheHelper NoCache { get; } = new CacheHelper(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches NoCache { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); /// /// Returns the current Request cache diff --git a/src/Umbraco.Core/Cache/CacheRefresherBase.cs b/src/Umbraco.Core/Cache/CacheRefresherBase.cs index 7242ab225e..5e6ec593af 100644 --- a/src/Umbraco.Core/Cache/CacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/CacheRefresherBase.cs @@ -16,10 +16,10 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance of the . /// - /// A cache helper. - protected CacheRefresherBase(CacheHelper cacheHelper) + /// A cache helper. + protected CacheRefresherBase(AppCaches appCaches) { - CacheHelper = cacheHelper; + AppCaches = appCaches; } /// @@ -93,7 +93,7 @@ namespace Umbraco.Core.Cache /// /// Gets the cache helper. /// - protected CacheHelper CacheHelper { get; } + protected AppCaches AppCaches { get; } /// /// Clears the cache for all repository entities of a specified type. @@ -102,7 +102,7 @@ namespace Umbraco.Core.Cache protected void ClearAllIsolatedCacheByEntityType() where TEntity : class, IEntity { - CacheHelper.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedRuntimeCache.ClearCache(); } /// diff --git a/src/Umbraco.Core/Cache/JsonCacheRefresherBase.cs b/src/Umbraco.Core/Cache/JsonCacheRefresherBase.cs index 27302f0786..d9d9644a36 100644 --- a/src/Umbraco.Core/Cache/JsonCacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/JsonCacheRefresherBase.cs @@ -13,8 +13,8 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance of the . /// - /// A cache helper. - protected JsonCacheRefresherBase(CacheHelper cacheHelper) : base(cacheHelper) + /// A cache helper. + protected JsonCacheRefresherBase(AppCaches appCaches) : base(appCaches) { } /// diff --git a/src/Umbraco.Core/Cache/PayloadCacheRefresherBase.cs b/src/Umbraco.Core/Cache/PayloadCacheRefresherBase.cs index 22bc46e020..4a3a03a0d6 100644 --- a/src/Umbraco.Core/Cache/PayloadCacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/PayloadCacheRefresherBase.cs @@ -15,8 +15,8 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance of the . /// - /// A cache helper. - protected PayloadCacheRefresherBase(CacheHelper cacheHelper) : base(cacheHelper) + /// A cache helper. + protected PayloadCacheRefresherBase(AppCaches appCaches) : base(appCaches) { } #region Json diff --git a/src/Umbraco.Core/Cache/TypedCacheRefresherBase.cs b/src/Umbraco.Core/Cache/TypedCacheRefresherBase.cs index 4defc15482..0b5a04b571 100644 --- a/src/Umbraco.Core/Cache/TypedCacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/TypedCacheRefresherBase.cs @@ -14,9 +14,9 @@ namespace Umbraco.Core.Cache /// /// Initializes a new instance of the . /// - /// A cache helper. - protected TypedCacheRefresherBase(CacheHelper cacheHelper) - : base(cacheHelper) + /// A cache helper. + protected TypedCacheRefresherBase(AppCaches appCaches) + : base(appCaches) { } #region Refresher diff --git a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs index 8c9ccd1088..9ed4a7265c 100644 --- a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs +++ b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs @@ -116,7 +116,7 @@ namespace Umbraco.Core.Composing.Composers return new LocalizedTextServiceFileSources( container.GetInstance(), - container.GetInstance().RuntimeCache, + container.GetInstance().RuntimeCache, mainLangFolder, pluginLangFolders.Concat(userLangFolders)); } diff --git a/src/Umbraco.Core/Composing/CompositionExtensions.cs b/src/Umbraco.Core/Composing/CompositionExtensions.cs index 2307d757c9..910062688c 100644 --- a/src/Umbraco.Core/Composing/CompositionExtensions.cs +++ b/src/Umbraco.Core/Composing/CompositionExtensions.cs @@ -18,7 +18,7 @@ namespace Umbraco.Core.Composing public static void RegisterEssentials(this Composition composition, ILogger logger, IProfiler profiler, IProfilingLogger profilingLogger, IMainDom mainDom, - CacheHelper appCaches, + AppCaches appCaches, IUmbracoDatabaseFactory databaseFactory, TypeLoader typeLoader, IRuntimeState state) @@ -28,7 +28,7 @@ namespace Umbraco.Core.Composing composition.RegisterUnique(profilingLogger); composition.RegisterUnique(mainDom); composition.RegisterUnique(appCaches); - composition.RegisterUnique(factory => factory.GetInstance().RuntimeCache); + composition.RegisterUnique(factory => factory.GetInstance().RuntimeCache); composition.RegisterUnique(databaseFactory); composition.RegisterUnique(factory => factory.GetInstance().SqlContext); composition.RegisterUnique(typeLoader); diff --git a/src/Umbraco.Core/Composing/Current.cs b/src/Umbraco.Core/Composing/Current.cs index 5c8351924f..bfc5cfd51c 100644 --- a/src/Umbraco.Core/Composing/Current.cs +++ b/src/Umbraco.Core/Composing/Current.cs @@ -180,8 +180,8 @@ namespace Umbraco.Core.Composing public static ICultureDictionaryFactory CultureDictionaryFactory => Factory.GetInstance(); - public static CacheHelper ApplicationCache - => Factory.GetInstance(); + public static AppCaches ApplicationCache + => Factory.GetInstance(); public static ServiceContext Services => Factory.GetInstance(); diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/AuditEntryRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/AuditEntryRepository.cs index 77759ea2da..1486935e2a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/AuditEntryRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/AuditEntryRepository.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Initializes a new instance of the class. /// - public AuditEntryRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public AuditEntryRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/AuditRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/AuditRepository.cs index 45f083bc6b..cda89fd89a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/AuditRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/AuditRepository.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class AuditRepository : NPocoRepositoryBase, IAuditRepository { public AuditRepository(IScopeAccessor scopeAccessor, ILogger logger) - : base(scopeAccessor, CacheHelper.NoCache, logger) + : base(scopeAccessor, AppCaches.NoCache, logger) { } protected override void PersistNewItem(IAuditItem entity) diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs index 3794bf183a..bd55654809 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs @@ -20,7 +20,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Initializes a new instance of the class. /// - public ConsentRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public ConsentRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs index bd7943ff1d..ba56c17087 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs @@ -33,7 +33,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement where TEntity : class, IUmbracoEntity where TRepository : class, IRepository { - protected ContentRepositoryBase(IScopeAccessor scopeAccessor, CacheHelper cache, ILanguageRepository languageRepository, ILogger logger) + protected ContentRepositoryBase(IScopeAccessor scopeAccessor, AppCaches cache, ILanguageRepository languageRepository, ILogger logger) : base(scopeAccessor, cache, logger) { LanguageRepository = languageRepository; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepository.cs index 4bec3160a7..f608e2968d 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepository.cs @@ -19,7 +19,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly ITemplateRepository _templateRepository; - public ContentTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, ITemplateRepository templateRepository) + public ContentTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, ITemplateRepository templateRepository) : base(scopeAccessor, cache, logger) { _templateRepository = templateRepository; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index 683df047f8..6404880a2e 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -28,7 +28,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal abstract class ContentTypeRepositoryBase : NPocoRepositoryBase, IReadRepository where TEntity : class, IContentTypeComposition { - protected ContentTypeRepositoryBase(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + protected ContentTypeRepositoryBase(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeContainerRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeContainerRepository.cs index f23b6df5e2..752b641bc3 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeContainerRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeContainerRepository.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { class DataTypeContainerRepository : EntityContainerRepository, IDataTypeContainerRepository { - public DataTypeContainerRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DataTypeContainerRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger, Constants.ObjectTypes.DataTypeContainer) { } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs index 4556c78fe6..28d4262763 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -27,7 +27,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly Lazy _editors; // fixme temp fixing circular dependencies with LAZY but is this the right place? - public DataTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, Lazy editors, ILogger logger) + public DataTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, Lazy editors, ILogger logger) : base(scopeAccessor, cache, logger) { _editors = editors; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs index 8f5ad70c32..3517fb3545 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs @@ -18,7 +18,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class DictionaryRepository : NPocoRepositoryBase, IDictionaryRepository { - public DictionaryRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DictionaryRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } @@ -290,7 +290,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly DictionaryRepository _dictionaryRepository; - public DictionaryByUniqueIdRepository(DictionaryRepository dictionaryRepository, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DictionaryByUniqueIdRepository(DictionaryRepository dictionaryRepository, IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { _dictionaryRepository = dictionaryRepository; @@ -343,7 +343,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly DictionaryRepository _dictionaryRepository; - public DictionaryByKeyRepository(DictionaryRepository dictionaryRepository, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DictionaryByKeyRepository(DictionaryRepository dictionaryRepository, IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { _dictionaryRepository = dictionaryRepository; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentBlueprintRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentBlueprintRepository.cs index 1d24cfd2dc..09fa420f26 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentBlueprintRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentBlueprintRepository.cs @@ -17,8 +17,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class DocumentBlueprintRepository : DocumentRepository, IDocumentBlueprintRepository { - public DocumentBlueprintRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, ILanguageRepository languageRepository, IContentSection settings) - : base(scopeAccessor, cacheHelper, logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, settings) + public DocumentBlueprintRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, ILanguageRepository languageRepository, IContentSection settings) + : base(scopeAccessor, appCaches, logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, settings) { EnsureUniqueNaming = false; // duplicates are allowed } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs index 054ab8cb4b..31c08f9124 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs @@ -25,20 +25,20 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly IContentTypeRepository _contentTypeRepository; private readonly ITemplateRepository _templateRepository; private readonly ITagRepository _tagRepository; - private readonly CacheHelper _cacheHelper; + private readonly AppCaches _appCaches; private PermissionRepository _permissionRepository; private readonly ContentByGuidReadRepository _contentByGuidReadRepository; private readonly IScopeAccessor _scopeAccessor; - public DocumentRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, ILanguageRepository languageRepository, IContentSection settings) - : base(scopeAccessor, cacheHelper, languageRepository, logger) + public DocumentRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, ILanguageRepository languageRepository, IContentSection settings) + : base(scopeAccessor, appCaches, languageRepository, logger) { _contentTypeRepository = contentTypeRepository ?? throw new ArgumentNullException(nameof(contentTypeRepository)); _templateRepository = templateRepository ?? throw new ArgumentNullException(nameof(templateRepository)); _tagRepository = tagRepository ?? throw new ArgumentNullException(nameof(tagRepository)); - _cacheHelper = cacheHelper; + _appCaches = appCaches; _scopeAccessor = scopeAccessor; - _contentByGuidReadRepository = new ContentByGuidReadRepository(this, scopeAccessor, cacheHelper, logger); + _contentByGuidReadRepository = new ContentByGuidReadRepository(this, scopeAccessor, appCaches, logger); EnsureUniqueNaming = settings.EnsureUniqueNaming; } @@ -48,7 +48,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement // note: is ok to 'new' the repo here as it's a sub-repo really private PermissionRepository PermissionRepository => _permissionRepository - ?? (_permissionRepository = new PermissionRepository(_scopeAccessor, _cacheHelper, Logger)); + ?? (_permissionRepository = new PermissionRepository(_scopeAccessor, _appCaches, Logger)); #region Repository Base @@ -847,7 +847,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly DocumentRepository _outerRepo; - public ContentByGuidReadRepository(DocumentRepository outerRepo, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public ContentByGuidReadRepository(DocumentRepository outerRepo, IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { _outerRepo = outerRepo; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentTypeContainerRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentTypeContainerRepository.cs index de8042cfcf..d50981e036 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentTypeContainerRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentTypeContainerRepository.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { class DocumentTypeContainerRepository : EntityContainerRepository, IDocumentTypeContainerRepository { - public DocumentTypeContainerRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DocumentTypeContainerRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger, Constants.ObjectTypes.DocumentTypeContainer) { } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DomainRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DomainRepository.cs index f75d82bd4e..fa06216f9b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DomainRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DomainRepository.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class DomainRepository : NPocoRepositoryBase, IDomainRepository { - public DomainRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DomainRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/EntityContainerRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/EntityContainerRepository.cs index fae7ae2ebc..09fe949df1 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/EntityContainerRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/EntityContainerRepository.cs @@ -19,7 +19,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly Guid _containerObjectType; - public EntityContainerRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, Guid containerObjectType) + public EntityContainerRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, Guid containerObjectType) : base(scopeAccessor, cache, logger) { var allowedContainers = new[] { Constants.ObjectTypes.DocumentTypeContainer, Constants.ObjectTypes.MediaTypeContainer, Constants.ObjectTypes.DataTypeContainer }; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ExternalLoginRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ExternalLoginRepository.cs index ce9a44f595..7cb78f4c9f 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ExternalLoginRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ExternalLoginRepository.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class ExternalLoginRepository : NPocoRepositoryBase, IExternalLoginRepository { - public ExternalLoginRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public ExternalLoginRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs index e236670e74..b3f2ff4af0 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly Dictionary _codeIdMap = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _idCodeMap = new Dictionary(); - public LanguageRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public LanguageRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MacroRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MacroRepository.cs index 594f26fa72..565917e078 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MacroRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MacroRepository.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class MacroRepository : NPocoRepositoryBase, IMacroRepository { - public MacroRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MacroRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaRepository.cs index 3e665e321f..f2c7e35395 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaRepository.cs @@ -26,7 +26,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly ITagRepository _tagRepository; private readonly MediaByGuidReadRepository _mediaByGuidReadRepository; - public MediaRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, IMediaTypeRepository mediaTypeRepository, ITagRepository tagRepository, IContentSection contentSection, ILanguageRepository languageRepository) + public MediaRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IMediaTypeRepository mediaTypeRepository, ITagRepository tagRepository, IContentSection contentSection, ILanguageRepository languageRepository) : base(scopeAccessor, cache, languageRepository, logger) { _mediaTypeRepository = mediaTypeRepository ?? throw new ArgumentNullException(nameof(mediaTypeRepository)); @@ -395,7 +395,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly MediaRepository _outerRepo; - public MediaByGuidReadRepository(MediaRepository outerRepo, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MediaByGuidReadRepository(MediaRepository outerRepo, IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { _outerRepo = outerRepo; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeContainerRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeContainerRepository.cs index 318d3a9c5a..68b33e989d 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeContainerRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeContainerRepository.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { class MediaTypeContainerRepository : EntityContainerRepository, IMediaTypeContainerRepository { - public MediaTypeContainerRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MediaTypeContainerRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger, Constants.ObjectTypes.MediaTypeContainer) { } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeRepository.cs index 7dc1c29396..4639871a4a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MediaTypeRepository.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class MediaTypeRepository : ContentTypeRepositoryBase, IMediaTypeRepository { - public MediaTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MediaTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs index e80faaa44a..11166ce777 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class MemberGroupRepository : NPocoRepositoryBase, IMemberGroupRepository { - public MemberGroupRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MemberGroupRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs index bfadebd61b..2daa4abeca 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs @@ -24,7 +24,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly ITagRepository _tagRepository; private readonly IMemberGroupRepository _memberGroupRepository; - public MemberRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, IMemberTypeRepository memberTypeRepository, IMemberGroupRepository memberGroupRepository, ITagRepository tagRepository, ILanguageRepository languageRepository) + public MemberRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, IMemberTypeRepository memberTypeRepository, IMemberGroupRepository memberGroupRepository, ITagRepository tagRepository, ILanguageRepository languageRepository) : base(scopeAccessor, cache, languageRepository, logger) { _memberTypeRepository = memberTypeRepository ?? throw new ArgumentNullException(nameof(memberTypeRepository)); diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs index 023e308ad3..b81ce4010b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class MemberTypeRepository : ContentTypeRepositoryBase, IMemberTypeRepository { - public MemberTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public MemberTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/NPocoRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/NPocoRepositoryBase.cs index df7517469c..234693602f 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/NPocoRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/NPocoRepositoryBase.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Initializes a new instance of the class. /// - protected NPocoRepositoryBase(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + protected NPocoRepositoryBase(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/PermissionRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/PermissionRepository.cs index 8261ed2ea3..b4fd86c567 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/PermissionRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/PermissionRepository.cs @@ -25,7 +25,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class PermissionRepository : NPocoRepositoryBase where TEntity : class, IEntity { - public PermissionRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public PermissionRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/PublicAccessRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/PublicAccessRepository.cs index f49905573d..bd2580b38f 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/PublicAccessRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/PublicAccessRepository.cs @@ -14,7 +14,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class PublicAccessRepository : NPocoRepositoryBase, IPublicAccessRepository { - public PublicAccessRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public PublicAccessRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RedirectUrlRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RedirectUrlRepository.cs index 3ca937ffcd..baac02b6bf 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RedirectUrlRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RedirectUrlRepository.cs @@ -13,7 +13,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class RedirectUrlRepository : NPocoRepositoryBase, IRedirectUrlRepository { - public RedirectUrlRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public RedirectUrlRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RelationRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RelationRepository.cs index fb5ba00ea0..c5ba24f385 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RelationRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RelationRepository.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly IRelationTypeRepository _relationTypeRepository; public RelationRepository(IScopeAccessor scopeAccessor, ILogger logger, IRelationTypeRepository relationTypeRepository) - : base(scopeAccessor, CacheHelper.NoCache, logger) + : base(scopeAccessor, AppCaches.NoCache, logger) { _relationTypeRepository = relationTypeRepository; } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RelationTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RelationTypeRepository.cs index e4d8396e71..4faf78bd0a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RelationTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RelationTypeRepository.cs @@ -18,7 +18,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class RelationTypeRepository : NPocoRepositoryBase, IRelationTypeRepository { - public RelationTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public RelationTypeRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs index 84c76dbb53..2626f60123 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs @@ -19,7 +19,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private IRepositoryCachePolicy _cachePolicy; - protected RepositoryBase(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + protected RepositoryBase(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) { ScopeAccessor = scopeAccessor ?? throw new ArgumentNullException(nameof(scopeAccessor)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -28,7 +28,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement protected ILogger Logger { get; } - protected CacheHelper GlobalCache { get; } + protected AppCaches GlobalCache { get; } protected IRuntimeCacheProvider GlobalIsolatedCache => GlobalCache.IsolatedRuntimeCache.GetOrCreateCache(); @@ -127,7 +127,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { get { - if (GlobalCache == CacheHelper.NoCache) + if (GlobalCache == AppCaches.NoCache) return NoCacheRepositoryCachePolicy.Instance; // create the cache policy using IsolatedCache which is either global diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs index 2679f8f92f..ead7c066be 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement internal class ServerRegistrationRepository : NPocoRepositoryBase, IServerRegistrationRepository { public ServerRegistrationRepository(IScopeAccessor scopeAccessor, ILogger logger) - : base(scopeAccessor, CacheHelper.NoCache, logger) + : base(scopeAccessor, AppCaches.NoCache, logger) { } protected override IRepositoryCachePolicy CreateCachePolicy() diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/SimpleGetRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/SimpleGetRepository.cs index 7a3bfdb757..43233d0f31 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/SimpleGetRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/SimpleGetRepository.cs @@ -18,7 +18,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement where TEntity : class, IEntity where TDto: class { - protected SimpleGetRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + protected SimpleGetRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/TagRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/TagRepository.cs index 77e474be08..7dd3f03407 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/TagRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/TagRepository.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { internal class TagRepository : NPocoRepositoryBase, ITagRepository { - public TagRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public TagRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs index 19ef303ebe..bef71b1a51 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly ViewHelper _viewHelper; private readonly MasterPageHelper _masterPageHelper; - public TemplateRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, ITemplatesSection templateConfig, IFileSystems fileSystems) + public TemplateRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger, ITemplatesSection templateConfig, IFileSystems fileSystems) : base(scopeAccessor, cache, logger) { _masterpagesFileSystem = fileSystems.MasterPagesFileSystem; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/UserGroupRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/UserGroupRepository.cs index 91466a0d09..c76a5de0d0 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/UserGroupRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/UserGroupRepository.cs @@ -23,11 +23,11 @@ namespace Umbraco.Core.Persistence.Repositories.Implement private readonly UserGroupWithUsersRepository _userGroupWithUsersRepository; private readonly PermissionRepository _permissionRepository; - public UserGroupRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger) - : base(scopeAccessor, cacheHelper, logger) + public UserGroupRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger) + : base(scopeAccessor, appCaches, logger) { - _userGroupWithUsersRepository = new UserGroupWithUsersRepository(this, scopeAccessor, cacheHelper, logger); - _permissionRepository = new PermissionRepository(scopeAccessor, cacheHelper, logger); + _userGroupWithUsersRepository = new UserGroupWithUsersRepository(this, scopeAccessor, appCaches, logger); + _permissionRepository = new PermissionRepository(scopeAccessor, appCaches, logger); } public const string GetByAliasCacheKeyPrefix = "UserGroupRepository_GetByAlias_"; @@ -360,7 +360,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private readonly UserGroupRepository _userGroupRepo; - public UserGroupWithUsersRepository(UserGroupRepository userGroupRepo, IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public UserGroupWithUsersRepository(UserGroupRepository userGroupRepo, IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) : base(scopeAccessor, cache, logger) { _userGroupRepo = userGroupRepo; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs index 17fe79a55b..918cc66cb0 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/UserRepository.cs @@ -35,22 +35,22 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// Constructor /// /// - /// + /// /// /// /// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read. /// /// - public UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IGlobalSettings globalSettings) - : base(scopeAccessor, cacheHelper, logger) + public UserRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger, IMapperCollection mapperCollection, IGlobalSettings globalSettings) + : base(scopeAccessor, appCaches, logger) { _mapperCollection = mapperCollection; _globalSettings = globalSettings; } // for tests - internal UserRepository(IScopeAccessor scopeAccessor, CacheHelper cacheHelper, ILogger logger, IMapperCollection mapperCollection, IDictionary passwordConfig, IGlobalSettings globalSettings) - : base(scopeAccessor, cacheHelper, logger) + internal UserRepository(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger, IMapperCollection mapperCollection, IDictionary passwordConfig, IGlobalSettings globalSettings) + : base(scopeAccessor, appCaches, logger) { _mapperCollection = mapperCollection; _globalSettings = globalSettings; diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index 729e960896..f29109b9d2 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -325,13 +325,13 @@ namespace Umbraco.Core.Runtime /// /// Gets the application caches. /// - protected virtual CacheHelper GetAppCaches() + protected virtual AppCaches GetAppCaches() { // need the deep clone runtime cache provider to ensure entities are cached properly, ie // are cloned in and cloned out - no request-based cache here since no web-based context, // is overriden by the web runtime - return new CacheHelper( + return new AppCaches( new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), new StaticCacheProvider(), NullCacheProvider.Instance, diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 2236854351..79162c06ad 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -111,7 +111,7 @@ - + diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 984fb94fab..23e198b778 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Macros public void Setup() { //we DO want cache enabled for these tests - var cacheHelper = new CacheHelper( + var cacheHelper = new AppCaches( new ObjectCacheRuntimeCacheProvider(), new StaticCacheProvider(), NullCacheProvider.Instance, diff --git a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs index 1f7c5624bf..f48abc1233 100644 --- a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Models.Mapping base.Compose(); var manifestBuilder = new ManifestParser( - CacheHelper.Disabled.RuntimeCache, + AppCaches.Disabled.RuntimeCache, new ManifestValueValidatorCollection(Enumerable.Empty()), Composition.Logger) { diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs index aeaf76967f..34699826ad 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository) { - var cacheHelper = CacheHelper.Disabled; + var cacheHelper = AppCaches.Disabled; var templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(scopeAccessor, cacheHelper, Logger); contentTypeRepository = new ContentTypeRepository(scopeAccessor, cacheHelper, Logger, templateRepository); @@ -46,20 +46,20 @@ namespace Umbraco.Tests.Persistence.Repositories private ContentTypeRepository CreateRepository(IScopeAccessor scopeAccessor) { - var templateRepository = new TemplateRepository(scopeAccessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var contentTypeRepository = new ContentTypeRepository(scopeAccessor, CacheHelper.Disabled, Logger, templateRepository); + var templateRepository = new TemplateRepository(scopeAccessor, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var contentTypeRepository = new ContentTypeRepository(scopeAccessor, AppCaches.Disabled, Logger, templateRepository); return contentTypeRepository; } private MediaTypeRepository CreateMediaTypeRepository(IScopeAccessor scopeAccessor) { - var contentTypeRepository = new MediaTypeRepository(scopeAccessor, CacheHelper.Disabled, Logger); + var contentTypeRepository = new MediaTypeRepository(scopeAccessor, AppCaches.Disabled, Logger); return contentTypeRepository; } private EntityContainerRepository CreateContainerRepository(IScopeAccessor scopeAccessor, Guid containerEntityType) { - return new EntityContainerRepository(scopeAccessor, CacheHelper.Disabled, Logger, containerEntityType); + return new EntityContainerRepository(scopeAccessor, AppCaches.Disabled, Logger, containerEntityType); } //TODO Add test to verify SetDefaultTemplates updates both AllowedTemplates and DefaultTemplate(id). @@ -71,7 +71,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var templateRepo = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepo = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); var repository = CreateRepository((IScopeAccessor) provider); var templates = new[] { diff --git a/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs index ce871d0d0a..b9724b0770 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs @@ -25,7 +25,7 @@ namespace Umbraco.Tests.Persistence.Repositories private EntityContainerRepository CreateContainerRepository(IScopeAccessor scopeAccessor) { - return new EntityContainerRepository(scopeAccessor, CacheHelper.Disabled, Logger, Constants.ObjectTypes.DataTypeContainer); + return new EntityContainerRepository(scopeAccessor, AppCaches.Disabled, Logger, Constants.ObjectTypes.DataTypeContainer); } [Test] diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index c1fa5381ff..772147f5ad 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -43,39 +43,39 @@ namespace Umbraco.Tests.Persistence.Repositories base.TearDown(); } - private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out DataTypeRepository dtdRepository, CacheHelper cacheHelper = null) + private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out DataTypeRepository dtdRepository, AppCaches appCaches = null) { - cacheHelper = cacheHelper ?? CacheHelper; + appCaches = appCaches ?? AppCaches; TemplateRepository tr; var ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out tr); var editors = new PropertyEditorCollection(new DataEditorCollection(Enumerable.Empty())); - dtdRepository = new DataTypeRepository(scopeAccessor, cacheHelper, new Lazy(() => editors), Logger); + dtdRepository = new DataTypeRepository(scopeAccessor, appCaches, new Lazy(() => editors), Logger); return ctRepository; } - private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, CacheHelper cacheHelper = null) + private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, AppCaches appCaches = null) { TemplateRepository tr; - return CreateRepository(scopeAccessor, out contentTypeRepository, out tr, cacheHelper); + return CreateRepository(scopeAccessor, out contentTypeRepository, out tr, appCaches); } - private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository, CacheHelper cacheHelper = null) + private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository, out TemplateRepository templateRepository, AppCaches appCaches = null) { - cacheHelper = cacheHelper ?? CacheHelper; + appCaches = appCaches ?? AppCaches; - templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(scopeAccessor, cacheHelper, Logger); - contentTypeRepository = new ContentTypeRepository(scopeAccessor, cacheHelper, Logger, templateRepository); - var languageRepository = new LanguageRepository(scopeAccessor, cacheHelper, Logger); - var repository = new DocumentRepository(scopeAccessor, cacheHelper, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + templateRepository = new TemplateRepository(scopeAccessor, appCaches, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(scopeAccessor, appCaches, Logger); + contentTypeRepository = new ContentTypeRepository(scopeAccessor, appCaches, Logger, templateRepository); + var languageRepository = new LanguageRepository(scopeAccessor, appCaches, Logger); + var repository = new DocumentRepository(scopeAccessor, appCaches, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); return repository; } [Test] public void CacheActiveForIntsAndGuids() { - var realCache = new CacheHelper( + var realCache = new AppCaches( new ObjectCacheRuntimeCacheProvider(), new StaticCacheProvider(), new StaticCacheProvider(), @@ -84,7 +84,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, cacheHelper: realCache); + var repository = CreateRepository((IScopeAccessor)provider, out var contentTypeRepository, appCaches: realCache); var udb = (UmbracoDatabase)scope.Database; diff --git a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs index a5402f964e..a64a65047b 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs @@ -22,12 +22,12 @@ namespace Umbraco.Tests.Persistence.Repositories private DomainRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository, out DocumentRepository documentRepository, out LanguageRepository languageRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger); - contentTypeRepository = new ContentTypeRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, templateRepository); - languageRepository = new LanguageRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger); - documentRepository = new DocumentRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); - var domainRepository = new DomainRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger); + var templateRepository = new TemplateRepository(accessor, Core.Cache.AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(accessor, Core.Cache.AppCaches.Disabled, Logger); + contentTypeRepository = new ContentTypeRepository(accessor, Core.Cache.AppCaches.Disabled, Logger, templateRepository); + languageRepository = new LanguageRepository(accessor, Core.Cache.AppCaches.Disabled, Logger); + documentRepository = new DocumentRepository(accessor, Core.Cache.AppCaches.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + var domainRepository = new DomainRepository(accessor, Core.Cache.AppCaches.Disabled, Logger); return domainRepository; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs index 2f91c602af..5823537f7a 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.Persistence.Repositories private LanguageRepository CreateRepository(IScopeProvider provider) { - return new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + return new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs index e21debfdfd..6f215f4a35 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = new Macro("test1", "Test", "~/views/macropartials/test.cshtml", MacroTypes.PartialView); ; @@ -52,7 +52,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = repository.Get(1); macro.Alias = "test2"; @@ -69,7 +69,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Assert Assert.That(repository, Is.Not.Null); @@ -83,7 +83,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var macro = repository.Get(1); @@ -111,7 +111,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var macros = repository.GetMany(); @@ -129,7 +129,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var query = scope.SqlContext.Query().Where(x => x.Alias.ToUpper() == "TEST1"); @@ -147,7 +147,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var query = scope.SqlContext.Query().Where(x => x.Name.StartsWith("Test")); @@ -165,7 +165,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var macro = new Macro("test", "Test", "~/views/macropartials/test.cshtml", MacroTypes.PartialView); @@ -186,7 +186,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var macro = repository.Get(2); @@ -221,7 +221,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var macro = repository.Get(3); @@ -242,7 +242,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); // Act var exists = repository.Exists(3); @@ -261,7 +261,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); @@ -287,7 +287,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); @@ -312,7 +312,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); @@ -336,7 +336,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); @@ -367,7 +367,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); @@ -394,7 +394,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var macro = repository.Get(1); macro.Properties.Add(new MacroProperty("new1", "New1", 3, "test")); @@ -422,7 +422,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); repository.Save(new Macro("test1", "Test1", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView)); repository.Save(new Macro("test2", "Test2", "~/views/macropartials/test2.cshtml", MacroTypes.PartialView)); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs index d1e7f96ff3..5e1900b29e 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs @@ -30,14 +30,14 @@ namespace Umbraco.Tests.Persistence.Repositories CreateTestData(); } - private MediaRepository CreateRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository, CacheHelper cacheHelper = null) + private MediaRepository CreateRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository, AppCaches appCaches = null) { - cacheHelper = cacheHelper ?? CacheHelper; + appCaches = appCaches ?? AppCaches; var scopeAccessor = (IScopeAccessor) provider; - mediaTypeRepository = new MediaTypeRepository(scopeAccessor, cacheHelper, Logger); - var tagRepository = new TagRepository(scopeAccessor, cacheHelper, Logger); - var repository = new MediaRepository(scopeAccessor, cacheHelper, Logger, mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); + mediaTypeRepository = new MediaTypeRepository(scopeAccessor, appCaches, Logger); + var tagRepository = new TagRepository(scopeAccessor, appCaches, Logger); + var repository = new MediaRepository(scopeAccessor, appCaches, Logger, mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); return repository; } @@ -46,7 +46,7 @@ namespace Umbraco.Tests.Persistence.Repositories { MediaTypeRepository mediaTypeRepository; - var realCache = new CacheHelper( + var realCache = new AppCaches( new ObjectCacheRuntimeCacheProvider(), new StaticCacheProvider(), new StaticCacheProvider(), @@ -55,7 +55,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = CreateRepository(provider, out mediaTypeRepository, cacheHelper: realCache); + var repository = CreateRepository(provider, out mediaTypeRepository, appCaches: realCache); var udb = (UmbracoDatabase)scope.Database; diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs index ae4308db55..49bb93f2a7 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaTypeRepositoryTest.cs @@ -21,12 +21,12 @@ namespace Umbraco.Tests.Persistence.Repositories { private MediaTypeRepository CreateRepository(IScopeProvider provider) { - return new MediaTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); + return new MediaTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); } private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) { - return new EntityContainerRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Constants.ObjectTypes.MediaTypeContainer); + return new EntityContainerRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Constants.ObjectTypes.MediaTypeContainer); } diff --git a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs index 18bfc4fcea..dea15cd4ad 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs @@ -29,10 +29,10 @@ namespace Umbraco.Tests.Persistence.Repositories private MemberRepository CreateRepository(IScopeProvider provider, out MemberTypeRepository memberTypeRepository, out MemberGroupRepository memberGroupRepository) { var accessor = (IScopeAccessor) provider; - memberTypeRepository = new MemberTypeRepository(accessor, CacheHelper.Disabled, Logger); - memberGroupRepository = new MemberGroupRepository(accessor, CacheHelper.Disabled, Logger); - var tagRepo = new TagRepository(accessor, CacheHelper.Disabled, Logger); - var repository = new MemberRepository(accessor, CacheHelper.Disabled, Logger, memberTypeRepository, memberGroupRepository, tagRepo, Mock.Of()); + memberTypeRepository = new MemberTypeRepository(accessor, AppCaches.Disabled, Logger); + memberGroupRepository = new MemberGroupRepository(accessor, AppCaches.Disabled, Logger); + var tagRepo = new TagRepository(accessor, AppCaches.Disabled, Logger); + var repository = new MemberRepository(accessor, AppCaches.Disabled, Logger, memberTypeRepository, memberGroupRepository, tagRepo, Mock.Of()); return repository; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs index 87d146f9f4..0c2314fd47 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MemberTypeRepositoryTest.cs @@ -22,7 +22,7 @@ namespace Umbraco.Tests.Persistence.Repositories { private MemberTypeRepository CreateRepository(IScopeProvider provider) { - return new MemberTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + return new MemberTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs index e76d794e69..d28a002e31 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs @@ -29,7 +29,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -59,7 +59,7 @@ namespace Umbraco.Tests.Persistence.Repositories using (var scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -99,7 +99,7 @@ namespace Umbraco.Tests.Persistence.Repositories using (var scope = provider.CreateScope()) { scope.Database.AsUmbracoDatabase().EnableSqlTrace = true; - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -144,7 +144,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -182,7 +182,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -210,7 +210,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var allEntries = new List(); for (int i = 0; i < 10; i++) @@ -274,7 +274,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repo = new PublicAccessRepository((IScopeAccessor) provider, CacheHelper, Logger); + var repo = new PublicAccessRepository((IScopeAccessor) provider, AppCaches, Logger); var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[] { @@ -307,11 +307,11 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(accessor, CacheHelper, Logger); - contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper, Logger, templateRepository); - var languageRepository = new LanguageRepository(accessor, CacheHelper, Logger); - var repository = new DocumentRepository(accessor, CacheHelper, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + var templateRepository = new TemplateRepository(accessor, AppCaches, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(accessor, AppCaches, Logger); + contentTypeRepository = new ContentTypeRepository(accessor, AppCaches, Logger, templateRepository); + var languageRepository = new LanguageRepository(accessor, AppCaches, Logger); + var repository = new DocumentRepository(accessor, AppCaches, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); return repository; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/RedirectUrlRepositoryTests.cs b/src/Umbraco.Tests/Persistence/Repositories/RedirectUrlRepositoryTests.cs index ca2c713a27..66f6655c77 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/RedirectUrlRepositoryTests.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/RedirectUrlRepositoryTests.cs @@ -188,7 +188,7 @@ namespace Umbraco.Tests.Persistence.Repositories private IRedirectUrlRepository CreateRepository(IScopeProvider provider) { - return new RedirectUrlRepository((IScopeAccessor) provider, CacheHelper, Logger); + return new RedirectUrlRepository((IScopeAccessor) provider, AppCaches, Logger); } private IContent _textpage, _subpage, _otherpage, _trashed; diff --git a/src/Umbraco.Tests/Persistence/Repositories/RelationRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/RelationRepositoryTest.cs index 697951d021..cea7f44b71 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/RelationRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/RelationRepositoryTest.cs @@ -30,7 +30,7 @@ namespace Umbraco.Tests.Persistence.Repositories private RelationRepository CreateRepository(IScopeProvider provider, out RelationTypeRepository relationTypeRepository) { var accessor = (IScopeAccessor) provider; - relationTypeRepository = new RelationTypeRepository(accessor, CacheHelper.Disabled, Mock.Of()); + relationTypeRepository = new RelationTypeRepository(accessor, AppCaches.Disabled, Mock.Of()); var repository = new RelationRepository(accessor, Mock.Of(), relationTypeRepository); return repository; } @@ -266,7 +266,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var relationTypeRepository = new RelationTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var relationTypeRepository = new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); var relationRepository = new RelationRepository((IScopeAccessor) provider, Mock.Of(), relationTypeRepository); relationTypeRepository.Save(relateContent); diff --git a/src/Umbraco.Tests/Persistence/Repositories/RelationTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/RelationTypeRepositoryTest.cs index 26b2fe48c2..e52e2dfcdf 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/RelationTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/RelationTypeRepositoryTest.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Persistence.Repositories private RelationTypeRepository CreateRepository(IScopeProvider provider) { - return new RelationTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + return new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); } @@ -232,7 +232,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = ScopeProvider.CreateScope()) { - var repository = new RelationTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new RelationTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); repository.Save(relateContent);//Id 2 repository.Save(relateContentType);//Id 3 diff --git a/src/Umbraco.Tests/Persistence/Repositories/ServerRegistrationRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ServerRegistrationRepositoryTest.cs index 08c34f453c..e2fc4b4705 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ServerRegistrationRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ServerRegistrationRepositoryTest.cs @@ -16,13 +16,13 @@ namespace Umbraco.Tests.Persistence.Repositories [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class ServerRegistrationRepositoryTest : TestWithDatabaseBase { - private CacheHelper _cacheHelper; + private AppCaches _appCaches; public override void SetUp() { base.SetUp(); - _cacheHelper = new CacheHelper(); + _appCaches = new AppCaches(); CreateTestData(); } diff --git a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs index 78eb736007..4812131a61 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs @@ -947,26 +947,26 @@ namespace Umbraco.Tests.Persistence.Repositories private TagRepository CreateRepository(IScopeProvider provider) { - return new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); + return new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); } private DocumentRepository CreateContentRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(accessor, CacheHelper.Disabled, Logger); - contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper.Disabled, Logger, templateRepository); - var languageRepository = new LanguageRepository(accessor, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository(accessor, CacheHelper.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(accessor, AppCaches.Disabled, Logger); + contentTypeRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, Logger, templateRepository); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, Logger); + var repository = new DocumentRepository(accessor, AppCaches.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); return repository; } private MediaRepository CreateMediaRepository(IScopeProvider provider, out MediaTypeRepository mediaTypeRepository) { var accessor = (IScopeAccessor) provider; - var tagRepository = new TagRepository(accessor, CacheHelper.Disabled, Logger); - mediaTypeRepository = new MediaTypeRepository(accessor, CacheHelper.Disabled, Logger); - var repository = new MediaRepository(accessor, CacheHelper.Disabled, Logger, mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); + var tagRepository = new TagRepository(accessor, AppCaches.Disabled, Logger); + mediaTypeRepository = new MediaTypeRepository(accessor, AppCaches.Disabled, Logger); + var repository = new MediaRepository(accessor, AppCaches.Disabled, Logger, mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); return repository; } } diff --git a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs index f4bed68315..94471aed7e 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Persistence.Repositories private ITemplateRepository CreateRepository(IScopeProvider provider, ITemplatesSection templatesSection = null) { - return new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, + return new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, templatesSection ?? Mock.Of(t => t.DefaultRenderingEngine == RenderingEngine.Mvc), _fileSystems); } @@ -363,10 +363,10 @@ namespace Umbraco.Tests.Persistence.Repositories { var templateRepository = CreateRepository(ScopeProvider); - var tagRepository = new TagRepository((IScopeAccessor) ScopeProvider, CacheHelper.Disabled, Logger); - var contentTypeRepository = new ContentTypeRepository((IScopeAccessor) ScopeProvider, CacheHelper.Disabled, Logger, templateRepository); - var languageRepository = new LanguageRepository((IScopeAccessor) ScopeProvider, CacheHelper.Disabled, Logger); - var contentRepo = new DocumentRepository((IScopeAccessor) ScopeProvider, CacheHelper.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + var tagRepository = new TagRepository((IScopeAccessor) ScopeProvider, AppCaches.Disabled, Logger); + var contentTypeRepository = new ContentTypeRepository((IScopeAccessor) ScopeProvider, AppCaches.Disabled, Logger, templateRepository); + var languageRepository = new LanguageRepository((IScopeAccessor) ScopeProvider, AppCaches.Disabled, Logger); + var contentRepo = new DocumentRepository((IScopeAccessor) ScopeProvider, AppCaches.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); var contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage2", "Textpage"); ServiceContext.FileService.SaveTemplate(contentType.DefaultTemplate); // else, FK violation on contentType! diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs index f0fb8cff88..311372ef10 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs @@ -19,7 +19,7 @@ namespace Umbraco.Tests.Persistence.Repositories { private UserGroupRepository CreateRepository(IScopeProvider provider) { - return new UserGroupRepository((IScopeAccessor) provider, Core.Cache.CacheHelper.Disabled, Mock.Of()); + return new UserGroupRepository((IScopeAccessor) provider, Core.Cache.AppCaches.Disabled, Mock.Of()); } [Test] @@ -131,7 +131,7 @@ namespace Umbraco.Tests.Persistence.Repositories var id = userGroup.Id; - var repository2 = new UserGroupRepository((IScopeAccessor) provider, Core.Cache.CacheHelper.Disabled, Logger); + var repository2 = new UserGroupRepository((IScopeAccessor) provider, Core.Cache.AppCaches.Disabled, Logger); repository2.Delete(userGroup); scope.Complete(); diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs index 847972cc50..7934544d8f 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs @@ -26,9 +26,9 @@ namespace Umbraco.Tests.Persistence.Repositories private MediaRepository CreateMediaRepository(IScopeProvider provider, out IMediaTypeRepository mediaTypeRepository) { var accessor = (IScopeAccessor) provider; - mediaTypeRepository = new MediaTypeRepository(accessor, CacheHelper, Mock.Of()); - var tagRepository = new TagRepository(accessor, CacheHelper, Mock.Of()); - var repository = new MediaRepository(accessor, CacheHelper, Mock.Of(), mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); + mediaTypeRepository = new MediaTypeRepository(accessor, AppCaches, Mock.Of()); + var tagRepository = new TagRepository(accessor, AppCaches, Mock.Of()); + var repository = new MediaRepository(accessor, AppCaches, Mock.Of(), mediaTypeRepository, tagRepository, Mock.Of(), Mock.Of()); return repository; } @@ -41,25 +41,25 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateContentRepository(IScopeProvider provider, out IContentTypeRepository contentTypeRepository, out ITemplateRepository templateRepository) { var accessor = (IScopeAccessor) provider; - templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(accessor, CacheHelper, Logger); - contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper, Logger, templateRepository); - var languageRepository = new LanguageRepository(accessor, CacheHelper, Logger); - var repository = new DocumentRepository(accessor, CacheHelper, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + templateRepository = new TemplateRepository(accessor, AppCaches, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(accessor, AppCaches, Logger); + contentTypeRepository = new ContentTypeRepository(accessor, AppCaches, Logger, templateRepository); + var languageRepository = new LanguageRepository(accessor, AppCaches, Logger); + var repository = new DocumentRepository(accessor, AppCaches, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); return repository; } private UserRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor) provider; - var repository = new UserRepository(accessor, CacheHelper.Disabled, Logger, Mappers, TestObjects.GetGlobalSettings()); + var repository = new UserRepository(accessor, AppCaches.Disabled, Logger, Mappers, TestObjects.GetGlobalSettings()); return repository; } private UserGroupRepository CreateUserGroupRepository(IScopeProvider provider) { var accessor = (IScopeAccessor) provider; - return new UserGroupRepository(accessor, CacheHelper.Disabled, Logger); + return new UserGroupRepository(accessor, AppCaches.Disabled, Logger); } [Test] @@ -207,7 +207,7 @@ namespace Umbraco.Tests.Persistence.Repositories var id = user.Id; - var repository2 = new UserRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(),TestObjects.GetGlobalSettings()); + var repository2 = new UserRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(),TestObjects.GetGlobalSettings()); repository2.Delete(user); diff --git a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs index 84f4f5dbd7..fe2cbdc145 100644 --- a/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs +++ b/src/Umbraco.Tests/Routing/RenderRouteHandlerTests.cs @@ -173,7 +173,7 @@ namespace Umbraco.Tests.Routing /// public class CustomDocumentController : RenderMvcController { - public CustomDocumentController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + public CustomDocumentController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(globalSettings, umbracoContext, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs index ccb7427907..3a52eea17c 100644 --- a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs +++ b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs @@ -59,7 +59,7 @@ namespace Umbraco.Tests.Runtimes var logger = new ConsoleLogger(); var profiler = new LogProfiler(logger); var profilingLogger = new ProfilingLogger(logger, profiler); - var appCaches = new CacheHelper(); // fixme has HttpRuntime stuff? + var appCaches = new AppCaches(); // fixme has HttpRuntime stuff? var databaseFactory = new UmbracoDatabaseFactory(logger, new Lazy(() => factory.GetInstance())); var typeLoader = new TypeLoader(appCaches.RuntimeCache, LocalTempStorage.Default, profilingLogger); var mainDom = new SimpleMainDom(); @@ -239,7 +239,7 @@ namespace Umbraco.Tests.Runtimes var logger = new ConsoleLogger(); var profiler = Mock.Of(); var profilingLogger = new ProfilingLogger(logger, profiler); - var appCaches = CacheHelper.Disabled; + var appCaches = AppCaches.Disabled; var databaseFactory = Mock.Of(); var typeLoader = new TypeLoader(appCaches.RuntimeCache, LocalTempStorage.Default, profilingLogger); var runtimeState = Mock.Of(); diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 3a0cb00ea9..5d4fa4f182 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -37,10 +37,10 @@ namespace Umbraco.Tests.Scoping .Add(() => Composition.TypeLoader.GetCacheRefreshers()); } - protected override CacheHelper GetCacheHelper() + protected override AppCaches GetCacheHelper() { // this is what's created core web runtime - return new CacheHelper( + return new AppCaches( new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), new StaticCacheProvider(), NullCacheProvider.Instance, diff --git a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs index 3aefa88a50..c56f66fc94 100644 --- a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs @@ -163,11 +163,11 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); - var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepo = new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, tRepository); + var languageRepository = new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var repository = new DocumentRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); // Act Stopwatch watch = Stopwatch.StartNew(); @@ -196,11 +196,11 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); - var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepo = new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, tRepository); + var languageRepository = new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var repository = new DocumentRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); // Act Stopwatch watch = Stopwatch.StartNew(); @@ -227,11 +227,11 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); - var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepo = new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, tRepository); + var languageRepository = new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var repository = new DocumentRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); // Act var contents = repository.GetMany(); @@ -261,11 +261,11 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); - var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepo = new TagRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, tRepository); + var languageRepository = new LanguageRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger); + var repository = new DocumentRepository((IScopeAccessor) provider, AppCaches.Disabled, Logger, ctRepository, tRepository, tagRepo, languageRepository, Mock.Of()); // Act var contents = repository.GetMany(); diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index 0f48a9c99a..799ce6a47c 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -3037,11 +3037,11 @@ namespace Umbraco.Tests.Services private DocumentRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); - var tagRepository = new TagRepository(accessor, CacheHelper.Disabled, Logger); - contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper.Disabled, Logger, templateRepository); - var languageRepository = new LanguageRepository(accessor, CacheHelper.Disabled, Logger); - var repository = new DocumentRepository(accessor, CacheHelper.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); + var templateRepository = new TemplateRepository(accessor, AppCaches.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tagRepository = new TagRepository(accessor, AppCaches.Disabled, Logger); + contentTypeRepository = new ContentTypeRepository(accessor, AppCaches.Disabled, Logger, templateRepository); + var languageRepository = new LanguageRepository(accessor, AppCaches.Disabled, Logger); + var repository = new DocumentRepository(accessor, AppCaches.Disabled, Logger, contentTypeRepository, templateRepository, tagRepository, languageRepository, Mock.Of()); return repository; } } diff --git a/src/Umbraco.Tests/Services/MacroServiceTests.cs b/src/Umbraco.Tests/Services/MacroServiceTests.cs index 52cc8ab0d1..69e816585e 100644 --- a/src/Umbraco.Tests/Services/MacroServiceTests.cs +++ b/src/Umbraco.Tests/Services/MacroServiceTests.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.Disabled, Mock.Of()); + var repository = new MacroRepository((IScopeAccessor) provider, AppCaches.Disabled, Mock.Of()); repository.Save(new Macro("test1", "Test1", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView)); repository.Save(new Macro("test2", "Test2", "~/views/macropartials/test2.cshtml", MacroTypes.PartialView)); diff --git a/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs b/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs index 795d79ced1..ececf46a18 100644 --- a/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs +++ b/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs @@ -15,7 +15,7 @@ namespace Umbraco.Tests.Templates [TestFixture] public class TemplateRepositoryTests { - private readonly Mock _cacheMock = new Mock(); + private readonly Mock _cacheMock = new Mock(); private readonly Mock _templateConfigMock = new Mock(); private readonly IFileSystems _fileSystems = Mock.Of(); private TemplateRepository _templateRepository; diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 9e2a2156ee..94e38d6872 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -151,7 +151,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(UrlInfo.Url("/hello/world/1234")); - var membershipHelper = new MembershipHelper(new TestUmbracoContextAccessor(umbCtx), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()); + var membershipHelper = new MembershipHelper(new TestUmbracoContextAccessor(umbCtx), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()); var umbHelper = new UmbracoHelper(umbCtx, Mock.Of(), diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 14ffeb743f..29eb649c48 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -90,7 +90,7 @@ namespace Umbraco.Tests.TestHelpers /// just mock the services to be passed to the ctor of the ServiceContext. public ServiceContext GetServiceContext( IScopeProvider scopeProvider, IScopeAccessor scopeAccessor, - CacheHelper cache, + AppCaches cache, ILogger logger, IGlobalSettings globalSettings, IUmbracoSettingsSection umbracoSettings, diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index c413cb0e94..575f14e818 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -56,7 +56,7 @@ namespace Umbraco.Tests.Testing.TestingTests Composition.Register(_ => Mock.Of()); Composition.Register(_ => Mock.Of()); Composition.Register(_ => Mock.Of()); - Composition.Register(_ => CacheHelper.Disabled); + Composition.Register(_ => AppCaches.Disabled); Composition.Register(); // ReSharper disable once UnusedVariable @@ -65,7 +65,7 @@ namespace Umbraco.Tests.Testing.TestingTests Mock.Of(), Mock.Of(), Mock.Of(), - new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()), + new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()), ServiceContext.CreatePartial()); Assert.Pass(); } diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index a79531af74..c980f9c1ee 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -101,7 +101,7 @@ namespace Umbraco.Tests.Testing protected virtual IProfilingLogger ProfilingLogger => Factory.GetInstance(); - protected CacheHelper CacheHelper => Factory.GetInstance(); + protected AppCaches AppCaches => Factory.GetInstance(); protected virtual ISqlSyntaxProvider SqlSyntax => Factory.GetInstance(); @@ -199,9 +199,9 @@ namespace Umbraco.Tests.Testing return (logger, profiler); } - protected virtual CacheHelper GetCacheHelper() + protected virtual AppCaches GetCacheHelper() { - return CacheHelper.Disabled; + return AppCaches.Disabled; } protected virtual void ComposeWeb() diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index 35e8f0a937..03844b5d72 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -132,7 +132,7 @@ namespace Umbraco.Tests.Web.Mvc Mock.Of(), Mock.Of(), Mock.Of(), - new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()), + new MembershipHelper(new TestUmbracoContextAccessor(umbracoContext), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), Mock.Of(), null, Mock.Of(), Mock.Of()), ServiceContext.CreatePartial()); var ctrl = new TestSurfaceController(umbracoContext, helper); @@ -185,7 +185,7 @@ namespace Umbraco.Tests.Web.Mvc public class TestSurfaceController : SurfaceController { public TestSurfaceController(UmbracoContext ctx, UmbracoHelper helper = null) - : base(ctx, null, ServiceContext.CreatePartial(), Mock.Of(), null, null) + : base(ctx, null, ServiceContext.CreatePartial(), Mock.Of(), null, null) { if (helper != null) { diff --git a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs index c1ab217642..cf93b44215 100644 --- a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs @@ -5,8 +5,8 @@ namespace Umbraco.Web.Cache { public sealed class ApplicationCacheRefresher : CacheRefresherBase { - public ApplicationCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public ApplicationCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs index 247c33c361..72fceec631 100644 --- a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs @@ -5,8 +5,8 @@ namespace Umbraco.Web.Cache { public sealed class ApplicationTreeCacheRefresher : CacheRefresherBase { - public ApplicationTreeCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public ApplicationTreeCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - CacheHelper.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs index b0192e9e75..3ae2f8e3dd 100644 --- a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs @@ -20,8 +20,8 @@ namespace Umbraco.Web.Cache private readonly IdkMap _idkMap; private readonly IDomainService _domainService; - public ContentCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap, IDomainService domainService) - : base(cacheHelper) + public ContentCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap, IDomainService domainService) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _idkMap = idkMap; @@ -44,10 +44,10 @@ namespace Umbraco.Web.Cache public override void Refresh(JsonPayload[] payloads) { - CacheHelper.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearCacheObjectTypes(); var idsRemoved = new HashSet(); - var isolatedCache = CacheHelper.IsolatedRuntimeCache.GetOrCreateCache(); + var isolatedCache = AppCaches.IsolatedRuntimeCache.GetOrCreateCache(); foreach (var payload in payloads) { @@ -103,7 +103,7 @@ namespace Umbraco.Web.Cache { // when a public version changes Current.ApplicationCache.ClearPartialViewCache(); - MacroCacheRefresher.ClearMacroContentCache(CacheHelper); // just the content + MacroCacheRefresher.ClearMacroContentCache(AppCaches); // just the content } base.Refresh(payloads); @@ -153,17 +153,17 @@ namespace Umbraco.Web.Cache #region Indirect - public static void RefreshContentTypes(CacheHelper cacheHelper) + public static void RefreshContentTypes(AppCaches appCaches) { // we could try to have a mechanism to notify the PublishedCachesService // and figure out whether published items were modified or not... keep it // simple for now, just clear the whole thing - cacheHelper.ClearPartialViewCache(); - MacroCacheRefresher.ClearMacroContentCache(cacheHelper); // just the content + appCaches.ClearPartialViewCache(); + MacroCacheRefresher.ClearMacroContentCache(appCaches); // just the content - cacheHelper.IsolatedRuntimeCache.ClearCache(); - cacheHelper.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedRuntimeCache.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs index c1b99d25ec..90b6e79ae1 100644 --- a/src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs @@ -13,8 +13,8 @@ namespace Umbraco.Web.Cache private readonly IPublishedSnapshotService _publishedSnapshotService; private readonly IdkMap _idkMap; - public ContentTypeCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) - : base(cacheHelper) + public ContentTypeCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _idkMap = idkMap; @@ -65,15 +65,15 @@ namespace Umbraco.Web.Cache if (payloads.Any(x => x.ItemType == typeof(IContentType).Name)) // don't try to be clever - refresh all - ContentCacheRefresher.RefreshContentTypes(CacheHelper); + ContentCacheRefresher.RefreshContentTypes(AppCaches); if (payloads.Any(x => x.ItemType == typeof(IMediaType).Name)) // don't try to be clever - refresh all - MediaCacheRefresher.RefreshMediaTypes(CacheHelper); + MediaCacheRefresher.RefreshMediaTypes(AppCaches); if (payloads.Any(x => x.ItemType == typeof(IMemberType).Name)) // don't try to be clever - refresh all - MemberCacheRefresher.RefreshMemberTypes(CacheHelper); + MemberCacheRefresher.RefreshMemberTypes(AppCaches); // notify _publishedSnapshotService.Notify(payloads); diff --git a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs index be17c28067..e1a8f05e39 100644 --- a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs @@ -15,8 +15,8 @@ namespace Umbraco.Web.Cache private readonly IPublishedSnapshotService _publishedSnapshotService; private readonly IdkMap _idkMap; - public DataTypeCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) - : base(cacheHelper) + public DataTypeCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _idkMap = idkMap; @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache ClearAllIsolatedCacheByEntityType(); ClearAllIsolatedCacheByEntityType(); - var dataTypeCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var dataTypeCache = AppCaches.IsolatedRuntimeCache.GetCache(); foreach (var payload in payloads) { diff --git a/src/Umbraco.Web/Cache/DictionaryCacheRefresher.cs b/src/Umbraco.Web/Cache/DictionaryCacheRefresher.cs index 7dadee87b1..525b4d2157 100644 --- a/src/Umbraco.Web/Cache/DictionaryCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DictionaryCacheRefresher.cs @@ -6,8 +6,8 @@ namespace Umbraco.Web.Cache { public sealed class DictionaryCacheRefresher : CacheRefresherBase { - public DictionaryCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public DictionaryCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define diff --git a/src/Umbraco.Web/Cache/DomainCacheRefresher.cs b/src/Umbraco.Web/Cache/DomainCacheRefresher.cs index 6907a654ff..37b0a483a6 100644 --- a/src/Umbraco.Web/Cache/DomainCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DomainCacheRefresher.cs @@ -10,8 +10,8 @@ namespace Umbraco.Web.Cache { private readonly IPublishedSnapshotService _publishedSnapshotService; - public DomainCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService) - : base(cacheHelper) + public DomainCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; } diff --git a/src/Umbraco.Web/Cache/LanguageCacheRefresher.cs b/src/Umbraco.Web/Cache/LanguageCacheRefresher.cs index bee12020cb..f5fe5075eb 100644 --- a/src/Umbraco.Web/Cache/LanguageCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/LanguageCacheRefresher.cs @@ -10,8 +10,8 @@ namespace Umbraco.Web.Cache { public sealed class LanguageCacheRefresher : CacheRefresherBase { - public LanguageCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService, IDomainService domainService) - : base(cacheHelper) + public LanguageCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IDomainService domainService) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _domainService = domainService; diff --git a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs index a4af601379..cdeb2ffdd0 100644 --- a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs @@ -12,8 +12,8 @@ namespace Umbraco.Web.Cache { public sealed class MacroCacheRefresher : JsonCacheRefresherBase { - public MacroCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public MacroCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -33,11 +33,11 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { foreach (var prefix in GetAllMacroCacheKeys()) - CacheHelper.RuntimeCache.ClearCacheByKeySearch(prefix); + AppCaches.RuntimeCache.ClearCacheByKeySearch(prefix); ClearAllIsolatedCacheByEntityType(); - CacheHelper.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearCacheObjectTypes(); base.RefreshAll(); } @@ -49,9 +49,9 @@ namespace Umbraco.Web.Cache foreach (var payload in payloads) { foreach (var alias in GetCacheKeysForAlias(payload.Alias)) - CacheHelper.RuntimeCache.ClearCacheByKeySearch(alias); + AppCaches.RuntimeCache.ClearCacheByKeySearch(alias); - var macroRepoCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var macroRepoCache = AppCaches.IsolatedRuntimeCache.GetCache(); if (macroRepoCache) { macroRepoCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); @@ -110,9 +110,9 @@ namespace Umbraco.Web.Cache return GetAllMacroCacheKeys().Select(x => x + alias).ToArray(); } - public static void ClearMacroContentCache(CacheHelper cacheHelper) + public static void ClearMacroContentCache(AppCaches appCaches) { - cacheHelper.RuntimeCache.ClearCacheObjectTypes(); + appCaches.RuntimeCache.ClearCacheObjectTypes(); } #endregion diff --git a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs index 4abf7d8787..a6ccd7e005 100644 --- a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs @@ -18,8 +18,8 @@ namespace Umbraco.Web.Cache private readonly IPublishedSnapshotService _publishedSnapshotService; private readonly IdkMap _idkMap; - public MediaCacheRefresher(CacheHelper cacheHelper, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) - : base(cacheHelper) + public MediaCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IdkMap idkMap) + : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _idkMap = idkMap; @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache { Current.ApplicationCache.ClearPartialViewCache(); - var mediaCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var mediaCache = AppCaches.IsolatedRuntimeCache.GetCache(); foreach (var payload in payloads) { @@ -119,9 +119,9 @@ namespace Umbraco.Web.Cache #region Indirect - public static void RefreshMediaTypes(CacheHelper cacheHelper) + public static void RefreshMediaTypes(AppCaches appCaches) { - cacheHelper.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedRuntimeCache.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs index 237daa39b4..29c102e7a2 100644 --- a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs @@ -11,8 +11,8 @@ namespace Umbraco.Web.Cache { private readonly IdkMap _idkMap; - public MemberCacheRefresher(CacheHelper cacheHelper, IdkMap idkMap) - : base(cacheHelper) + public MemberCacheRefresher(AppCaches appCaches, IdkMap idkMap) + : base(appCaches) { _idkMap = idkMap; } @@ -58,9 +58,9 @@ namespace Umbraco.Web.Cache private void ClearCache(int id) { _idkMap.ClearCache(id); - CacheHelper.ClearPartialViewCache(); + AppCaches.ClearPartialViewCache(); - var memberCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var memberCache = AppCaches.IsolatedRuntimeCache.GetCache(); if (memberCache) memberCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); } @@ -69,9 +69,9 @@ namespace Umbraco.Web.Cache #region Indirect - public static void RefreshMemberTypes(CacheHelper cacheHelper) + public static void RefreshMemberTypes(AppCaches appCaches) { - cacheHelper.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedRuntimeCache.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs index 4540f0b495..9368b0f9f4 100644 --- a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs @@ -8,8 +8,8 @@ namespace Umbraco.Web.Cache { public sealed class MemberGroupCacheRefresher : JsonCacheRefresherBase { - public MemberGroupCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public MemberGroupCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache // Since we cache by group name, it could be problematic when renaming to // previously existing names - see http://issues.umbraco.org/issue/U4-10846. // To work around this, just clear all the cache items - CacheHelper.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedRuntimeCache.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/PublicAccessCacheRefresher.cs b/src/Umbraco.Web/Cache/PublicAccessCacheRefresher.cs index 7c3af1129f..59c8231ed2 100644 --- a/src/Umbraco.Web/Cache/PublicAccessCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/PublicAccessCacheRefresher.cs @@ -6,8 +6,8 @@ namespace Umbraco.Web.Cache { public sealed class PublicAccessCacheRefresher : CacheRefresherBase { - public PublicAccessCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public PublicAccessCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define diff --git a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs index 4dd7282f98..8b1c8581cd 100644 --- a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs @@ -8,8 +8,8 @@ namespace Umbraco.Web.Cache { public sealed class RelationTypeCacheRefresher : CacheRefresherBase { - public RelationTypeCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public RelationTypeCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -34,7 +34,7 @@ namespace Umbraco.Web.Cache public override void Refresh(int id) { - var cache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var cache = AppCaches.IsolatedRuntimeCache.GetCache(); if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); base.Refresh(id); } @@ -47,7 +47,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var cache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var cache = AppCaches.IsolatedRuntimeCache.GetCache(); if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs index 6f76d148cc..7ff7c6fdb6 100644 --- a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs @@ -9,8 +9,8 @@ namespace Umbraco.Web.Cache { private readonly IdkMap _idkMap; - public TemplateCacheRefresher(CacheHelper cacheHelper, IdkMap idkMap) - : base(cacheHelper) + public TemplateCacheRefresher(AppCaches appCaches, IdkMap idkMap) + : base(appCaches) { _idkMap = idkMap; } @@ -52,7 +52,7 @@ namespace Umbraco.Web.Cache private void RemoveFromCache(int id) { _idkMap.ClearCache(id); - CacheHelper.RuntimeCache.ClearCacheItem($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); + AppCaches.RuntimeCache.ClearCacheItem($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); //need to clear the runtime cache for templates ClearAllIsolatedCacheByEntityType(); diff --git a/src/Umbraco.Web/Cache/UserCacheRefresher.cs b/src/Umbraco.Web/Cache/UserCacheRefresher.cs index ae57fc902a..a502a7554f 100644 --- a/src/Umbraco.Web/Cache/UserCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserCacheRefresher.cs @@ -8,8 +8,8 @@ namespace Umbraco.Web.Cache { public sealed class UserCacheRefresher : CacheRefresherBase { - public UserCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public UserCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -40,7 +40,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var userCache = AppCaches.IsolatedRuntimeCache.GetCache(); if (userCache) userCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); diff --git a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs index deb49ad624..4dea595c85 100644 --- a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs @@ -14,8 +14,8 @@ namespace Umbraco.Web.Cache /// public sealed class UserGroupCacheRefresher : CacheRefresherBase { - public UserGroupCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public UserGroupCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define @@ -35,7 +35,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { ClearAllIsolatedCacheByEntityType(); - var userGroupCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); if (userGroupCache) { userGroupCache.Result.ClearCacheByKeySearch(UserGroupRepository.GetByAliasCacheKeyPrefix); @@ -55,7 +55,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userGroupCache = CacheHelper.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); if (userGroupCache) { userGroupCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); diff --git a/src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs b/src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs index bd2ad50ef5..37e02a0149 100644 --- a/src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserGroupPermissionsCacheRefresher.cs @@ -8,8 +8,8 @@ namespace Umbraco.Web.Cache [EditorBrowsable(EditorBrowsableState.Never)] public sealed class UserGroupPermissionsCacheRefresher : CacheRefresherBase { - public UserGroupPermissionsCacheRefresher(CacheHelper cacheHelper) - : base(cacheHelper) + public UserGroupPermissionsCacheRefresher(AppCaches appCaches) + : base(appCaches) { } #region Define diff --git a/src/Umbraco.Web/CacheHelperExtensions.cs b/src/Umbraco.Web/CacheHelperExtensions.cs index d7aa838a09..3c5ea1930d 100644 --- a/src/Umbraco.Web/CacheHelperExtensions.cs +++ b/src/Umbraco.Web/CacheHelperExtensions.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web /// /// Outputs and caches a partial view in MVC /// - /// + /// /// /// /// @@ -28,7 +28,7 @@ namespace Umbraco.Web /// /// public static IHtmlString CachedPartialView( - this CacheHelper cacheHelper, + this AppCaches appCaches, HtmlHelper htmlHelper, string partialViewName, object model, @@ -43,7 +43,7 @@ namespace Umbraco.Web return htmlHelper.Partial(partialViewName, model, viewData); } - return cacheHelper.RuntimeCache.GetCacheItem( + return appCaches.RuntimeCache.GetCacheItem( PartialViewCacheKey + cacheKey, () => htmlHelper.Partial(partialViewName, model, viewData), priority: CacheItemPriority.NotRemovable, //not removable, the same as macros (apparently issue #27610) @@ -53,10 +53,10 @@ namespace Umbraco.Web /// /// Clears the cache for partial views /// - /// - public static void ClearPartialViewCache(this CacheHelper cacheHelper) + /// + public static void ClearPartialViewCache(this AppCaches appCaches) { - cacheHelper.RuntimeCache.ClearCacheByKeySearch(PartialViewCacheKey); + appCaches.RuntimeCache.ClearCacheByKeySearch(PartialViewCacheKey); } } } diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 1e8f3d17f7..ed1853c351 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -203,7 +203,7 @@ namespace Umbraco.Web.Composing public static IProfilingLogger ProfilingLogger => CoreCurrent.ProfilingLogger; - public static CacheHelper ApplicationCache => CoreCurrent.ApplicationCache; + public static AppCaches ApplicationCache => CoreCurrent.ApplicationCache; public static ServiceContext Services => CoreCurrent.Services; diff --git a/src/Umbraco.Web/Controllers/UmbLoginController.cs b/src/Umbraco.Web/Controllers/UmbLoginController.cs index fc6613200c..684925c3e3 100644 --- a/src/Umbraco.Web/Controllers/UmbLoginController.cs +++ b/src/Umbraco.Web/Controllers/UmbLoginController.cs @@ -16,7 +16,7 @@ namespace Umbraco.Web.Controllers { } - public UmbLoginController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + public UmbLoginController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs b/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs index 83f4ae04a1..3f394824f6 100644 --- a/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs +++ b/src/Umbraco.Web/Controllers/UmbLoginStatusController.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.Controllers { } - public UmbLoginStatusController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) + public UmbLoginStatusController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Web/Controllers/UmbProfileController.cs b/src/Umbraco.Web/Controllers/UmbProfileController.cs index 7ee8385edc..459d1b1829 100644 --- a/src/Umbraco.Web/Controllers/UmbProfileController.cs +++ b/src/Umbraco.Web/Controllers/UmbProfileController.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.Controllers { } - public UmbProfileController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) + public UmbProfileController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Web/Controllers/UmbRegisterController.cs b/src/Umbraco.Web/Controllers/UmbRegisterController.cs index 5a5024dad9..0288995b1f 100644 --- a/src/Umbraco.Web/Controllers/UmbRegisterController.cs +++ b/src/Umbraco.Web/Controllers/UmbRegisterController.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.Controllers { } - public UmbRegisterController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) + public UmbRegisterController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index 231ec9ba67..d1c9ec48bb 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -52,7 +52,7 @@ namespace Umbraco.Web.Editors /// /// Initializes a new instance of the class with all its dependencies. /// - public AuthenticationController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + public AuthenticationController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 6294a0377f..414c248041 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Editors private const string TokenPasswordResetCode = "PasswordResetCode"; private static readonly string[] TempDataTokenNames = { TokenExternalSignInError, TokenPasswordResetCode }; - public BackOfficeController(ManifestParser manifestParser, UmbracoFeatures features, IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger, IRuntimeState runtimeState) + public BackOfficeController(ManifestParser manifestParser, UmbracoFeatures features, IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger, IRuntimeState runtimeState) : base(globalSettings, umbracoContext, services, applicationCache, logger, profilingLogger) { _manifestParser = manifestParser; diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index 670d37e7a7..84ce177eef 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -56,7 +56,7 @@ namespace Umbraco.Web.Editors IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, PropertyEditorCollection propertyEditors, - ServiceContext services, CacheHelper applicationCache, + ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { diff --git a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs index 898208319a..8d23a34c5e 100644 --- a/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs +++ b/src/Umbraco.Web/Editors/ContentTypeControllerBase.cs @@ -33,7 +33,7 @@ namespace Umbraco.Web.Editors private readonly ICultureDictionaryFactory _cultureDictionaryFactory; private ICultureDictionary _cultureDictionary; - protected ContentTypeControllerBase(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected ContentTypeControllerBase(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { _cultureDictionaryFactory = cultureDictionaryFactory; } diff --git a/src/Umbraco.Web/Editors/DashboardController.cs b/src/Umbraco.Web/Editors/DashboardController.cs index 8960f110c3..3fdf1b78c8 100644 --- a/src/Umbraco.Web/Editors/DashboardController.cs +++ b/src/Umbraco.Web/Editors/DashboardController.cs @@ -38,7 +38,7 @@ namespace Umbraco.Web.Editors /// /// Initializes a new instance of the with all its dependencies. /// - public DashboardController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, Dashboards dashboards) + public DashboardController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState, Dashboards dashboards) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { _dashboards = dashboards; diff --git a/src/Umbraco.Web/Editors/MediaTypeController.cs b/src/Umbraco.Web/Editors/MediaTypeController.cs index f2b8fd3dda..b8617e6f94 100644 --- a/src/Umbraco.Web/Editors/MediaTypeController.cs +++ b/src/Umbraco.Web/Editors/MediaTypeController.cs @@ -37,7 +37,7 @@ namespace Umbraco.Web.Editors [MediaTypeControllerControllerConfiguration] public class MediaTypeController : ContentTypeControllerBase { - public MediaTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public MediaTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/MemberTypeController.cs b/src/Umbraco.Web/Editors/MemberTypeController.cs index 3abc0035d3..4ba5204e4d 100644 --- a/src/Umbraco.Web/Editors/MemberTypeController.cs +++ b/src/Umbraco.Web/Editors/MemberTypeController.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web.Editors [UmbracoTreeAuthorize(new string[] { Constants.Trees.MemberTypes, Constants.Trees.Members})] public class MemberTypeController : ContentTypeControllerBase { - public MemberTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + public MemberTypeController(ICultureDictionaryFactory cultureDictionaryFactory, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(cultureDictionaryFactory, globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 05d1e2a7a3..f59fd360ed 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -45,7 +45,7 @@ namespace Umbraco.Web.Editors public class PackageInstallController : UmbracoAuthorizedJsonController { public PackageInstallController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, - ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, + ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { diff --git a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs index 3baa5e85ff..8cb9408044 100644 --- a/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs +++ b/src/Umbraco.Web/Editors/UmbracoAuthorizedJsonController.cs @@ -37,7 +37,7 @@ namespace Umbraco.Web.Editors /// /// /// - protected UmbracoAuthorizedJsonController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) + protected UmbracoAuthorizedJsonController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } } diff --git a/src/Umbraco.Web/Mvc/PluginController.cs b/src/Umbraco.Web/Mvc/PluginController.cs index a8d73fe575..a8e7f1f0d1 100644 --- a/src/Umbraco.Web/Mvc/PluginController.cs +++ b/src/Umbraco.Web/Mvc/PluginController.cs @@ -50,7 +50,7 @@ namespace Umbraco.Web.Mvc /// /// Gets or sets the application cache. /// - public CacheHelper ApplicationCache { get; } + public AppCaches ApplicationCache { get; } /// /// Gets or sets the logger. @@ -93,14 +93,14 @@ namespace Umbraco.Web.Mvc Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), + Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance() ) { } - protected PluginController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + protected PluginController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) { UmbracoContext = umbracoContext; DatabaseFactory = databaseFactory; diff --git a/src/Umbraco.Web/Mvc/RenderMvcController.cs b/src/Umbraco.Web/Mvc/RenderMvcController.cs index 44a6a9346d..dc775450bf 100644 --- a/src/Umbraco.Web/Mvc/RenderMvcController.cs +++ b/src/Umbraco.Web/Mvc/RenderMvcController.cs @@ -24,7 +24,7 @@ namespace Umbraco.Web.Mvc ActionInvoker = new RenderActionInvoker(); } - public RenderMvcController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + public RenderMvcController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(globalSettings, umbracoContext, services, applicationCache, logger, profilingLogger) { ActionInvoker = new RenderActionInvoker(); diff --git a/src/Umbraco.Web/Mvc/SurfaceController.cs b/src/Umbraco.Web/Mvc/SurfaceController.cs index b3e67e4b2b..1035d43739 100644 --- a/src/Umbraco.Web/Mvc/SurfaceController.cs +++ b/src/Umbraco.Web/Mvc/SurfaceController.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.Mvc { } - protected SurfaceController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + protected SurfaceController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(umbracoContext, databaseFactory, services, applicationCache, logger, profilingLogger) { } diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs index 2f8f7a6e76..7084b79271 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizedController.cs @@ -20,7 +20,7 @@ namespace Umbraco.Web.Mvc protected UmbracoAuthorizedController() { } - protected UmbracoAuthorizedController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + protected UmbracoAuthorizedController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) : base(globalSettings, umbracoContext, services, applicationCache, logger, profilingLogger) { } } diff --git a/src/Umbraco.Web/Mvc/UmbracoController.cs b/src/Umbraco.Web/Mvc/UmbracoController.cs index 36f688b714..7d451321bc 100644 --- a/src/Umbraco.Web/Mvc/UmbracoController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoController.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.Mvc /// /// Gets or sets the application cache. /// - public CacheHelper ApplicationCache { get; set; } + public AppCaches ApplicationCache { get; set; } /// /// Gets or sets the logger. @@ -83,14 +83,14 @@ namespace Umbraco.Web.Mvc Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), + Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance() ) { } - protected UmbracoController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) + protected UmbracoController(IGlobalSettings globalSettings, UmbracoContext umbracoContext, ServiceContext services, AppCaches applicationCache, ILogger logger, IProfilingLogger profilingLogger) { GlobalSettings = globalSettings; UmbracoContext = umbracoContext; diff --git a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs index 394aa39dd9..2c5c0395a4 100644 --- a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs +++ b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.Mvc /// /// Gets or sets the application cache. /// - public CacheHelper ApplicationCache { get; set; } + public AppCaches ApplicationCache { get; set; } // fixme // previously, Services and ApplicationCache would derive from UmbracoContext.Application, which @@ -110,12 +110,12 @@ namespace Umbraco.Web.Mvc protected UmbracoViewPage() : this( Current.Factory.GetInstance(), - Current.Factory.GetInstance() + Current.Factory.GetInstance() ) { } - protected UmbracoViewPage(ServiceContext services, CacheHelper applicationCache) + protected UmbracoViewPage(ServiceContext services, AppCaches applicationCache) { Services = services; ApplicationCache = applicationCache; diff --git a/src/Umbraco.Web/Runtime/WebRuntime.cs b/src/Umbraco.Web/Runtime/WebRuntime.cs index ad1a4851f0..c69a3bec8b 100644 --- a/src/Umbraco.Web/Runtime/WebRuntime.cs +++ b/src/Umbraco.Web/Runtime/WebRuntime.cs @@ -59,7 +59,7 @@ namespace Umbraco.Web.Runtime protected override IProfiler GetProfiler() => _webProfiler; - protected override CacheHelper GetAppCaches() => new CacheHelper( + 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 DeepCloneRuntimeCacheProvider(new HttpRuntimeCacheProvider(HttpRuntime.Cache)), diff --git a/src/Umbraco.Web/Security/MembershipHelper.cs b/src/Umbraco.Web/Security/MembershipHelper.cs index eb4c24aabc..6ae8ff8c96 100644 --- a/src/Umbraco.Web/Security/MembershipHelper.cs +++ b/src/Umbraco.Web/Security/MembershipHelper.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.Security private readonly IUserService _userService; private readonly IPublicAccessService _publicAccessService; private readonly PublishedRouter _publishedRouter; - private readonly CacheHelper _appCaches; + private readonly AppCaches _appCaches; private readonly ILogger _logger; #region Constructors @@ -47,7 +47,7 @@ namespace Umbraco.Web.Security IUserService userService, IPublicAccessService publicAccessService, PublishedRouter publishedRouter, - CacheHelper appCaches, + AppCaches appCaches, ILogger logger ) { diff --git a/src/Umbraco.Web/Services/ApplicationTreeService.cs b/src/Umbraco.Web/Services/ApplicationTreeService.cs index 86bfc5d0bb..2ddec054c7 100644 --- a/src/Umbraco.Web/Services/ApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/ApplicationTreeService.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.Services internal class ApplicationTreeService : IApplicationTreeService { private readonly ILogger _logger; - private readonly CacheHelper _cache; + private readonly AppCaches _cache; private readonly TypeLoader _typeLoader; private Lazy> _allAvailableTrees; internal const string TreeConfigFileName = "trees.config"; @@ -27,7 +27,7 @@ namespace Umbraco.Web.Services private static readonly object Locker = new object(); private readonly Lazy>> _groupedTrees; - public ApplicationTreeService(ILogger logger, CacheHelper cache, TypeLoader typeLoader) + public ApplicationTreeService(ILogger logger, AppCaches cache, TypeLoader typeLoader) { _logger = logger; _cache = cache; diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index 6337db67f9..2d06141292 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.Services private readonly Lazy> _allAvailableSections; private readonly IApplicationTreeService _applicationTreeService; private readonly IScopeProvider _scopeProvider; - private readonly CacheHelper _cache; + private readonly AppCaches _cache; internal const string AppConfigFileName = "applications.config"; private static string _appConfig; private static readonly object Locker = new object(); @@ -32,7 +32,7 @@ namespace Umbraco.Web.Services IUserService userService, IApplicationTreeService applicationTreeService, IScopeProvider scopeProvider, - CacheHelper cache) + AppCaches cache) { _applicationTreeService = applicationTreeService ?? throw new ArgumentNullException(nameof(applicationTreeService)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); diff --git a/src/Umbraco.Web/TagsController.cs b/src/Umbraco.Web/TagsController.cs index 181b9f7da2..784f1d9883 100644 --- a/src/Umbraco.Web/TagsController.cs +++ b/src/Umbraco.Web/TagsController.cs @@ -29,7 +29,7 @@ namespace Umbraco.Web.WebServices /// /// Initializes a new instance of the with all its dependencies. /// - public TagsController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + public TagsController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } diff --git a/src/Umbraco.Web/WebApi/UmbracoApiController.cs b/src/Umbraco.Web/WebApi/UmbracoApiController.cs index 3db3610cc2..a779632def 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiController.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.WebApi /// /// Initialize a new instance of the with all its dependencies. /// - protected UmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + protected UmbracoApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } } diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs index 21b88cc919..44457fbef1 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.WebApi Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance(), - Current.Factory.GetInstance(), + Current.Factory.GetInstance(), Current.Factory.GetInstance(), Current.Factory.GetInstance() ) @@ -48,7 +48,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, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + protected UmbracoApiControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) { GlobalSettings = globalSettings; _umbracoContextAccessor = umbracoContextAccessor; @@ -88,7 +88,7 @@ namespace Umbraco.Web.WebApi /// /// Gets the application cache. /// - public CacheHelper ApplicationCache { get; } + public AppCaches ApplicationCache { get; } /// /// Gets the logger. diff --git a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs index 4ae9c00a47..1d20857efd 100644 --- a/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs +++ b/src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.WebApi /// /// Initializes a new instance of the class with all its dependencies. /// - protected UmbracoAuthorizedApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, CacheHelper applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) + protected UmbracoAuthorizedApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches applicationCache, IProfilingLogger logger, IRuntimeState runtimeState) : base(globalSettings, umbracoContextAccessor, sqlContext, services, applicationCache, logger, runtimeState) { } From 1667e914cd4354f9edcb45cedeaf0d4b3108faad Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 17 Jan 2019 18:38:55 +1100 Subject: [PATCH 35/70] Allows the tree collection to be manipulated by devs on startup, renames some things --- src/Umbraco.Web/Runtime/WebRuntimeComposer.cs | 13 +++++-------- src/Umbraco.Web/Services/ITreeService.cs | 8 ++++---- src/Umbraco.Web/Services/TreeService.cs | 8 ++++---- .../Trees/ApplicationTreeController.cs | 2 +- .../Trees/BackOfficeSectionCollectionBuilder.cs | 9 ++------- src/Umbraco.Web/Trees/ITree.cs | 3 ++- src/Umbraco.Web/Trees/Tree.cs | 2 +- src/Umbraco.Web/Trees/TreeCollectionBuilder.cs | 15 +++++++-------- 8 files changed, 26 insertions(+), 34 deletions(-) diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs index f21c040a37..1a0bf8d1b0 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComposer.cs @@ -1,15 +1,13 @@ -using System.Web; +using System.Linq; +using System.Web; using System.Web.Security; using Examine; using Microsoft.AspNet.SignalR; using Umbraco.Core; using Umbraco.Core.Components; using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; using Umbraco.Core.Dictionary; using Umbraco.Core.Events; -using Umbraco.Core.Models; -using Umbraco.Core.Models.ContentEditing; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.ValueConverters; @@ -23,9 +21,7 @@ using Umbraco.Web.Dictionary; using Umbraco.Web.Editors; using Umbraco.Web.Features; using Umbraco.Web.HealthCheck; -using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.PublishedContent; -using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; @@ -207,12 +203,13 @@ namespace Umbraco.Web.Runtime .Append(); // register back office trees - foreach (var treeControllerType in umbracoApiControllerTypes) + foreach (var treeControllerType in umbracoApiControllerTypes + .Where(x => typeof(TreeControllerBase).IsAssignableFrom(x))) { var attribute = treeControllerType.GetCustomAttribute(false); if (attribute == null) continue; var tree = new Tree(attribute.SortOrder, attribute.ApplicationAlias, attribute.TreeAlias, attribute.TreeTitle, treeControllerType, attribute.IsSingleNodeTree); - composition.WithCollectionBuilder().AddTree(tree); + composition.WithCollectionBuilder().Trees.Add(tree); } } } diff --git a/src/Umbraco.Web/Services/ITreeService.cs b/src/Umbraco.Web/Services/ITreeService.cs index 5172e4b7b7..96787086c6 100644 --- a/src/Umbraco.Web/Services/ITreeService.cs +++ b/src/Umbraco.Web/Services/ITreeService.cs @@ -26,16 +26,16 @@ namespace Umbraco.Web.Services /// /// Gets the application tree for the applcation with the specified alias /// - /// The application alias. + /// The application alias. /// Returns a ApplicationTree Array - IEnumerable GetApplicationTrees(string applicationAlias); + IEnumerable GetTrees(string sectionAlias); /// /// Gets the grouped application trees for the application with the specified alias /// - /// + /// /// - IDictionary> GetGroupedApplicationTrees(string applicationAlias); + IDictionary> GetGroupedTrees(string sectionAlias); } } diff --git a/src/Umbraco.Web/Services/TreeService.cs b/src/Umbraco.Web/Services/TreeService.cs index 8389c27a19..f58dce59bc 100644 --- a/src/Umbraco.Web/Services/TreeService.cs +++ b/src/Umbraco.Web/Services/TreeService.cs @@ -24,13 +24,13 @@ namespace Umbraco.Web.Services public IEnumerable GetAll() => _treeCollection; /// - public IEnumerable GetApplicationTrees(string applicationAlias) - => GetAll().Where(x => x.ApplicationAlias.InvariantEquals(applicationAlias)).OrderBy(x => x.SortOrder).ToList(); + public IEnumerable GetTrees(string sectionAlias) + => GetAll().Where(x => x.ApplicationAlias.InvariantEquals(sectionAlias)).OrderBy(x => x.SortOrder).ToList(); - public IDictionary> GetGroupedApplicationTrees(string applicationAlias) + public IDictionary> GetGroupedTrees(string sectionAlias) { var result = new Dictionary>(); - var foundTrees = GetApplicationTrees(applicationAlias).ToList(); + var foundTrees = GetTrees(sectionAlias).ToList(); foreach(var treeGroup in _groupedTrees.Value) { List resultGroup = null; diff --git a/src/Umbraco.Web/Trees/ApplicationTreeController.cs b/src/Umbraco.Web/Trees/ApplicationTreeController.cs index 5a0f72c8dc..5433f3c157 100644 --- a/src/Umbraco.Web/Trees/ApplicationTreeController.cs +++ b/src/Umbraco.Web/Trees/ApplicationTreeController.cs @@ -60,7 +60,7 @@ namespace Umbraco.Web.Trees if (string.IsNullOrEmpty(application)) throw new HttpResponseException(HttpStatusCode.NotFound); //find all tree definitions that have the current application alias - var groupedTrees = _treeService.GetGroupedApplicationTrees(application); + var groupedTrees = _treeService.GetGroupedTrees(application); var allTrees = groupedTrees.Values.SelectMany(x => x).ToList(); if (string.IsNullOrEmpty(tree) == false || allTrees.Count == 1) diff --git a/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs index ec5833f79c..3228cd309f 100644 --- a/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs +++ b/src/Umbraco.Web/Trees/BackOfficeSectionCollectionBuilder.cs @@ -12,12 +12,6 @@ namespace Umbraco.Web.Trees { protected override BackOfficeSectionCollectionBuilder This => this; - // need to inject dependencies in the collection, so override creation - public override BackOfficeSectionCollection CreateCollection(IFactory factory) - { - return new BackOfficeSectionCollection(CreateItems(factory)); - } - protected override IEnumerable CreateItems(IFactory factory) { // get the manifest parser just-in-time - injecting it in the ctor would mean that @@ -25,7 +19,8 @@ namespace Umbraco.Web.Trees // its dependencies too, and that can create cycles or other oddities var manifestParser = factory.GetInstance(); - return base.CreateItems(factory).Concat(manifestParser.Manifest.Sections.Select(x => new ManifestBackOfficeSection(x.Key, x.Value))); + return base.CreateItems(factory) + .Concat(manifestParser.Manifest.Sections.Select(x => new ManifestBackOfficeSection(x.Key, x.Value))); } private class ManifestBackOfficeSection : IBackOfficeSection diff --git a/src/Umbraco.Web/Trees/ITree.cs b/src/Umbraco.Web/Trees/ITree.cs index f408ce5e60..867beda20e 100644 --- a/src/Umbraco.Web/Trees/ITree.cs +++ b/src/Umbraco.Web/Trees/ITree.cs @@ -1,7 +1,8 @@ namespace Umbraco.Web.Trees { //fixme - we don't really use this, it is nice to have the treecontroller, attribute and ApplicationTree streamlined to implement this but it's not used - public interface ITree + //leave as internal for now, maybe we'll use in the future, means we could pass around ITree + internal interface ITree { /// /// Gets or sets the sort order. diff --git a/src/Umbraco.Web/Trees/Tree.cs b/src/Umbraco.Web/Trees/Tree.cs index 3bac5bae58..39f5cec1eb 100644 --- a/src/Umbraco.Web/Trees/Tree.cs +++ b/src/Umbraco.Web/Trees/Tree.cs @@ -43,7 +43,7 @@ namespace Umbraco.Web.Trees public Type TreeControllerType { get; } - public static string GetRootNodeDisplayName(ITree tree, ILocalizedTextService textService) + internal static string GetRootNodeDisplayName(ITree tree, ILocalizedTextService textService) { var label = $"[{tree.TreeAlias}]"; diff --git a/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs index 143b8e308b..ae2675bac9 100644 --- a/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs +++ b/src/Umbraco.Web/Trees/TreeCollectionBuilder.cs @@ -3,16 +3,15 @@ using Umbraco.Core.Composing; namespace Umbraco.Web.Trees { - //fixme - how will we allow users to modify these items? they will need to be able to change the ApplicationTree's registered (i.e. sort order, section) - public class TreeCollectionBuilder : CollectionBuilderBase + public class TreeCollectionBuilder : ICollectionBuilder { - private readonly List _instances = new List(); + /// + /// expose the list of trees which developers can manipulate before the collection is created + /// + public List Trees { get; } = new List(); - public void AddTree(Tree tree) - { - _instances.Add(tree); - } + public TreeCollection CreateCollection(IFactory factory) => new TreeCollection(Trees); - protected override IEnumerable CreateItems(IFactory factory) => _instances; + public void RegisterWith(IRegister register) => register.Register(CreateCollection, Lifetime.Singleton); } } From 0bee01e0eeea61ba2861a9e3b16f3594ea9a9396 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 17 Jan 2019 11:01:23 +0100 Subject: [PATCH 36/70] Great AppCaches renaming --- src/Umbraco.Core/Cache/AppCaches.cs | 75 +++-- .../Cache/AppPolicedCacheDictionary.cs | 74 +++++ .../Cache/CacheProviderExtensions.cs | 24 +- src/Umbraco.Core/Cache/CacheRefresherBase.cs | 2 +- src/Umbraco.Core/Cache/DeepCloneAppCache.cs | 157 ++++++++++ .../Cache/DeepCloneRuntimeCacheProvider.cs | 155 ---------- .../Cache/DefaultRepositoryCachePolicy.cs | 30 +- .../Cache/DictionaryCacheProvider.cs | 178 ++++------- ...rBase.cs => FastDictionaryAppCacheBase.cs} | 242 ++++++++------- .../Cache/FastDictionaryCacheProvider.cs | 162 ++++++++++ .../Cache/FullDataSetRepositoryCachePolicy.cs | 8 +- ...acheProvider.cs => HttpRequestAppCache.cs} | 157 +++++----- src/Umbraco.Core/Cache/IAppCache.cs | 94 ++++++ src/Umbraco.Core/Cache/IAppPolicedCache.cs | 54 ++++ src/Umbraco.Core/Cache/ICacheProvider.cs | 68 ----- .../Cache/IRuntimeCacheProvider.cs | 35 --- src/Umbraco.Core/Cache/IsolatedCaches.cs | 41 +++ .../Cache/IsolatedRuntimeCache.cs | 91 ------ src/Umbraco.Core/Cache/NoAppCache.cs | 82 +++++ .../Cache/NoCacheRepositoryCachePolicy.cs | 2 +- src/Umbraco.Core/Cache/NullCacheProvider.cs | 66 ---- ...acheProvider.cs => ObjectCacheAppCache.cs} | 283 +++++++++--------- .../Cache/RepositoryCachePolicyBase.cs | 10 +- .../SingleItemsOnlyRepositoryCachePolicy.cs | 2 +- src/Umbraco.Core/Cache/StaticCacheProvider.cs | 79 ----- ...CacheProvider.cs => WebCachingAppCache.cs} | 118 +++----- src/Umbraco.Core/Composing/TypeLoader.cs | 8 +- src/Umbraco.Core/ConfigsExtensions.cs | 2 +- .../Configuration/Grid/GridConfig.cs | 2 +- .../Configuration/Grid/GridEditorsConfig.cs | 4 +- src/Umbraco.Core/Manifest/ManifestParser.cs | 6 +- src/Umbraco.Core/Models/UserExtensions.cs | 2 +- .../Implement/ConsentRepository.cs | 2 +- .../Implement/DictionaryRepository.cs | 12 +- .../Implement/RepositoryBaseOfTIdTEntity.cs | 12 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 8 +- src/Umbraco.Core/Scoping/IScope.cs | 2 +- src/Umbraco.Core/Scoping/Scope.cs | 10 +- .../LocalizedTextServiceFileSources.cs | 6 +- src/Umbraco.Core/Umbraco.Core.csproj | 23 +- src/Umbraco.Tests/Cache/CacheProviderTests.cs | 94 +++--- .../DeepCloneRuntimeCacheProviderTests.cs | 16 +- .../Cache/DefaultCachePolicyTests.cs | 26 +- .../Cache/FullDataSetCachePolicyTests.cs | 32 +- .../Cache/HttpRequestCacheProviderTests.cs | 14 +- .../Cache/HttpRuntimeCacheProviderTests.cs | 16 +- .../Cache/ObjectCacheProviderTests.cs | 8 +- .../PublishedContentCacheTests.cs | 2 +- .../PublishedMediaCacheTests.cs | 8 +- .../Cache/RuntimeCacheProviderTests.cs | 4 +- .../Cache/SingleItemsOnlyCachePolicyTests.cs | 10 +- .../Composing/ComposingTestBase.cs | 2 +- .../Composing/TypeLoaderTests.cs | 2 +- src/Umbraco.Tests/CoreThings/UdiTests.cs | 2 +- .../FrontEnd/UmbracoHelperTests.cs | 2 +- src/Umbraco.Tests/Macros/MacroTests.cs | 8 +- .../Manifest/ManifestParserTests.cs | 2 +- src/Umbraco.Tests/Models/ContentTests.cs | 6 +- .../Repositories/DocumentRepositoryTest.cs | 8 +- .../Repositories/MediaRepositoryTest.cs | 8 +- .../Published/PropertyCacheLevelTests.cs | 4 +- .../PublishedContentSnapshotTestBase.cs | 2 +- .../PublishedContent/PublishedContentTests.cs | 2 +- .../PublishedContent/PublishedMediaTests.cs | 20 +- .../SolidPublishedSnapshot.cs | 4 +- .../Scoping/ScopedRepositoryTests.cs | 54 ++-- .../TestHelpers/BaseUsingSqlCeSyntax.cs | 2 +- .../TestHelpers/TestWithDatabaseBase.cs | 2 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 6 +- .../Web/Mvc/UmbracoViewPageTests.cs | 2 +- .../Web/TemplateUtilitiesTests.cs | 2 +- .../Cache/ApplicationCacheRefresher.cs | 4 +- .../Cache/ApplicationTreeCacheRefresher.cs | 4 +- .../Cache/ContentCacheRefresher.cs | 12 +- .../Cache/DataTypeCacheRefresher.cs | 2 +- src/Umbraco.Web/Cache/MacroCacheRefresher.cs | 12 +- src/Umbraco.Web/Cache/MediaCacheRefresher.cs | 8 +- src/Umbraco.Web/Cache/MemberCacheRefresher.cs | 6 +- .../Cache/MemberGroupCacheRefresher.cs | 2 +- .../Cache/RelationTypeCacheRefresher.cs | 8 +- .../Cache/TemplateCacheRefresher.cs | 2 +- src/Umbraco.Web/Cache/UserCacheRefresher.cs | 4 +- .../Cache/UserGroupCacheRefresher.cs | 10 +- src/Umbraco.Web/CacheHelperExtensions.cs | 2 +- .../Dictionary/UmbracoCultureDictionary.cs | 6 +- .../Editors/ExamineManagementController.cs | 10 +- src/Umbraco.Web/Editors/UsersController.cs | 2 +- src/Umbraco.Web/Macros/MacroRenderer.cs | 2 +- .../Models/Mapping/UserMapperProfile.cs | 2 +- .../PublishedCache/IPublishedSnapshot.cs | 4 +- .../PublishedCache/NuCache/ContentCache.cs | 8 +- .../PublishedCache/NuCache/MediaCache.cs | 8 +- .../PublishedCache/NuCache/MemberCache.cs | 4 +- .../PublishedCache/NuCache/Property.cs | 6 +- .../NuCache/PublishedContent.cs | 10 +- .../NuCache/PublishedSnapshot.cs | 8 +- .../NuCache/PublishedSnapshotService.cs | 8 +- .../PublishedElementPropertyBase.cs | 6 +- .../DictionaryPublishedContent.cs | 4 +- .../PublishedContentCache.cs | 6 +- .../XmlPublishedCache/PublishedMediaCache.cs | 12 +- .../XmlPublishedCache/PublishedMemberCache.cs | 4 +- .../XmlPublishedCache/PublishedSnapshot.cs | 4 +- .../PublishedSnapshotService.cs | 6 +- .../XmlPublishedCache/XmlPublishedContent.cs | 10 +- src/Umbraco.Web/Runtime/WebRuntime.cs | 10 +- .../Services/ApplicationTreeService.cs | 2 +- src/Umbraco.Web/Services/SectionService.cs | 2 +- 108 files changed, 1538 insertions(+), 1440 deletions(-) create mode 100644 src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs create mode 100644 src/Umbraco.Core/Cache/DeepCloneAppCache.cs delete mode 100644 src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs rename src/Umbraco.Core/Cache/{DictionaryCacheProviderBase.cs => FastDictionaryAppCacheBase.cs} (81%) create mode 100644 src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs rename src/Umbraco.Core/Cache/{HttpRequestCacheProvider.cs => HttpRequestAppCache.cs} (53%) create mode 100644 src/Umbraco.Core/Cache/IAppCache.cs create mode 100644 src/Umbraco.Core/Cache/IAppPolicedCache.cs delete mode 100644 src/Umbraco.Core/Cache/ICacheProvider.cs delete mode 100644 src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs create mode 100644 src/Umbraco.Core/Cache/IsolatedCaches.cs delete mode 100644 src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs create mode 100644 src/Umbraco.Core/Cache/NoAppCache.cs delete mode 100644 src/Umbraco.Core/Cache/NullCacheProvider.cs rename src/Umbraco.Core/Cache/{ObjectCacheRuntimeCacheProvider.cs => ObjectCacheAppCache.cs} (73%) delete mode 100644 src/Umbraco.Core/Cache/StaticCacheProvider.cs rename src/Umbraco.Core/Cache/{HttpRuntimeCacheProvider.cs => WebCachingAppCache.cs} (68%) diff --git a/src/Umbraco.Core/Cache/AppCaches.cs b/src/Umbraco.Core/Cache/AppCaches.cs index 7dd95624ef..6372bccbab 100644 --- a/src/Umbraco.Core/Cache/AppCaches.cs +++ b/src/Umbraco.Core/Cache/AppCaches.cs @@ -4,47 +4,41 @@ using System.Web; namespace Umbraco.Core.Cache { /// - /// Represents the application-wide caches. + /// Represents the application caches. /// public class AppCaches { /// - /// Initializes a new instance for use in the web + /// Initializes a new instance of the for use in a web application. /// public AppCaches() - : this( - new HttpRuntimeCacheProvider(HttpRuntime.Cache), - new StaticCacheProvider(), - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())) - { - } + : this(HttpRuntime.Cache) + { } /// - /// Initializes a new instance for use in the web + /// Initializes a new instance of the for use in a web application. /// public AppCaches(System.Web.Caching.Cache cache) : this( - new HttpRuntimeCacheProvider(cache), - new StaticCacheProvider(), - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())) - { - } + new WebCachingAppCache(cache), + new DictionaryCacheProvider(), + new HttpRequestAppCache(), + new IsolatedCaches(t => new ObjectCacheAppCache())) + { } /// - /// Initializes a new instance based on the provided providers + /// Initializes a new instance of the with cache providers. /// public AppCaches( - IRuntimeCacheProvider httpCacheProvider, - ICacheProvider staticCacheProvider, - ICacheProvider requestCacheProvider, - IsolatedRuntimeCache isolatedCacheManager) + IAppPolicedCache runtimeCache, + IAppCache staticCacheProvider, + IAppCache requestCache, + IsolatedCaches isolatedCaches) { - RuntimeCache = httpCacheProvider ?? throw new ArgumentNullException(nameof(httpCacheProvider)); + RuntimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); StaticCache = staticCacheProvider ?? throw new ArgumentNullException(nameof(staticCacheProvider)); - RequestCache = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); - IsolatedRuntimeCache = isolatedCacheManager ?? throw new ArgumentNullException(nameof(isolatedCacheManager)); + RequestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache)); + IsolatedCaches = isolatedCaches ?? throw new ArgumentNullException(nameof(isolatedCaches)); } /// @@ -54,7 +48,7 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies apply, but the underlying caches do not cache anything. /// Used by tests. /// - public static AppCaches Disabled { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches Disabled { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, NoAppCache.Instance, new IsolatedCaches(_ => NoAppCache.Instance)); /// /// Gets the special no-cache instance. @@ -63,27 +57,42 @@ namespace Umbraco.Core.Cache /// When used by repositories, all cache policies are bypassed. /// Used by repositories that do no cache. /// - public static AppCaches NoCache { get; } = new AppCaches(NullCacheProvider.Instance, NullCacheProvider.Instance, NullCacheProvider.Instance, new IsolatedRuntimeCache(_ => NullCacheProvider.Instance)); + public static AppCaches NoCache { get; } = new AppCaches(NoAppCache.Instance, NoAppCache.Instance, NoAppCache.Instance, new IsolatedCaches(_ => NoAppCache.Instance)); /// - /// Returns the current Request cache + /// Gets the per-request cache. /// - public ICacheProvider RequestCache { get; internal set; } + /// + /// The per-request caches works on top of the current HttpContext items. + /// fixme - what about non-web applications? + /// + public IAppCache RequestCache { get; } /// /// Returns the current Runtime cache /// - public ICacheProvider StaticCache { get; internal set; } + /// + /// fixme - what is this? why not use RuntimeCache? + /// + public IAppCache StaticCache { get; } /// - /// Returns the current Runtime cache + /// Gets the runtime cache. /// - public IRuntimeCacheProvider RuntimeCache { get; internal set; } + /// + /// The runtime cache is the main application cache. + /// + public IAppPolicedCache RuntimeCache { get; } /// - /// Returns the current Isolated Runtime cache manager + /// Gets the isolated caches. /// - public IsolatedRuntimeCache IsolatedRuntimeCache { get; internal set; } + /// + /// Isolated caches are used by e.g. repositories, to ensure that each cached entity + /// type has its own cache, so that lookups are fast and the repository does not need to + /// search through all keys on a global scale. + /// + public IsolatedCaches IsolatedCaches { get; } } diff --git a/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs new file mode 100644 index 0000000000..51cc3c4c53 --- /dev/null +++ b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Concurrent; + +namespace Umbraco.Core.Cache +{ + /// + /// Provides a base class for implementing a dictionary of . + /// + /// The type of the dictionary key. + public abstract class AppPolicedCacheDictionary + { + private readonly ConcurrentDictionary _caches = new ConcurrentDictionary(); + + /// + /// Initializes a new instance of the class. + /// + /// + protected AppPolicedCacheDictionary(Func cacheFactory) + { + CacheFactory = cacheFactory; + } + + /// + /// Gets the internal cache factory, for tests only! + /// + internal readonly Func CacheFactory; + + /// + /// Gets or creates a cache. + /// + public IAppPolicedCache GetOrCreate(TKey key) + => _caches.GetOrAdd(key, k => CacheFactory(k)); + + /// + /// Tries to get a cache. + /// + public Attempt Get(TKey key) + => _caches.TryGetValue(key, out var cache) ? Attempt.Succeed(cache) : Attempt.Fail(); + + /// + /// Removes a cache. + /// + public void Remove(TKey key) + { + _caches.TryRemove(key, out _); + } + + /// + /// Removes all caches. + /// + public void RemoveAll() + { + _caches.Clear(); + } + + /// + /// Clears a cache. + /// + public void ClearCache(TKey key) + { + if (_caches.TryGetValue(key, out var cache)) + cache.Clear(); + } + + /// + /// Clears all caches. + /// + public void ClearAllCaches() + { + foreach (var cache in _caches.Values) + cache.Clear(); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs index e42cb4d9ad..0e41b981fb 100644 --- a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs +++ b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.Cache /// public static class CacheProviderExtensions { - public static T GetCacheItem(this IRuntimeCacheProvider provider, + public static T GetCacheItem(this IAppPolicedCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout, @@ -19,11 +19,11 @@ namespace Umbraco.Core.Cache CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { - var result = provider.GetCacheItem(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); + var result = provider.Get(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); return result == null ? default(T) : result.TryConvertTo().Result; } - public static void InsertCacheItem(this IRuntimeCacheProvider provider, + public static void InsertCacheItem(this IAppPolicedCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout = null, @@ -32,24 +32,24 @@ namespace Umbraco.Core.Cache CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { - provider.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); + provider.Insert(cacheKey, () => getCacheItem(), timeout, isSliding, priority, removedCallback, dependentFiles); } - public static IEnumerable GetCacheItemsByKeySearch(this ICacheProvider provider, string keyStartsWith) + public static IEnumerable GetCacheItemsByKeySearch(this IAppCache provider, string keyStartsWith) { - var result = provider.GetCacheItemsByKeySearch(keyStartsWith); + var result = provider.SearchByKey(keyStartsWith); return result.Select(x => x.TryConvertTo().Result); } - public static IEnumerable GetCacheItemsByKeyExpression(this ICacheProvider provider, string regexString) + public static IEnumerable GetCacheItemsByKeyExpression(this IAppCache provider, string regexString) { - var result = provider.GetCacheItemsByKeyExpression(regexString); + var result = provider.SearchByRegex(regexString); return result.Select(x => x.TryConvertTo().Result); } - public static T GetCacheItem(this ICacheProvider provider, string cacheKey) + public static T GetCacheItem(this IAppCache provider, string cacheKey) { - var result = provider.GetCacheItem(cacheKey); + var result = provider.Get(cacheKey); if (result == null) { return default(T); @@ -57,9 +57,9 @@ namespace Umbraco.Core.Cache return result.TryConvertTo().Result; } - public static T GetCacheItem(this ICacheProvider provider, string cacheKey, Func getCacheItem) + public static T GetCacheItem(this IAppCache provider, string cacheKey, Func getCacheItem) { - var result = provider.GetCacheItem(cacheKey, () => getCacheItem()); + var result = provider.Get(cacheKey, () => getCacheItem()); if (result == null) { return default(T); diff --git a/src/Umbraco.Core/Cache/CacheRefresherBase.cs b/src/Umbraco.Core/Cache/CacheRefresherBase.cs index 5e6ec593af..bfa16ff3fa 100644 --- a/src/Umbraco.Core/Cache/CacheRefresherBase.cs +++ b/src/Umbraco.Core/Cache/CacheRefresherBase.cs @@ -102,7 +102,7 @@ namespace Umbraco.Core.Cache protected void ClearAllIsolatedCacheByEntityType() where TEntity : class, IEntity { - AppCaches.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedCaches.ClearCache(); } /// diff --git a/src/Umbraco.Core/Cache/DeepCloneAppCache.cs b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs new file mode 100644 index 0000000000..cdc66f1db7 --- /dev/null +++ b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Caching; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Entities; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements by wrapping an inner other + /// instance, and ensuring that all inserts and returns are deep cloned copies of the cache item, + /// when the item is deep-cloneable. + /// + internal class DeepCloneAppCache : IAppPolicedCache + { + /// + /// Initializes a new instance of the class. + /// + public DeepCloneAppCache(IAppPolicedCache innerCache) + { + var type = typeof (DeepCloneAppCache); + + if (innerCache.GetType() == type) + throw new InvalidOperationException($"A {type} cannot wrap another instance of itself."); + + InnerCache = innerCache; + } + + /// + /// Gets the inner cache. + /// + public IAppPolicedCache InnerCache { get; } + + /// + public object Get(string key) + { + var item = InnerCache.Get(key); + return CheckCloneableAndTracksChanges(item); + } + + /// + public object Get(string key, Func factory) + { + var cached = InnerCache.Get(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + }); + return CheckCloneableAndTracksChanges(cached); + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + return InnerCache.SearchByKey(keyStartsWith) + .Select(CheckCloneableAndTracksChanges); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + return InnerCache.SearchByRegex(regex) + .Select(CheckCloneableAndTracksChanges); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + var cached = InnerCache.Get(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + + // clone / reset to go into the cache + }, timeout, isSliding, priority, removedCallback, dependentFiles); + + // clone / reset to go into the cache + return CheckCloneableAndTracksChanges(cached); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + InnerCache.Insert(key, () => + { + var result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now - this may throw if cacheItem throws, and then nothing goes into cache + // do not store null values (backward compat), clone / reset to go into the cache + return value == null ? null : CheckCloneableAndTracksChanges(value); + }, timeout, isSliding, priority, removedCallback, dependentFiles); + } + + /// + public void Clear() + { + InnerCache.Clear(); + } + + /// + public void Clear(string key) + { + InnerCache.Clear(key); + } + + /// + public void ClearOfType(string typeName) + { + InnerCache.ClearOfType(typeName); + } + + /// + public void ClearOfType() + { + InnerCache.ClearOfType(); + } + + /// + public void ClearOfType(Func predicate) + { + InnerCache.ClearOfType(predicate); + } + + /// + public void ClearByKey(string keyStartsWith) + { + InnerCache.ClearByKey(keyStartsWith); + } + + /// + public void ClearByRegex(string regex) + { + InnerCache.ClearByRegex(regex); + } + + private static object CheckCloneableAndTracksChanges(object input) + { + if (input is IDeepCloneable cloneable) + { + input = cloneable.DeepClone(); + } + + // reset dirty initial properties + if (input is IRememberBeingDirty tracksChanges) + { + tracksChanges.ResetDirtyProperties(false); + input = tracksChanges; + } + + return input; + } + } +} diff --git a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs deleted file mode 100644 index 255d7b526d..0000000000 --- a/src/Umbraco.Core/Cache/DeepCloneRuntimeCacheProvider.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; -using Umbraco.Core.Models; -using Umbraco.Core.Models.Entities; - -namespace Umbraco.Core.Cache -{ - /// - /// Interface describing this cache provider as a wrapper for another - /// - internal interface IRuntimeCacheProviderWrapper - { - IRuntimeCacheProvider InnerProvider { get; } - } - - /// - /// A wrapper for any IRuntimeCacheProvider that ensures that all inserts and returns - /// are a deep cloned copy of the item when the item is IDeepCloneable and that tracks changes are - /// reset if the object is TracksChangesEntityBase - /// - internal class DeepCloneRuntimeCacheProvider : IRuntimeCacheProvider, IRuntimeCacheProviderWrapper - { - public IRuntimeCacheProvider InnerProvider { get; } - - public DeepCloneRuntimeCacheProvider(IRuntimeCacheProvider innerProvider) - { - var type = typeof (DeepCloneRuntimeCacheProvider); - - if (innerProvider.GetType() == type) - throw new InvalidOperationException($"A {type} cannot wrap another instance of {type}."); - - InnerProvider = innerProvider; - } - - #region Clear - doesn't require any changes - - public void ClearAllCache() - { - InnerProvider.ClearAllCache(); - } - - public void ClearCacheItem(string key) - { - InnerProvider.ClearCacheItem(key); - } - - public void ClearCacheObjectTypes(string typeName) - { - InnerProvider.ClearCacheObjectTypes(typeName); - } - - public void ClearCacheObjectTypes() - { - InnerProvider.ClearCacheObjectTypes(); - } - - public void ClearCacheObjectTypes(Func predicate) - { - InnerProvider.ClearCacheObjectTypes(predicate); - } - - public void ClearCacheByKeySearch(string keyStartsWith) - { - InnerProvider.ClearCacheByKeySearch(keyStartsWith); - } - - public void ClearCacheByKeyExpression(string regexString) - { - InnerProvider.ClearCacheByKeyExpression(regexString); - } - - #endregion - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return InnerProvider.GetCacheItemsByKeySearch(keyStartsWith) - .Select(CheckCloneableAndTracksChanges); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return InnerProvider.GetCacheItemsByKeyExpression(regexString) - .Select(CheckCloneableAndTracksChanges); - } - - public object GetCacheItem(string cacheKey) - { - var item = InnerProvider.GetCacheItem(cacheKey); - return CheckCloneableAndTracksChanges(item); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - var cached = InnerProvider.GetCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.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 null; // do not store null values (backward compat) - - return CheckCloneableAndTracksChanges(value); - }); - return CheckCloneableAndTracksChanges(cached); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - var cached = InnerProvider.GetCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.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 null; // do not store null values (backward compat) - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(value); - }, timeout, isSliding, priority, removedCallback, dependentFiles); - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(cached); - } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - InnerProvider.InsertCacheItem(cacheKey, () => - { - var result = DictionaryCacheProviderBase.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 null; // do not store null values (backward compat) - - // clone / reset to go into the cache - return CheckCloneableAndTracksChanges(value); - }, timeout, isSliding, priority, removedCallback, dependentFiles); - } - - private static object CheckCloneableAndTracksChanges(object input) - { - var cloneable = input as IDeepCloneable; - if (cloneable != null) - { - input = cloneable.DeepClone(); - } - - // reset dirty initial properties (U4-1946) - var tracksChanges = input as IRememberBeingDirty; - if (tracksChanges != null) - { - tracksChanges.ResetDirtyProperties(false); - input = tracksChanges; - } - - return input; - } - } -} diff --git a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs index 8387f547d3..6f160cd552 100644 --- a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs @@ -23,7 +23,7 @@ namespace Umbraco.Core.Cache private static readonly TEntity[] EmptyEntities = new TEntity[0]; // const private readonly RepositoryCachePolicyOptions _options; - public DefaultRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public DefaultRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor) { _options = options ?? throw new ArgumentNullException(nameof(options)); @@ -42,7 +42,7 @@ namespace Umbraco.Core.Cache protected virtual void InsertEntity(string cacheKey, TEntity entity) { - Cache.InsertCacheItem(cacheKey, () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(cacheKey, () => entity, TimeSpan.FromMinutes(5), true); } protected virtual void InsertEntities(TId[] ids, TEntity[] entities) @@ -52,7 +52,7 @@ namespace Umbraco.Core.Cache // getting all of them, and finding nothing. // if we can cache a zero count, cache an empty array, // for as long as the cache is not cleared (no expiration) - Cache.InsertCacheItem(GetEntityTypeCacheKey(), () => EmptyEntities); + Cache.Insert(GetEntityTypeCacheKey(), () => EmptyEntities); } else { @@ -60,7 +60,7 @@ namespace Umbraco.Core.Cache foreach (var entity in entities) { var capture = entity; - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => capture, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => capture, TimeSpan.FromMinutes(5), true); } } } @@ -77,21 +77,21 @@ namespace Umbraco.Core.Cache // just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); } // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } catch { // if an exception is thrown we need to remove the entry from cache, // this is ONLY a work around because of the way // that we cache entities: http://issues.umbraco.org/issue/U4-4259 - Cache.ClearCacheItem(GetEntityCacheKey(entity.Id)); + Cache.Clear(GetEntityCacheKey(entity.Id)); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); throw; } @@ -109,21 +109,21 @@ namespace Umbraco.Core.Cache // just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { - Cache.InsertCacheItem(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); + Cache.Insert(GetEntityCacheKey(entity.Id), () => entity, TimeSpan.FromMinutes(5), true); } // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } catch { // if an exception is thrown we need to remove the entry from cache, // this is ONLY a work around because of the way // that we cache entities: http://issues.umbraco.org/issue/U4-4259 - Cache.ClearCacheItem(GetEntityCacheKey(entity.Id)); + Cache.Clear(GetEntityCacheKey(entity.Id)); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); throw; } @@ -142,9 +142,9 @@ namespace Umbraco.Core.Cache { // whatever happens, clear the cache var cacheKey = GetEntityCacheKey(entity.Id); - Cache.ClearCacheItem(cacheKey); + Cache.Clear(cacheKey); // if there's a GetAllCacheAllowZeroCount cache, ensure it is cleared - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } } @@ -238,7 +238,7 @@ namespace Umbraco.Core.Cache /// public override void ClearAll() { - Cache.ClearCacheByKeySearch(GetEntityTypeCacheKey()); + Cache.ClearByKey(GetEntityTypeCacheKey()); } } } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs index 98dceb80b0..2ff5f6ea83 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs +++ b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs @@ -1,147 +1,97 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; -using Umbraco.Core.Composing; namespace Umbraco.Core.Cache { - internal class DictionaryCacheProvider : ICacheProvider + /// + /// Implements on top of a concurrent dictionary. + /// + public class DictionaryCacheProvider : IAppCache { - private readonly ConcurrentDictionary> _items - = new ConcurrentDictionary>(); + /// + /// Gets the internal items dictionary, for tests only! + /// + internal readonly ConcurrentDictionary Items = new ConcurrentDictionary(); - // for tests - internal ConcurrentDictionary> Items => _items; - - public void ClearAllCache() + /// + public virtual object Get(string key) { - _items.Clear(); + // fixme throws if non-existing, shouldn't it return null? + return Items[key]; } - public void ClearCacheItem(string key) + /// + public virtual object Get(string key, Func factory) { - _items.TryRemove(key, out _); + return Items.GetOrAdd(key, _ => factory()); } - public void ClearCacheObjectTypes(string typeName) + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) { - var type = TypeFinder.GetTypeByName(typeName); - if (type == null) return; - var isInterface = type.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy and not null, its value may be null - // remove null values as well, does not hurt - // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - - // if T is an interface remove anything that implements that interface - // otherwise remove exact types (not inherited types) - return value == null || (isInterface ? (type.IsInstanceOfType(value)) : (value.GetType() == type)); - })) - _items.TryRemove(kvp.Key, out _); + var items = new List(); + foreach (var (key, value) in Items) + if (key.InvariantStartsWith(keyStartsWith)) + items.Add(value); + return items; } - public void ClearCacheObjectTypes() + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + var items = new List(); + foreach (var (key, value) in Items) + if (compiled.IsMatch(key)) + items.Add(value); + return items; + } + + /// + public virtual void Clear() + { + Items.Clear(); + } + + /// + public virtual void Clear(string key) + { + Items.TryRemove(key, out _); + } + + /// + public virtual void ClearOfType(string typeName) + { + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); + } + + /// + public virtual void ClearOfType() { var typeOfT = typeof(T); - var isInterface = typeOfT.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy and not null, its value may be null - // remove null values as well, does not hurt - // compare on exact type, don't use "is" - // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - - // if T is an interface remove anything that implements that interface - // otherwise remove exact types (not inherited types) - return value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT)); - })) - _items.TryRemove(kvp.Key, out _); + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); } - public void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { var typeOfT = typeof(T); - var isInterface = typeOfT.IsInterface; - - foreach (var kvp in _items - .Where(x => - { - // entry.Value is Lazy and not null, its value may be null - // remove null values as well, does not hurt - // compare on exact type, don't use "is" - // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue(x.Value, true); - if (value == null) return true; - - // if T is an interface remove anything that implements that interface - // otherwise remove exact types (not inherited types) - return (isInterface ? (value is T) : (value.GetType() == typeOfT)) - // run predicate on the 'public key' part only, ie without prefix - && predicate(x.Key, (T)value); - })) - _items.TryRemove(kvp.Key, out _); + Items.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); } - public void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { - foreach (var ikvp in _items - .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith))) - _items.TryRemove(ikvp.Key, out _); + Items.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); } - public void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { - foreach (var ikvp in _items - .Where(kvp => Regex.IsMatch(kvp.Key, regexString))) - _items.TryRemove(ikvp.Key, out _); - } - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return _items - .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)) - .Select(kvp => DictionaryCacheProviderBase.GetSafeLazyValue(kvp.Value)) - .Where(x => x != null); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return _items - .Where(kvp => Regex.IsMatch(kvp.Key, regexString)) - .Select(kvp => DictionaryCacheProviderBase.GetSafeLazyValue(kvp.Value)) - .Where(x => x != null); - } - - public object GetCacheItem(string cacheKey) - { - _items.TryGetValue(cacheKey, out var result); // else null - return result == null ? null : DictionaryCacheProviderBase.GetSafeLazyValue(result); // return exceptions as null - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - var result = _items.GetOrAdd(cacheKey, k => DictionaryCacheProviderBase.GetSafeLazy(getCacheItem)); - - var value = result.Value; // will not throw (safe lazy) - if (!(value is DictionaryCacheProviderBase.ExceptionHolder eh)) - return value; - - // and... it's in the cache anyway - so contrary to other cache providers, - // which would trick with GetSafeLazyValue, we need to remove by ourselves, - // in order NOT to cache exceptions - - _items.TryRemove(cacheKey, out result); - eh.Exception.Throw(); // throw once! - return null; // never reached + var compiled = new Regex(regex, RegexOptions.Compiled); + Items.RemoveAll(kvp => compiled.IsMatch(kvp.Key)); } } } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs b/src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs similarity index 81% rename from src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs rename to src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs index f556d47a8e..371ab90a57 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs +++ b/src/Umbraco.Core/Cache/FastDictionaryAppCacheBase.cs @@ -8,7 +8,10 @@ using Umbraco.Core.Composing; namespace Umbraco.Core.Cache { - internal abstract class DictionaryCacheProviderBase : ICacheProvider + /// + /// Provides a base class to fast, dictionary-based implementations. + /// + internal abstract class FastDictionaryAppCacheBase : IAppCache { // prefix cache keys so we know which one are ours protected const string CacheItemPrefix = "umbrtmche"; @@ -16,82 +19,75 @@ namespace Umbraco.Core.Cache // an object that represent a value that has not been created yet protected internal static readonly object ValueNotCreated = new object(); - // manupulate the underlying cache entries - // these *must* be called from within the appropriate locks - // and use the full prefixed cache keys - protected abstract IEnumerable GetDictionaryEntries(); - protected abstract void RemoveEntry(string key); - protected abstract object GetEntry(string key); + #region IAppCache - // read-write lock the underlying cache - //protected abstract IDisposable ReadLock { get; } - //protected abstract IDisposable WriteLock { get; } - - protected abstract void EnterReadLock(); - protected abstract void ExitReadLock(); - protected abstract void EnterWriteLock(); - protected abstract void ExitWriteLock(); - - protected string GetCacheKey(string key) + /// + public virtual object Get(string key) { - return string.Format("{0}-{1}", CacheItemPrefix, key); - } - - protected internal static Lazy GetSafeLazy(Func getCacheItem) - { - // try to generate the value and if it fails, - // wrap in an ExceptionHolder - would be much simpler - // to just use lazy.IsValueFaulted alas that field is - // internal - return new Lazy(() => - { - try - { - return getCacheItem(); - } - catch (Exception e) - { - return new ExceptionHolder(ExceptionDispatchInfo.Capture(e)); - } - }); - } - - protected internal static object GetSafeLazyValue(Lazy lazy, bool onlyIfValueIsCreated = false) - { - // if onlyIfValueIsCreated, do not trigger value creation - // must return something, though, to differenciate from null values - if (onlyIfValueIsCreated && lazy.IsValueCreated == false) return ValueNotCreated; - - // if execution has thrown then lazy.IsValueCreated is false - // and lazy.IsValueFaulted is true (but internal) so we use our - // own exception holder (see Lazy source code) to return null - if (lazy.Value is ExceptionHolder) return null; - - // we have a value and execution has not thrown so returning - // here does not throw - unless we're re-entering, take care of it + key = GetCacheKey(key); + Lazy result; try { - return lazy.Value; + EnterReadLock(); + result = GetEntry(key) as Lazy; // null if key not found } - catch (InvalidOperationException e) + finally { - throw new InvalidOperationException("The method that computes a value for the cache has tried to read that value from the cache.", e); + ExitReadLock(); } + return result == null ? null : GetSafeLazyValue(result); // return exceptions as null } - internal class ExceptionHolder + /// + public abstract object Get(string key, Func factory); + + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) { - public ExceptionHolder(ExceptionDispatchInfo e) + var plen = CacheItemPrefix.Length + 1; + IEnumerable entries; + try { - Exception = e; + EnterReadLock(); + entries = GetDictionaryEntries() + .Where(x => ((string)x.Key).Substring(plen).InvariantStartsWith(keyStartsWith)) + .ToArray(); // evaluate while locked + } + finally + { + ExitReadLock(); } - public ExceptionDispatchInfo Exception { get; } + return entries + .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null); // backward compat, don't store null values in the cache } - #region Clear + /// + public virtual IEnumerable SearchByRegex(string regex) + { + const string prefix = CacheItemPrefix + "-"; + var compiled = new Regex(regex, RegexOptions.Compiled); + var plen = prefix.Length; + IEnumerable entries; + try + { + EnterReadLock(); + entries = GetDictionaryEntries() + .Where(x => compiled.IsMatch(((string)x.Key).Substring(plen))) + .ToArray(); // evaluate while locked + } + finally + { + ExitReadLock(); + } + return entries + .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null); // backward compat, don't store null values in the cache + } - public virtual void ClearAllCache() + /// + public virtual void Clear() { try { @@ -106,7 +102,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheItem(string key) + /// + public virtual void Clear(string key) { var cacheKey = GetCacheKey(key); try @@ -120,7 +117,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(string typeName) + /// + public virtual void ClearOfType(string typeName) { var type = TypeFinder.GetTypeByName(typeName); if (type == null) return; @@ -149,7 +147,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes() + /// + public virtual void ClearOfType() { var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; @@ -178,7 +177,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; @@ -210,7 +210,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { var plen = CacheItemPrefix.Length + 1; try @@ -227,14 +228,16 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { + var compiled = new Regex(regex, RegexOptions.Compiled); var plen = CacheItemPrefix.Length + 1; try { EnterWriteLock(); foreach (var entry in GetDictionaryEntries() - .Where(x => Regex.IsMatch(((string)x.Key).Substring(plen), regexString)) + .Where(x => compiled.IsMatch(((string)x.Key).Substring(plen))) .ToArray()) RemoveEntry((string) entry.Key); } @@ -246,67 +249,80 @@ namespace Umbraco.Core.Cache #endregion - #region Get + #region Dictionary - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) + // manipulate the underlying cache entries + // these *must* be called from within the appropriate locks + // and use the full prefixed cache keys + protected abstract IEnumerable GetDictionaryEntries(); + protected abstract void RemoveEntry(string key); + protected abstract object GetEntry(string key); + + // read-write lock the underlying cache + //protected abstract IDisposable ReadLock { get; } + //protected abstract IDisposable WriteLock { get; } + + protected abstract void EnterReadLock(); + protected abstract void ExitReadLock(); + protected abstract void EnterWriteLock(); + protected abstract void ExitWriteLock(); + + protected string GetCacheKey(string key) { - var plen = CacheItemPrefix.Length + 1; - IEnumerable entries; - try - { - EnterReadLock(); - entries = GetDictionaryEntries() - .Where(x => ((string)x.Key).Substring(plen).InvariantStartsWith(keyStartsWith)) - .ToArray(); // evaluate while locked - } - finally - { - ExitReadLock(); - } - - return entries - .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null); // backward compat, don't store null values in the cache + return $"{CacheItemPrefix}-{key}"; } - public virtual IEnumerable GetCacheItemsByKeyExpression(string regexString) + protected internal static Lazy GetSafeLazy(Func getCacheItem) { - const string prefix = CacheItemPrefix + "-"; - var plen = prefix.Length; - IEnumerable entries; - try + // try to generate the value and if it fails, + // wrap in an ExceptionHolder - would be much simpler + // to just use lazy.IsValueFaulted alas that field is + // internal + return new Lazy(() => { - EnterReadLock(); - entries = GetDictionaryEntries() - .Where(x => Regex.IsMatch(((string)x.Key).Substring(plen), regexString)) - .ToArray(); // evaluate while locked - } - finally - { - ExitReadLock(); - } - return entries - .Select(x => GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null); // backward compat, don't store null values in the cache + try + { + return getCacheItem(); + } + catch (Exception e) + { + return new ExceptionHolder(ExceptionDispatchInfo.Capture(e)); + } + }); } - public virtual object GetCacheItem(string cacheKey) + protected internal static object GetSafeLazyValue(Lazy lazy, bool onlyIfValueIsCreated = false) { - cacheKey = GetCacheKey(cacheKey); - Lazy result; + // if onlyIfValueIsCreated, do not trigger value creation + // must return something, though, to differentiate from null values + if (onlyIfValueIsCreated && lazy.IsValueCreated == false) return ValueNotCreated; + + // if execution has thrown then lazy.IsValueCreated is false + // and lazy.IsValueFaulted is true (but internal) so we use our + // own exception holder (see Lazy source code) to return null + if (lazy.Value is ExceptionHolder) return null; + + // we have a value and execution has not thrown so returning + // here does not throw - unless we're re-entering, take care of it try { - EnterReadLock(); - result = GetEntry(cacheKey) as Lazy; // null if key not found + return lazy.Value; } - finally + catch (InvalidOperationException e) { - ExitReadLock(); + throw new InvalidOperationException("The method that computes a value for the cache has tried to read that value from the cache.", e); } - return result == null ? null : GetSafeLazyValue(result); // return exceptions as null } - public abstract object GetCacheItem(string cacheKey, Func getCacheItem); + internal class ExceptionHolder + { + public ExceptionHolder(ExceptionDispatchInfo e) + { + Exception = e; + } + + public ExceptionDispatchInfo Exception { get; } + } #endregion } diff --git a/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs new file mode 100644 index 0000000000..a3863dac52 --- /dev/null +++ b/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Umbraco.Core.Composing; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements a fast on top of a concurrent dictionary. + /// + internal class FastDictionaryCacheProvider : IAppCache + { + /// + /// Gets the internal items dictionary, for tests only! + /// + internal readonly ConcurrentDictionary> Items = new ConcurrentDictionary>(); + + /// + public object Get(string cacheKey) + { + Items.TryGetValue(cacheKey, out var result); // else null + return result == null ? null : FastDictionaryAppCacheBase.GetSafeLazyValue(result); // return exceptions as null + } + + /// + public object Get(string cacheKey, Func getCacheItem) + { + var result = Items.GetOrAdd(cacheKey, k => FastDictionaryAppCacheBase.GetSafeLazy(getCacheItem)); + + var value = result.Value; // will not throw (safe lazy) + if (!(value is FastDictionaryAppCacheBase.ExceptionHolder eh)) + return value; + + // and... it's in the cache anyway - so contrary to other cache providers, + // which would trick with GetSafeLazyValue, we need to remove by ourselves, + // in order NOT to cache exceptions + + Items.TryRemove(cacheKey, out result); + eh.Exception.Throw(); // throw once! + return null; // never reached + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + return Items + .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)) + .Select(kvp => FastDictionaryAppCacheBase.GetSafeLazyValue(kvp.Value)) + .Where(x => x != null); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + return Items + .Where(kvp => compiled.IsMatch(kvp.Key)) + .Select(kvp => FastDictionaryAppCacheBase.GetSafeLazyValue(kvp.Value)) + .Where(x => x != null); + } + + /// + public void Clear() + { + Items.Clear(); + } + + /// + public void Clear(string key) + { + Items.TryRemove(key, out _); + } + + /// + public void ClearOfType(string typeName) + { + var type = TypeFinder.GetTypeByName(typeName); + if (type == null) return; + var isInterface = type.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy and not null, its value may be null + // remove null values as well, does not hurt + // get non-created as NonCreatedValue & exceptions as null + var value = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + + // if T is an interface remove anything that implements that interface + // otherwise remove exact types (not inherited types) + return value == null || (isInterface ? (type.IsInstanceOfType(value)) : (value.GetType() == type)); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearOfType() + { + var typeOfT = typeof(T); + var isInterface = typeOfT.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy and not null, its value may be null + // remove null values as well, does not hurt + // compare on exact type, don't use "is" + // get non-created as NonCreatedValue & exceptions as null + var value = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + + // if T is an interface remove anything that implements that interface + // otherwise remove exact types (not inherited types) + return value == null || (isInterface ? (value is T) : (value.GetType() == typeOfT)); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearOfType(Func predicate) + { + var typeOfT = typeof(T); + var isInterface = typeOfT.IsInterface; + + foreach (var kvp in Items + .Where(x => + { + // entry.Value is Lazy and not null, its value may be null + // remove null values as well, does not hurt + // compare on exact type, don't use "is" + // get non-created as NonCreatedValue & exceptions as null + var value = FastDictionaryAppCacheBase.GetSafeLazyValue(x.Value, true); + if (value == null) return true; + + // if T is an interface remove anything that implements that interface + // otherwise remove exact types (not inherited types) + return (isInterface ? (value is T) : (value.GetType() == typeOfT)) + // run predicate on the 'public key' part only, ie without prefix + && predicate(x.Key, (T)value); + })) + Items.TryRemove(kvp.Key, out _); + } + + /// + public void ClearByKey(string keyStartsWith) + { + foreach (var ikvp in Items + .Where(kvp => kvp.Key.InvariantStartsWith(keyStartsWith))) + Items.TryRemove(ikvp.Key, out _); + } + + /// + public void ClearByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + foreach (var ikvp in Items + .Where(kvp => compiled.IsMatch(kvp.Key))) + Items.TryRemove(ikvp.Key, out _); + } + } +} diff --git a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs index 319d84d41f..3bc4c9d059 100644 --- a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs @@ -24,7 +24,7 @@ namespace Umbraco.Core.Cache private readonly Func _entityGetId; private readonly bool _expires; - public FullDataSetRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) + public FullDataSetRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) : base(cache, scopeAccessor) { _entityGetId = entityGetId; @@ -55,11 +55,11 @@ namespace Umbraco.Core.Cache if (_expires) { - Cache.InsertCacheItem(key, () => new DeepCloneableList(entities), TimeSpan.FromMinutes(5), true); + Cache.Insert(key, () => new DeepCloneableList(entities), TimeSpan.FromMinutes(5), true); } else { - Cache.InsertCacheItem(key, () => new DeepCloneableList(entities)); + Cache.Insert(key, () => new DeepCloneableList(entities)); } } @@ -171,7 +171,7 @@ namespace Umbraco.Core.Cache /// public override void ClearAll() { - Cache.ClearCacheItem(GetEntityTypeCacheKey()); + Cache.Clear(GetEntityTypeCacheKey()); } } } diff --git a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs b/src/Umbraco.Core/Cache/HttpRequestAppCache.cs similarity index 53% rename from src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs rename to src/Umbraco.Core/Cache/HttpRequestAppCache.cs index 52c230ff71..dcb2621d75 100644 --- a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs +++ b/src/Umbraco.Core/Cache/HttpRequestAppCache.cs @@ -7,54 +7,83 @@ using System.Web; namespace Umbraco.Core.Cache { /// - /// A cache provider that caches items in the HttpContext.Items + /// Implements a fast on top of HttpContext.Items. /// /// - /// If the Items collection is null, then this provider has no effect + /// If no current HttpContext items can be found (no current HttpContext, + /// or no Items...) then this cache acts as a pass-through and does not cache + /// anything. /// - internal class HttpRequestCacheProvider : DictionaryCacheProviderBase + internal class HttpRequestAppCache : FastDictionaryAppCacheBase { - // context provider - // the idea is that there is only one, application-wide HttpRequestCacheProvider instance, - // that is initialized with a method that returns the "current" context. - // NOTE - // but then it is initialized with () => new HttpContextWrapper(HttpContent.Current) - // which is higly inefficient because it creates a new wrapper each time we refer to _context() - // so replace it with _context1 and _context2 below + a way to get context.Items. - //private readonly Func _context; - - // NOTE - // and then in almost 100% cases _context2 will be () => HttpContext.Current - // so why not bring that logic in here and fallback on to HttpContext.Current when - // _context1 is null? - //private readonly HttpContextBase _context1; - //private readonly Func _context2; private readonly HttpContextBase _context; - private IDictionary ContextItems - { - //get { return _context1 != null ? _context1.Items : _context2().Items; } - get { return _context != null ? _context.Items : HttpContext.Current.Items; } - } - - private bool HasContextItems - { - get { return (_context != null && _context.Items != null) || HttpContext.Current != null; } - } - - // for unit tests - public HttpRequestCacheProvider(HttpContextBase context) + /// + /// Initializes a new instance of the class with a context, for unit tests! + /// + public HttpRequestAppCache(HttpContextBase context) { _context = context; } - // main constructor - // will use HttpContext.Current - public HttpRequestCacheProvider(/*Func context*/) + /// + /// Initializes a new instance of the class. + /// + /// + /// Will use HttpContext.Current. + /// fixme - should use IHttpContextAccessor + /// + public HttpRequestAppCache() + { } + + private IDictionary ContextItems => _context?.Items ?? HttpContext.Current?.Items; + + private bool HasContextItems => _context?.Items != null || HttpContext.Current != null; + + /// + public override object Get(string key, Func factory) { - //_context2 = context; + //no place to cache so just return the callback result + if (HasContextItems == false) return factory(); + + key = GetCacheKey(key); + + Lazy result; + + try + { + EnterWriteLock(); + result = ContextItems[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 || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null + { + result = GetSafeLazy(factory); + ContextItems[key] = result; + } + } + finally + { + ExitWriteLock(); + } + + // 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; + + var value = result.Value; // will not throw (safe lazy) + if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! + return value; } + #region Entries + protected override IEnumerable GetDictionaryEntries() { const string prefix = CacheItemPrefix + "-"; @@ -62,7 +91,7 @@ namespace Umbraco.Core.Cache if (HasContextItems == false) return Enumerable.Empty(); return ContextItems.Cast() - .Where(x => x.Key is string && ((string)x.Key).StartsWith(prefix)); + .Where(x => x.Key is string s && s.StartsWith(prefix)); } protected override void RemoveEntry(string key) @@ -77,6 +106,8 @@ namespace Umbraco.Core.Cache return HasContextItems ? ContextItems[key] : null; } + #endregion + #region Lock private bool _entered; @@ -103,59 +134,5 @@ namespace Umbraco.Core.Cache } #endregion - - #region Get - - public override object GetCacheItem(string cacheKey, Func getCacheItem) - { - //no place to cache so just return the callback result - if (HasContextItems == false) return getCacheItem(); - - cacheKey = GetCacheKey(cacheKey); - - Lazy result; - - try - { - EnterWriteLock(); - result = ContextItems[cacheKey] 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 || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null - { - result = GetSafeLazy(getCacheItem); - ContextItems[cacheKey] = result; - } - } - finally - { - ExitWriteLock(); - } - - // 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; - - var value = result.Value; // will not throw (safe lazy) - if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! - return value; - } - - #endregion - - #region Insert - #endregion - - private class NoopLocker : DisposableObjectSlim - { - protected override void DisposeResources() - { } - } } } diff --git a/src/Umbraco.Core/Cache/IAppCache.cs b/src/Umbraco.Core/Cache/IAppCache.cs new file mode 100644 index 0000000000..674781f6d6 --- /dev/null +++ b/src/Umbraco.Core/Cache/IAppCache.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace Umbraco.Core.Cache +{ + /// + /// Defines an application cache. + /// + public interface IAppCache + { + /// + /// Gets an item identified by its key. + /// + /// The key of the item. + /// The item, or null if the item was not found. + object Get(string key); + + /// + /// Gets or creates an item identified by its key. + /// + /// The key of the item. + /// A factory function that can create the item. + /// The item. + object Get(string key, Func factory); + + /// + /// Gets items with a key starting with the specified value. + /// + /// The StartsWith value to use in the search. + /// Items matching the search. + IEnumerable SearchByKey(string keyStartsWith); + + /// + /// Gets items with a key matching a regular expression. + /// + /// The regular expression. + /// Items matching the search. + IEnumerable SearchByRegex(string regex); + + /// + /// Removes all items from the cache. + /// + void Clear(); + + /// + /// Removes an item identified by its key from the cache. + /// + /// The key of the item. + void Clear(string key); + + /// + /// Removes items of a specified type from the cache. + /// + /// The name of the type to remove. + /// + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + /// Performs a case-sensitive search. + /// + void ClearOfType(string typeName); + + /// + /// Removes items of a specified type from the cache. + /// + /// The type of the items to remove. + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + void ClearOfType(); + + /// + /// Removes items of a specified type from the cache. + /// + /// The type of the items to remove. + /// The predicate to satisfy. + /// If the type is an interface, then all items of a type implementing that interface are + /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from + /// the specified type are not removed). + void ClearOfType(Func predicate); + + /// + /// Clears items with a key starting with the specified value. + /// + /// The StartsWith value to use in the search. + void ClearByKey(string keyStartsWith); + + /// + /// Clears items with a key matching a regular expression. + /// + /// The regular expression. + void ClearByRegex(string regex); + } +} diff --git a/src/Umbraco.Core/Cache/IAppPolicedCache.cs b/src/Umbraco.Core/Cache/IAppPolicedCache.cs new file mode 100644 index 0000000000..0aee7584df --- /dev/null +++ b/src/Umbraco.Core/Cache/IAppPolicedCache.cs @@ -0,0 +1,54 @@ +using System; +using System.Web.Caching; + +// fixme should this be/support non-web? + +namespace Umbraco.Core.Cache +{ + /// + /// Defines an application cache that support cache policies. + /// + /// A cache policy can be used to cache with timeouts, + /// or depending on files, and with a remove callback, etc. + public interface IAppPolicedCache : IAppCache + { + /// + /// Gets an item identified by its key. + /// + /// The key of the item. + /// A factory function that can create the item. + /// An optional cache timeout. + /// An optional value indicating whether the cache timeout is sliding (default is false). + /// An optional cache priority (default is Normal). + /// An optional callback to handle removals. + /// Files the cache entry depends on. + /// The item. + object Get( + string key, + Func factory, + TimeSpan? timeout, + bool isSliding = false, + CacheItemPriority priority = CacheItemPriority.Normal, + CacheItemRemovedCallback removedCallback = null, + string[] dependentFiles = null); + + /// + /// Inserts an item. + /// + /// The key of the item. + /// A factory function that can create the item. + /// An optional cache timeout. + /// An optional value indicating whether the cache timeout is sliding (default is false). + /// An optional cache priority (default is Normal). + /// An optional callback to handle removals. + /// Files the cache entry depends on. + void Insert( + string key, + Func factory, + TimeSpan? timeout = null, + bool isSliding = false, + CacheItemPriority priority = CacheItemPriority.Normal, + CacheItemRemovedCallback removedCallback = null, + string[] dependentFiles = null); + } +} diff --git a/src/Umbraco.Core/Cache/ICacheProvider.cs b/src/Umbraco.Core/Cache/ICacheProvider.cs deleted file mode 100644 index 177f7570c2..0000000000 --- a/src/Umbraco.Core/Cache/ICacheProvider.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Umbraco.Core.Cache -{ - /// - /// An interface for implementing a basic cache provider - /// - public interface ICacheProvider - { - /// - /// Removes all items from the cache. - /// - void ClearAllCache(); - - /// - /// Removes an item from the cache, identified by its key. - /// - /// The key of the item. - void ClearCacheItem(string key); - - /// - /// Removes items from the cache, of a specified type. - /// - /// The name of the type to remove. - /// - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - /// Performs a case-sensitive search. - /// - void ClearCacheObjectTypes(string typeName); - - /// - /// Removes items from the cache, of a specified type. - /// - /// The type of the items to remove. - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - void ClearCacheObjectTypes(); - - /// - /// Removes items from the cache, of a specified type, satisfying a predicate. - /// - /// The type of the items to remove. - /// The predicate to satisfy. - /// If the type is an interface, then all items of a type implementing that interface are - /// removed. Otherwise, only items of that exact type are removed (items of type inheriting from - /// the specified type are not removed). - void ClearCacheObjectTypes(Func predicate); - - void ClearCacheByKeySearch(string keyStartsWith); - void ClearCacheByKeyExpression(string regexString); - - IEnumerable GetCacheItemsByKeySearch(string keyStartsWith); - IEnumerable GetCacheItemsByKeyExpression(string regexString); - - /// - /// Returns an item with a given key - /// - /// - /// - object GetCacheItem(string cacheKey); - - object GetCacheItem(string cacheKey, Func getCacheItem); - } -} diff --git a/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs deleted file mode 100644 index 9f3d687e1d..0000000000 --- a/src/Umbraco.Core/Cache/IRuntimeCacheProvider.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Runtime.Caching; -using System.Text; -using System.Web.Caching; -using CacheItemPriority = System.Web.Caching.CacheItemPriority; - -namespace Umbraco.Core.Cache -{ - /// - /// An abstract class for implementing a runtime cache provider - /// - /// - /// - public interface IRuntimeCacheProvider : ICacheProvider - { - object GetCacheItem( - string cacheKey, - Func getCacheItem, - TimeSpan? timeout, - bool isSliding = false, - CacheItemPriority priority = CacheItemPriority.Normal, - CacheItemRemovedCallback removedCallback = null, - string[] dependentFiles = null); - - void InsertCacheItem( - string cacheKey, - Func getCacheItem, - TimeSpan? timeout = null, - bool isSliding = false, - CacheItemPriority priority = CacheItemPriority.Normal, - CacheItemRemovedCallback removedCallback = null, - string[] dependentFiles = null); - - } -} diff --git a/src/Umbraco.Core/Cache/IsolatedCaches.cs b/src/Umbraco.Core/Cache/IsolatedCaches.cs new file mode 100644 index 0000000000..bc624be20d --- /dev/null +++ b/src/Umbraco.Core/Cache/IsolatedCaches.cs @@ -0,0 +1,41 @@ +using System; + +namespace Umbraco.Core.Cache +{ + /// + /// Represents a dictionary of for types. + /// + /// + /// Isolated caches are used by e.g. repositories, to ensure that each cached entity + /// type has its own cache, so that lookups are fast and the repository does not need to + /// search through all keys on a global scale. + /// + public class IsolatedCaches : AppPolicedCacheDictionary + { + /// + /// Initializes a new instance of the class. + /// + /// + public IsolatedCaches(Func cacheFactory) + : base(cacheFactory) + { } + + /// + /// Gets a cache. + /// + public IAppPolicedCache GetOrCreate() + => GetOrCreate(typeof(T)); + + /// + /// Tries to get a cache. + /// + public Attempt Get() + => Get(typeof(T)); + + /// + /// Clears a cache. + /// + public void ClearCache() + => ClearCache(typeof(T)); + } +} diff --git a/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs b/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs deleted file mode 100644 index ee73a17532..0000000000 --- a/src/Umbraco.Core/Cache/IsolatedRuntimeCache.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Collections.Concurrent; - -namespace Umbraco.Core.Cache -{ - /// - /// Used to get/create/manipulate isolated runtime cache - /// - /// - /// This is useful for repository level caches to ensure that cache lookups by key are fast so - /// that the repository doesn't need to search through all keys on a global scale. - /// - public class IsolatedRuntimeCache - { - internal Func CacheFactory { get; set; } - - /// - /// Constructor that allows specifying a factory for the type of runtime isolated cache to create - /// - /// - public IsolatedRuntimeCache(Func cacheFactory) - { - CacheFactory = cacheFactory; - } - - private readonly ConcurrentDictionary _isolatedCache = new ConcurrentDictionary(); - - /// - /// Returns an isolated runtime cache for a given type - /// - /// - /// - public IRuntimeCacheProvider GetOrCreateCache() - { - return _isolatedCache.GetOrAdd(typeof(T), type => CacheFactory(type)); - } - - /// - /// Returns an isolated runtime cache for a given type - /// - /// - public IRuntimeCacheProvider GetOrCreateCache(Type type) - { - return _isolatedCache.GetOrAdd(type, t => CacheFactory(t)); - } - - /// - /// Tries to get a cache by the type specified - /// - /// - /// - public Attempt GetCache() - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryGetValue(typeof(T), out cache)) - { - return Attempt.Succeed(cache); - } - return Attempt.Fail(); - } - - /// - /// Clears all values inside this isolated runtime cache - /// - /// - /// - public void ClearCache() - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryGetValue(typeof(T), out cache)) - { - cache.ClearAllCache(); - } - } - - /// - /// Clears all of the isolated caches - /// - public void ClearAllCaches() - { - foreach (var key in _isolatedCache.Keys) - { - IRuntimeCacheProvider cache; - if (_isolatedCache.TryRemove(key, out cache)) - { - cache.ClearAllCache(); - } - } - } - } -} diff --git a/src/Umbraco.Core/Cache/NoAppCache.cs b/src/Umbraco.Core/Cache/NoAppCache.cs new file mode 100644 index 0000000000..8a7e15cb29 --- /dev/null +++ b/src/Umbraco.Core/Cache/NoAppCache.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Caching; + +namespace Umbraco.Core.Cache +{ + /// + /// Implements and do not cache. + /// + public class NoAppCache : IAppPolicedCache + { + private NoAppCache() { } + + /// + /// Gets the singleton instance. + /// + public static NoAppCache Instance { get; } = new NoAppCache(); + + /// + public virtual object Get(string cacheKey) + { + return null; + } + + /// + public virtual object Get(string cacheKey, Func factory) + { + return factory(); + } + + /// + public virtual IEnumerable SearchByKey(string keyStartsWith) + { + return Enumerable.Empty(); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + return Enumerable.Empty(); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + return factory(); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { } + + /// + public virtual void Clear() + { } + + /// + public virtual void Clear(string key) + { } + + /// + public virtual void ClearOfType(string typeName) + { } + + /// + public virtual void ClearOfType() + { } + + /// + public virtual void ClearOfType(Func predicate) + { } + + /// + public virtual void ClearByKey(string keyStartsWith) + { } + + /// + public virtual void ClearByRegex(string regex) + { } + } +} diff --git a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs index a3e7335d7f..acc67be679 100644 --- a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs @@ -13,7 +13,7 @@ namespace Umbraco.Core.Cache public static NoCacheRepositoryCachePolicy Instance { get; } = new NoCacheRepositoryCachePolicy(); - public IRepositoryCachePolicy Scoped(IRuntimeCacheProvider runtimeCache, IScope scope) + public IRepositoryCachePolicy Scoped(IAppPolicedCache runtimeCache, IScope scope) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Core/Cache/NullCacheProvider.cs b/src/Umbraco.Core/Cache/NullCacheProvider.cs deleted file mode 100644 index 78286f75e2..0000000000 --- a/src/Umbraco.Core/Cache/NullCacheProvider.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Caching; - -namespace Umbraco.Core.Cache -{ - /// - /// Represents a cache provider that does not cache anything. - /// - public class NullCacheProvider : IRuntimeCacheProvider - { - private NullCacheProvider() { } - - public static NullCacheProvider Instance { get; } = new NullCacheProvider(); - - public virtual void ClearAllCache() - { } - - public virtual void ClearCacheItem(string key) - { } - - public virtual void ClearCacheObjectTypes(string typeName) - { } - - public virtual void ClearCacheObjectTypes() - { } - - public virtual void ClearCacheObjectTypes(Func predicate) - { } - - public virtual void ClearCacheByKeySearch(string keyStartsWith) - { } - - public virtual void ClearCacheByKeyExpression(string regexString) - { } - - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return Enumerable.Empty(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return Enumerable.Empty(); - } - - public virtual object GetCacheItem(string cacheKey) - { - return default(object); - } - - public virtual object GetCacheItem(string cacheKey, Func getCacheItem) - { - return getCacheItem(); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - return getCacheItem(); - } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { } - } -} diff --git a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs similarity index 73% rename from src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs rename to src/Umbraco.Core/Cache/ObjectCacheAppCache.cs index 8a844bbc9b..9c5917a53c 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs @@ -11,31 +11,142 @@ using CacheItemPriority = System.Web.Caching.CacheItemPriority; namespace Umbraco.Core.Cache { /// - /// Represents a cache provider that caches item in a . - /// A cache provider that wraps the logic of a System.Runtime.Caching.ObjectCache + /// Implements on top of a . /// - /// The is created with name "in-memory". That name is - /// used to retrieve configuration options. It does not identify the memory cache, i.e. - /// each instance of this class has its own, independent, memory cache. - public class ObjectCacheRuntimeCacheProvider : IRuntimeCacheProvider + public class ObjectCacheAppCache : IAppPolicedCache { private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); - internal ObjectCache MemoryCache; /// - /// Used for debugging + /// Initializes a new instance of the . /// - internal Guid InstanceId { get; private set; } - - public ObjectCacheRuntimeCacheProvider() + public ObjectCacheAppCache() { + // the MemoryCache is created with name "in-memory". That name is + // used to retrieve configuration options. It does not identify the memory cache, i.e. + // each instance of this class has its own, independent, memory cache. MemoryCache = new MemoryCache("in-memory"); - InstanceId = Guid.NewGuid(); } - #region Clear + /// + /// Gets the internal memory cache, for tests only! + /// + internal readonly ObjectCache MemoryCache; - public virtual void ClearAllCache() + /// + public object Get(string key) + { + Lazy result; + try + { + _locker.EnterReadLock(); + result = MemoryCache.Get(key) as Lazy; // null if key not found + } + finally + { + if (_locker.IsReadLockHeld) + _locker.ExitReadLock(); + } + return result == null ? null : FastDictionaryAppCacheBase.GetSafeLazyValue(result); // return exceptions as null + } + + /// + public object Get(string key, Func factory) + { + return Get(key, factory, null); + } + + /// + public IEnumerable SearchByKey(string keyStartsWith) + { + KeyValuePair[] entries; + try + { + _locker.EnterReadLock(); + entries = MemoryCache + .Where(x => x.Key.InvariantStartsWith(keyStartsWith)) + .ToArray(); // evaluate while locked + } + finally + { + if (_locker.IsReadLockHeld) + _locker.ExitReadLock(); + } + return entries + .Select(x => FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null) // backward compat, don't store null values in the cache + .ToList(); + } + + /// + public IEnumerable SearchByRegex(string regex) + { + var compiled = new Regex(regex, RegexOptions.Compiled); + + KeyValuePair[] entries; + try + { + _locker.EnterReadLock(); + entries = MemoryCache + .Where(x => compiled.IsMatch(x.Key)) + .ToArray(); // evaluate while locked + } + finally + { + if (_locker.IsReadLockHeld) + _locker.ExitReadLock(); + } + return entries + .Select(x => FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null + .Where(x => x != null) // backward compat, don't store null values in the cache + .ToList(); + } + + /// + public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + // see notes in HttpRuntimeCacheProvider + + Lazy result; + + using (var lck = new UpgradeableReadLock(_locker)) + { + result = MemoryCache.Get(key) as Lazy; + if (result == null || FastDictionaryAppCacheBase.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null + { + result = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); + + lck.UpgradeToWriteLock(); + //NOTE: This does an add or update + MemoryCache.Set(key, result, policy); + } + } + + //return result.Value; + + var value = result.Value; // will not throw (safe lazy) + if (value is FastDictionaryAppCacheBase.ExceptionHolder eh) eh.Exception.Throw(); // throw once! + return value; + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = 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 = FastDictionaryAppCacheBase.GetSafeLazy(factory); + var value = result.Value; // force evaluation now + if (value == null) return; // do not store null values (backward compat) + + var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); + //NOTE: This does an add or update + MemoryCache.Set(key, result, policy); + } + + /// + public virtual void Clear() { try { @@ -50,7 +161,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheItem(string key) + /// + public virtual void Clear(string key) { try { @@ -65,7 +177,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(string typeName) + /// + public virtual void ClearOfType(string typeName) { var type = TypeFinder.GetTypeByName(typeName); if (type == null) return; @@ -79,7 +192,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy and not null, its value may be null // remove null values as well, does not hurt // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); // if T is an interface remove anything that implements that interface // otherwise remove exact types (not inherited types) @@ -96,12 +209,13 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes() + /// + public virtual void ClearOfType() { try { _locker.EnterWriteLock(); - var typeOfT = typeof (T); + var typeOfT = typeof(T); var isInterface = typeOfT.IsInterface; foreach (var key in MemoryCache .Where(x => @@ -109,7 +223,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy and not null, its value may be null // remove null values as well, does not hurt // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); // if T is an interface remove anything that implements that interface // otherwise remove exact types (not inherited types) @@ -127,7 +241,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheObjectTypes(Func predicate) + /// + public virtual void ClearOfType(Func predicate) { try { @@ -140,7 +255,7 @@ namespace Umbraco.Core.Cache // x.Value is Lazy and not null, its value may be null // remove null values as well, does not hurt // get non-created as NonCreatedValue & exceptions as null - var value = DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value, true); + var value = FastDictionaryAppCacheBase.GetSafeLazyValue((Lazy)x.Value, true); if (value == null) return true; // if T is an interface remove anything that implements that interface @@ -159,7 +274,8 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeySearch(string keyStartsWith) + /// + public virtual void ClearByKey(string keyStartsWith) { try { @@ -177,13 +293,16 @@ namespace Umbraco.Core.Cache } } - public virtual void ClearCacheByKeyExpression(string regexString) + /// + public virtual void ClearByRegex(string regex) { + var compiled = new Regex(regex, RegexOptions.Compiled); + try { _locker.EnterWriteLock(); foreach (var key in MemoryCache - .Where(x => Regex.IsMatch(x.Key, regexString)) + .Where(x => compiled.IsMatch(x.Key)) .Select(x => x.Key) .ToArray()) // ToArray required to remove MemoryCache.Remove(key); @@ -195,120 +314,6 @@ namespace Umbraco.Core.Cache } } - #endregion - - #region Get - - public IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - KeyValuePair[] entries; - try - { - _locker.EnterReadLock(); - entries = MemoryCache - .Where(x => x.Key.InvariantStartsWith(keyStartsWith)) - .ToArray(); // evaluate while locked - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - return entries - .Select(x => DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null) // backward compat, don't store null values in the cache - .ToList(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - KeyValuePair[] entries; - try - { - _locker.EnterReadLock(); - entries = MemoryCache - .Where(x => Regex.IsMatch(x.Key, regexString)) - .ToArray(); // evaluate while locked - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - return entries - .Select(x => DictionaryCacheProviderBase.GetSafeLazyValue((Lazy)x.Value)) // return exceptions as null - .Where(x => x != null) // backward compat, don't store null values in the cache - .ToList(); - } - - public object GetCacheItem(string cacheKey) - { - Lazy result; - try - { - _locker.EnterReadLock(); - result = MemoryCache.Get(cacheKey) as Lazy; // null if key not found - } - finally - { - if (_locker.IsReadLockHeld) - _locker.ExitReadLock(); - } - return result == null ? null : DictionaryCacheProviderBase.GetSafeLazyValue(result); // return exceptions as null - } - - public object GetCacheItem(string cacheKey, Func getCacheItem) - { - return GetCacheItem(cacheKey, getCacheItem, null); - } - - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - // see notes in HttpRuntimeCacheProvider - - Lazy result; - - using (var lck = new UpgradeableReadLock(_locker)) - { - result = MemoryCache.Get(cacheKey) as Lazy; - if (result == null || DictionaryCacheProviderBase.GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null - { - result = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); - - lck.UpgradeToWriteLock(); - //NOTE: This does an add or update - MemoryCache.Set(cacheKey, result, policy); - } - } - - //return result.Value; - - var value = result.Value; // will not throw (safe lazy) - if (value is DictionaryCacheProviderBase.ExceptionHolder eh) eh.Exception.Throw(); // throw once! - return value; - } - - #endregion - - #region Insert - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = 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 = DictionaryCacheProviderBase.GetSafeLazy(getCacheItem); - var value = result.Value; // force evaluation now - if (value == null) return; // do not store null values (backward compat) - - var policy = GetPolicy(timeout, isSliding, removedCallback, dependentFiles); - //NOTE: This does an add or update - MemoryCache.Set(cacheKey, result, policy); - } - - #endregion - private static CacheItemPolicy GetPolicy(TimeSpan? timeout = null, bool isSliding = false, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { var absolute = isSliding ? ObjectCache.InfiniteAbsoluteExpiration : (timeout == null ? ObjectCache.InfiniteAbsoluteExpiration : DateTime.Now.Add(timeout.Value)); diff --git a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs index 2d21d410a7..f8bba4b033 100644 --- a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs +++ b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs @@ -13,16 +13,16 @@ namespace Umbraco.Core.Cache internal abstract class RepositoryCachePolicyBase : IRepositoryCachePolicy where TEntity : class, IEntity { - private readonly IRuntimeCacheProvider _globalCache; + private readonly IAppPolicedCache _globalCache; private readonly IScopeAccessor _scopeAccessor; - protected RepositoryCachePolicyBase(IRuntimeCacheProvider globalCache, IScopeAccessor scopeAccessor) + protected RepositoryCachePolicyBase(IAppPolicedCache globalCache, IScopeAccessor scopeAccessor) { _globalCache = globalCache ?? throw new ArgumentNullException(nameof(globalCache)); _scopeAccessor = scopeAccessor ?? throw new ArgumentNullException(nameof(scopeAccessor)); } - protected IRuntimeCacheProvider Cache + protected IAppPolicedCache Cache { get { @@ -32,9 +32,9 @@ namespace Umbraco.Core.Cache case RepositoryCacheMode.Default: return _globalCache; case RepositoryCacheMode.Scoped: - return ambientScope.IsolatedRuntimeCache.GetOrCreateCache(); + return ambientScope.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.None: - return NullCacheProvider.Instance; + return NoAppCache.Instance; default: throw new NotSupportedException($"Repository cache mode {ambientScope.RepositoryCacheMode} is not supported."); } diff --git a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs index d89524d4f9..714798a47c 100644 --- a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Cache internal class SingleItemsOnlyRepositoryCachePolicy : DefaultRepositoryCachePolicy where TEntity : class, IEntity { - public SingleItemsOnlyRepositoryCachePolicy(IRuntimeCacheProvider cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public SingleItemsOnlyRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor, options) { } diff --git a/src/Umbraco.Core/Cache/StaticCacheProvider.cs b/src/Umbraco.Core/Cache/StaticCacheProvider.cs deleted file mode 100644 index 1604add4d7..0000000000 --- a/src/Umbraco.Core/Cache/StaticCacheProvider.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; - -namespace Umbraco.Core.Cache -{ - /// - /// Represents a cache provider that statically caches item in a concurrent dictionary. - /// - public class StaticCacheProvider : ICacheProvider - { - internal readonly ConcurrentDictionary StaticCache = new ConcurrentDictionary(); - - public virtual void ClearAllCache() - { - StaticCache.Clear(); - } - - public virtual void ClearCacheItem(string key) - { - object val; - StaticCache.TryRemove(key, out val); - } - - public virtual void ClearCacheObjectTypes(string typeName) - { - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); - } - - public virtual void ClearCacheObjectTypes() - { - var typeOfT = typeof(T); - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); - } - - public virtual void ClearCacheObjectTypes(Func predicate) - { - var typeOfT = typeof(T); - StaticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); - } - - public virtual void ClearCacheByKeySearch(string keyStartsWith) - { - StaticCache.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); - } - - public virtual void ClearCacheByKeyExpression(string regexString) - { - StaticCache.RemoveAll(kvp => Regex.IsMatch(kvp.Key, regexString)); - } - - public virtual IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) - { - return (from KeyValuePair c in StaticCache - where c.Key.InvariantStartsWith(keyStartsWith) - select c.Value).ToList(); - } - - public IEnumerable GetCacheItemsByKeyExpression(string regexString) - { - return (from KeyValuePair c in StaticCache - where Regex.IsMatch(c.Key, regexString) - select c.Value).ToList(); - } - - public virtual object GetCacheItem(string cacheKey) - { - var result = StaticCache[cacheKey]; - return result; - } - - public virtual object GetCacheItem(string cacheKey, Func getCacheItem) - { - return StaticCache.GetOrAdd(cacheKey, key => getCacheItem()); - } - } -} diff --git a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/WebCachingAppCache.cs similarity index 68% rename from src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs rename to src/Umbraco.Core/Cache/WebCachingAppCache.cs index 835c5d1ee6..b762fcda07 100644 --- a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/WebCachingAppCache.cs @@ -4,14 +4,15 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web.Caching; -using CacheItemPriority = System.Web.Caching.CacheItemPriority; namespace Umbraco.Core.Cache { /// + /// Implements on top of a . /// A CacheProvider that wraps the logic of the HttpRuntime.Cache /// - internal class HttpRuntimeCacheProvider : DictionaryCacheProviderBase, IRuntimeCacheProvider + /// The underlying cache is expected to be HttpRuntime.Cache. + internal class WebCachingAppCache : FastDictionaryAppCacheBase, IAppPolicedCache { // locker object that supports upgradeable read locking // does not need to support recursion if we implement the cache correctly and ensure @@ -21,16 +22,43 @@ namespace Umbraco.Core.Cache private readonly System.Web.Caching.Cache _cache; /// - /// Used for debugging + /// Initializes a new instance of the class. /// - internal Guid InstanceId { get; private set; } - - public HttpRuntimeCacheProvider(System.Web.Caching.Cache cache) + public WebCachingAppCache(System.Web.Caching.Cache cache) { _cache = cache; - InstanceId = Guid.NewGuid(); } + /// + 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, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + CacheDependency dependency = null; + if (dependentFiles != null && dependentFiles.Any()) + { + dependency = new CacheDependency(dependentFiles); + } + return Get(key, factory, timeout, isSliding, priority, removedCallback, dependency); + } + + /// + public void Insert(string key, Func factory, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) + { + CacheDependency dependency = null; + if (dependentFiles != null && dependentFiles.Any()) + { + dependency = new CacheDependency(dependentFiles); + } + Insert(key, factory, timeout, isSliding, priority, removedCallback, dependency); + } + + #region Dictionary + protected override IEnumerable GetDictionaryEntries() { const string prefix = CacheItemPrefix + "-"; @@ -48,6 +76,8 @@ namespace Umbraco.Core.Cache return _cache.Get(key); } + #endregion + #region Lock protected override void EnterReadLock() @@ -74,33 +104,9 @@ namespace Umbraco.Core.Cache #endregion - #region Get - - /// - /// Gets (and adds if necessary) an item from the cache with all of the default parameters - /// - /// - /// - /// - public override object GetCacheItem(string cacheKey, Func getCacheItem) + private object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) { - return GetCacheItem(cacheKey, getCacheItem, null, dependentFiles: null); - } - - /// - /// This overload is here for legacy purposes - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) - { - cacheKey = GetCacheKey(cacheKey); + 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 @@ -133,7 +139,7 @@ namespace Umbraco.Core.Cache try { _locker.EnterReadLock(); - result = _cache.Get(cacheKey) as Lazy; // null if key not found + result = _cache.Get(key) as Lazy; // null if key not found } finally { @@ -145,7 +151,7 @@ namespace Umbraco.Core.Cache using (var lck = new UpgradeableReadLock(_locker)) { - result = _cache.Get(cacheKey) as Lazy; // null if key not found + 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 @@ -153,13 +159,13 @@ namespace Umbraco.Core.Cache if (result == null || GetSafeLazyValue(result, true) == null) // get non-created as NonCreatedValue & exceptions as null { - result = GetSafeLazy(getCacheItem); + result = 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(cacheKey, result, dependency, absolute, sliding, priority, removedCallback); + _cache.Insert(key, result, dependency, absolute, sliding, priority, removedCallback); } } @@ -175,31 +181,7 @@ namespace Umbraco.Core.Cache return value; } - public object GetCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - return GetCacheItem(cacheKey, getCacheItem, timeout, isSliding, priority, removedCallback, dependency); - } - - #endregion - - #region Insert - - /// - /// This overload is here for legacy purposes - /// - /// - /// - /// - /// - /// - /// - /// - internal void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, CacheDependency dependency = null) + private void Insert(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, 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. @@ -225,17 +207,5 @@ namespace Umbraco.Core.Cache _locker.ExitWriteLock(); } } - - public void InsertCacheItem(string cacheKey, Func getCacheItem, TimeSpan? timeout = null, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) - { - CacheDependency dependency = null; - if (dependentFiles != null && dependentFiles.Any()) - { - dependency = new CacheDependency(dependentFiles); - } - InsertCacheItem(cacheKey, getCacheItem, timeout, isSliding, priority, removedCallback, dependency); - } - - #endregion } } diff --git a/src/Umbraco.Core/Composing/TypeLoader.cs b/src/Umbraco.Core/Composing/TypeLoader.cs index acb12ab575..fe277676d7 100644 --- a/src/Umbraco.Core/Composing/TypeLoader.cs +++ b/src/Umbraco.Core/Composing/TypeLoader.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Composing { private const string CacheKey = "umbraco-types.list"; - private readonly IRuntimeCacheProvider _runtimeCache; + private readonly IAppPolicedCache _runtimeCache; private readonly IProfilingLogger _logger; private readonly Dictionary _types = new Dictionary(); @@ -51,7 +51,7 @@ namespace Umbraco.Core.Composing /// The application runtime cache. /// Files storage mode. /// A profiling logger. - public TypeLoader(IRuntimeCacheProvider runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) + public TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) : this(runtimeCache, localTempStorage, logger, true) { } @@ -62,7 +62,7 @@ namespace Umbraco.Core.Composing /// Files storage mode. /// A profiling logger. /// Whether to detect changes using hashes. - internal TypeLoader(IRuntimeCacheProvider runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) + internal TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) { _runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); _localTempStorage = localTempStorage == LocalTempStorage.Unknown ? LocalTempStorage.Default : localTempStorage; @@ -478,7 +478,7 @@ namespace Umbraco.Core.Composing var typesHashFilePath = GetTypesHashFilePath(); DeleteFile(typesHashFilePath, FileDeleteTimeout); - _runtimeCache.ClearCacheItem(CacheKey); + _runtimeCache.Clear(CacheKey); } private Stream GetFileStream(string path, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, int timeoutMilliseconds) diff --git a/src/Umbraco.Core/ConfigsExtensions.cs b/src/Umbraco.Core/ConfigsExtensions.cs index 1414dbc852..9b2abda53c 100644 --- a/src/Umbraco.Core/ConfigsExtensions.cs +++ b/src/Umbraco.Core/ConfigsExtensions.cs @@ -46,7 +46,7 @@ namespace Umbraco.Core configs.Add(() => new CoreDebug()); // GridConfig depends on runtime caches, manifest parsers... and cannot be available during composition - configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); + configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs index 6c16a5e7ef..979eccb839 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration.Grid { class GridConfig : IGridConfig { - public GridConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) { EditorsConfig = new GridEditorsConfig(logger, runtimeCache, configFolder, isDebug); } diff --git a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs index 94249aa135..121b74194c 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs @@ -13,11 +13,11 @@ namespace Umbraco.Core.Configuration.Grid internal class GridEditorsConfig : IGridEditorsConfig { private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _runtimeCache; + private readonly IAppPolicedCache _runtimeCache; private readonly DirectoryInfo _configFolder; private readonly bool _isDebug; - public GridEditorsConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridEditorsConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) { _logger = logger; _runtimeCache = runtimeCache; diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index 59753df66a..fd344674af 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -20,7 +20,7 @@ namespace Umbraco.Core.Manifest { private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); - private readonly IRuntimeCacheProvider _cache; + private readonly IAppPolicedCache _cache; private readonly ILogger _logger; private readonly ManifestValueValidatorCollection _validators; @@ -29,14 +29,14 @@ namespace Umbraco.Core.Manifest /// /// Initializes a new instance of the class. /// - public ManifestParser(IRuntimeCacheProvider cache, ManifestValueValidatorCollection validators, ILogger logger) + public ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, ILogger logger) : this(cache, validators, "~/App_Plugins", logger) { } /// /// Initializes a new instance of the class. /// - private ManifestParser(IRuntimeCacheProvider cache, ManifestValueValidatorCollection validators, string path, ILogger logger) + private ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, string path, ILogger logger) { _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _validators = validators ?? throw new ArgumentNullException(nameof(validators)); diff --git a/src/Umbraco.Core/Models/UserExtensions.cs b/src/Umbraco.Core/Models/UserExtensions.cs index ba4d8cf590..7db3e3adbe 100644 --- a/src/Umbraco.Core/Models/UserExtensions.cs +++ b/src/Umbraco.Core/Models/UserExtensions.cs @@ -54,7 +54,7 @@ namespace Umbraco.Core.Models /// /// A list of 5 different sized avatar URLs /// - internal static string[] GetUserAvatarUrls(this IUser user, ICacheProvider staticCache) + internal static string[] GetUserAvatarUrls(this IUser user, IAppCache staticCache) { // If FIPS is required, never check the Gravatar service as it only supports MD5 hashing. // Unfortunately, if the FIPS setting is enabled on Windows, using MD5 will throw an exception diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs index bd55654809..8df9bf686d 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ConsentRepository.cs @@ -86,7 +86,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Update(dto); entity.ResetDirtyProperties(); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Id)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Id)); } /// diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs index 3517fb3545..9b191d830c 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs @@ -174,8 +174,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement entity.ResetDirtyProperties(); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.ItemKey)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.ItemKey)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Key)); } protected override void PersistDeletedItem(IDictionaryItem entity) @@ -186,8 +186,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Delete("WHERE id = @Id", new { Id = entity.Key }); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.ItemKey)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(entity.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.ItemKey)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(entity.Key)); entity.DeleteDate = DateTime.Now; } @@ -203,8 +203,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Delete("WHERE id = @Id", new { Id = dto.UniqueId }); //Clear the cache entries that exist by uniqueid/item key - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(dto.Key)); - IsolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(dto.UniqueId)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(dto.Key)); + IsolatedCache.Clear(RepositoryCacheKeys.GetKey(dto.UniqueId)); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs index 2626f60123..f106949c77 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs @@ -30,7 +30,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement protected AppCaches GlobalCache { get; } - protected IRuntimeCacheProvider GlobalIsolatedCache => GlobalCache.IsolatedRuntimeCache.GetOrCreateCache(); + protected IAppPolicedCache GlobalIsolatedCache => GlobalCache.IsolatedCaches.GetOrCreate(); protected IScopeAccessor ScopeAccessor { get; } @@ -60,18 +60,18 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// Gets the isolated cache. /// /// Depends on the ambient scope cache mode. - protected IRuntimeCacheProvider IsolatedCache + protected IAppPolicedCache IsolatedCache { get { switch (AmbientScope.RepositoryCacheMode) { case RepositoryCacheMode.Default: - return GlobalCache.IsolatedRuntimeCache.GetOrCreateCache(); + return GlobalCache.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.Scoped: - return AmbientScope.IsolatedRuntimeCache.GetOrCreateCache(); + return AmbientScope.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.None: - return NullCacheProvider.Instance; + return NoAppCache.Instance; default: throw new Exception("oops: cache mode."); } @@ -157,7 +157,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Adds or Updates an entity of type TEntity /// - /// This method is backed by an cache + /// This method is backed by an cache /// public void Save(TEntity entity) { diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index f29109b9d2..e37b5e254e 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -332,10 +332,10 @@ namespace Umbraco.Core.Runtime // is overriden by the web runtime return new AppCaches( - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } // by default, returns null, meaning that Umbraco should auto-detect the application root path. diff --git a/src/Umbraco.Core/Scoping/IScope.cs b/src/Umbraco.Core/Scoping/IScope.cs index eefc964965..de4eef0a08 100644 --- a/src/Umbraco.Core/Scoping/IScope.cs +++ b/src/Umbraco.Core/Scoping/IScope.cs @@ -38,7 +38,7 @@ namespace Umbraco.Core.Scoping /// /// Gets the scope isolated cache. /// - IsolatedRuntimeCache IsolatedRuntimeCache { get; } + IsolatedCaches IsolatedCaches { get; } /// /// Completes the scope. diff --git a/src/Umbraco.Core/Scoping/Scope.cs b/src/Umbraco.Core/Scoping/Scope.cs index b8d4d7b430..aa08016d3c 100644 --- a/src/Umbraco.Core/Scoping/Scope.cs +++ b/src/Umbraco.Core/Scoping/Scope.cs @@ -34,7 +34,7 @@ namespace Umbraco.Core.Scoping private bool _disposed; private bool? _completed; - private IsolatedRuntimeCache _isolatedRuntimeCache; + private IsolatedCaches _isolatedCaches; private IUmbracoDatabase _database; private EventMessages _messages; private ICompletable _fscope; @@ -177,14 +177,14 @@ namespace Umbraco.Core.Scoping } /// - public IsolatedRuntimeCache IsolatedRuntimeCache + public IsolatedCaches IsolatedCaches { get { - if (ParentScope != null) return ParentScope.IsolatedRuntimeCache; + if (ParentScope != null) return ParentScope.IsolatedCaches; - return _isolatedRuntimeCache ?? (_isolatedRuntimeCache - = new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + return _isolatedCaches ?? (_isolatedCaches + = new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } } diff --git a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs index 3b3f90a412..5577508adb 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Services.Implement public class LocalizedTextServiceFileSources { private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _cache; + private readonly IAppPolicedCache _cache; private readonly IEnumerable _supplementFileSources; private readonly DirectoryInfo _fileSourceFolder; @@ -37,7 +37,7 @@ namespace Umbraco.Core.Services.Implement /// public LocalizedTextServiceFileSources( ILogger logger, - IRuntimeCacheProvider cache, + IAppPolicedCache cache, DirectoryInfo fileSourceFolder, IEnumerable supplementFileSources) { @@ -140,7 +140,7 @@ namespace Umbraco.Core.Services.Implement /// /// /// - public LocalizedTextServiceFileSources(ILogger logger, IRuntimeCacheProvider cache, DirectoryInfo fileSourceFolder) + public LocalizedTextServiceFileSources(ILogger logger, IAppPolicedCache cache, DirectoryInfo fileSourceFolder) : this(logger, cache, fileSourceFolder, Enumerable.Empty()) { diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 79162c06ad..41f2bc4951 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -109,6 +109,7 @@ + @@ -118,29 +119,29 @@ - + - - + + - - - + + + - - + + - - + + - + diff --git a/src/Umbraco.Tests/Cache/CacheProviderTests.cs b/src/Umbraco.Tests/Cache/CacheProviderTests.cs index d060df3c56..f2288cbaf2 100644 --- a/src/Umbraco.Tests/Cache/CacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/CacheProviderTests.cs @@ -9,7 +9,7 @@ namespace Umbraco.Tests.Cache { public abstract class CacheProviderTests { - internal abstract ICacheProvider Provider { get; } + internal abstract IAppCache Provider { get; } protected abstract int GetTotalItemCount { get; } [SetUp] @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Cache [TearDown] public virtual void TearDown() { - Provider.ClearAllCache(); + Provider.Clear(); } [Test] @@ -32,11 +32,11 @@ namespace Umbraco.Tests.Cache Assert.Ignore("Do not run for StaticCacheProvider."); Exception exception = null; - var result = Provider.GetCacheItem("blah", () => + var result = Provider.Get("blah", () => { try { - var result2 = Provider.GetCacheItem("blah"); + var result2 = Provider.Get("blah"); } catch (Exception e) { @@ -56,7 +56,7 @@ namespace Umbraco.Tests.Cache object result; try { - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -66,7 +66,7 @@ namespace Umbraco.Tests.Cache try { - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -85,13 +85,13 @@ namespace Umbraco.Tests.Cache object result; - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; return ""; }); - result = Provider.GetCacheItem("Blah", () => + result = Provider.Get("Blah", () => { counter++; return ""; @@ -108,14 +108,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - var result = Provider.GetCacheItemsByKeySearch("Tes"); + var result = Provider.SearchByKey("Tes"); Assert.AreEqual(3, result.Count()); } @@ -127,14 +127,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("TTes1t", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("TTes1t", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheByKeyExpression("^\\w+es\\d.*"); + Provider.ClearByRegex("^\\w+es\\d.*"); Assert.AreEqual(2, GetTotalItemCount); } @@ -146,14 +146,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Tester2", () => cacheContent2); - Provider.GetCacheItem("Tes3", () => cacheContent3); - Provider.GetCacheItem("different4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Tester2", () => cacheContent2); + Provider.Get("Tes3", () => cacheContent3); + Provider.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheByKeySearch("Test"); + Provider.ClearByKey("Test"); Assert.AreEqual(2, GetTotalItemCount); } @@ -165,15 +165,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheItem("Test1"); - Provider.ClearCacheItem("Test2"); + Provider.Clear("Test1"); + Provider.Clear("Test2"); Assert.AreEqual(2, GetTotalItemCount); } @@ -185,14 +185,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearAllCache(); + Provider.Clear(); Assert.AreEqual(0, GetTotalItemCount); } @@ -201,7 +201,7 @@ namespace Umbraco.Tests.Cache public void Can_Add_When_Not_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - Provider.GetCacheItem("Test1", () => cacheContent1); + Provider.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); } @@ -209,8 +209,8 @@ namespace Umbraco.Tests.Cache public void Can_Get_When_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - var result = Provider.GetCacheItem("Test1", () => cacheContent1); - var result2 = Provider.GetCacheItem("Test1", () => cacheContent1); + var result = Provider.Get("Test1", () => cacheContent1); + var result2 = Provider.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); Assert.AreEqual(result, result2); } @@ -222,15 +222,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); //Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent"); - Provider.ClearCacheObjectTypes(typeof(MacroCacheContent).ToString()); + Provider.ClearOfType(typeof(MacroCacheContent).ToString()); Assert.AreEqual(1, GetTotalItemCount); } @@ -242,14 +242,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.GetCacheItem("Test1", () => cacheContent1); - Provider.GetCacheItem("Test2", () => cacheContent2); - Provider.GetCacheItem("Test3", () => cacheContent3); - Provider.GetCacheItem("Test4", () => cacheContent4); + Provider.Get("Test1", () => cacheContent1); + Provider.Get("Test2", () => cacheContent2); + Provider.Get("Test3", () => cacheContent3); + Provider.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearCacheObjectTypes(); + Provider.ClearOfType(); Assert.AreEqual(1, GetTotalItemCount); } diff --git a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs index 169100153e..5158989a8b 100644 --- a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class DeepCloneRuntimeCacheProviderTests : RuntimeCacheProviderTests { - private DeepCloneRuntimeCacheProvider _provider; + private DeepCloneAppCache _provider; protected override int GetTotalItemCount { @@ -26,15 +26,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new DeepCloneRuntimeCacheProvider(new HttpRuntimeCacheProvider(HttpRuntime.Cache)); + _provider = new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache)); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } @@ -75,15 +75,15 @@ namespace Umbraco.Tests.Cache public void DoesNotCacheExceptions() { string value; - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(1)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(2)); }); // does not throw - value = (string)_provider.GetCacheItem("key", () => GetValue(3)); + value = (string)_provider.Get("key", () => GetValue(3)); Assert.AreEqual("succ3", value); // cache - value = (string)_provider.GetCacheItem("key", () => GetValue(4)); + value = (string)_provider.Get("key", () => GetValue(4)); Assert.AreEqual("succ3", value); } diff --git a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs index 37488600c7..0f649328fe 100644 --- a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs @@ -28,8 +28,8 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { @@ -45,8 +45,8 @@ namespace Umbraco.Tests.Cache [Test] public void Get_Single_From_Cache() { - var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); + var cache = new Mock(); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -58,14 +58,14 @@ namespace Umbraco.Tests.Cache public void Caches_Per_Id_For_Get_All() { var cached = new List(); - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { cached.Add(cacheKey); }); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new AuditItem[] {}); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] {}); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -81,8 +81,8 @@ namespace Umbraco.Tests.Cache [Test] public void Get_All_Without_Ids_From_Cache() { - var cache = new Mock(); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new[] + var cache = new Mock(); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new[] { new AuditItem(1, AuditType.Copy, 123, "test", "blah"), new AuditItem(2, AuditType.Copy, 123, "test", "blah2") @@ -98,8 +98,8 @@ namespace Umbraco.Tests.Cache public void If_CreateOrUpdate_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; @@ -124,8 +124,8 @@ namespace Umbraco.Tests.Cache public void If_Removes_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; diff --git a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs index 404587bcfa..7c5a1524d2 100644 --- a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs @@ -37,8 +37,8 @@ namespace Umbraco.Tests.Cache }; var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { @@ -60,8 +60,8 @@ namespace Umbraco.Tests.Cache new AuditItem(2, AuditType.Copy, 123, "test", "blah2") }; - var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); + var cache = new Mock(); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new FullDataSetRepositoryCachePolicy(cache.Object, DefaultAccessor, item => item.Id, false); @@ -78,8 +78,8 @@ namespace Umbraco.Tests.Cache IList list = null; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { @@ -87,7 +87,7 @@ namespace Umbraco.Tests.Cache list = o() as IList; }); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(() => + cache.Setup(x => x.Get(It.IsAny())).Returns(() => { //return null if this is the first pass return cached.Any() ? new DeepCloneableList(ListCloneBehavior.CloneOnce) : null; @@ -121,8 +121,8 @@ namespace Umbraco.Tests.Cache var cached = new List(); IList list = null; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { @@ -130,7 +130,7 @@ namespace Umbraco.Tests.Cache list = o() as IList; }); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(new AuditItem[] { }); + cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new FullDataSetRepositoryCachePolicy(cache.Object, DefaultAccessor, item => item.Id, false); @@ -145,9 +145,9 @@ namespace Umbraco.Tests.Cache { var getAll = new[] { (AuditItem)null }; - var cache = new Mock(); + var cache = new Mock(); - cache.Setup(x => x.GetCacheItem(It.IsAny())).Returns(() => new DeepCloneableList(ListCloneBehavior.CloneOnce) + cache.Setup(x => x.Get(It.IsAny())).Returns(() => new DeepCloneableList(ListCloneBehavior.CloneOnce) { new AuditItem(1, AuditType.Copy, 123, "test", "blah"), new AuditItem(2, AuditType.Copy, 123, "test", "blah2") @@ -169,8 +169,8 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; @@ -201,8 +201,8 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); - cache.Setup(x => x.ClearCacheItem(It.IsAny())) + var cache = new Mock(); + cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { cacheCleared = true; diff --git a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs index cbb8d4e49d..f442319d7f 100644 --- a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs @@ -7,17 +7,17 @@ namespace Umbraco.Tests.Cache [TestFixture] public class HttpRequestCacheProviderTests : CacheProviderTests { - private HttpRequestCacheProvider _provider; + private HttpRequestAppCache _provider; private FakeHttpContextFactory _ctx; public override void Setup() { base.Setup(); _ctx = new FakeHttpContextFactory("http://localhost/test"); - _provider = new HttpRequestCacheProvider(_ctx.HttpContext); + _provider = new HttpRequestAppCache(_ctx.HttpContext); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } @@ -31,22 +31,22 @@ namespace Umbraco.Tests.Cache [TestFixture] public class StaticCacheProviderTests : CacheProviderTests { - private StaticCacheProvider _provider; + private DictionaryCacheProvider _provider; public override void Setup() { base.Setup(); - _provider = new StaticCacheProvider(); + _provider = new DictionaryCacheProvider(); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } protected override int GetTotalItemCount { - get { return _provider.StaticCache.Count; } + get { return _provider.Items.Count; } } } } diff --git a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs index 679b8c5125..56f3303e9c 100644 --- a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs @@ -9,7 +9,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class HttpRuntimeCacheProviderTests : RuntimeCacheProviderTests { - private HttpRuntimeCacheProvider _provider; + private WebCachingAppCache _provider; protected override int GetTotalItemCount { @@ -19,15 +19,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new HttpRuntimeCacheProvider(HttpRuntime.Cache); + _provider = new WebCachingAppCache(HttpRuntime.Cache); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } @@ -36,15 +36,15 @@ namespace Umbraco.Tests.Cache public void DoesNotCacheExceptions() { string value; - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_provider.GetCacheItem("key", () => GetValue(2)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(1)); }); + Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(2)); }); // does not throw - value = (string)_provider.GetCacheItem("key", () => GetValue(3)); + value = (string)_provider.Get("key", () => GetValue(3)); Assert.AreEqual("succ3", value); // cache - value = (string)_provider.GetCacheItem("key", () => GetValue(4)); + value = (string)_provider.Get("key", () => GetValue(4)); Assert.AreEqual("succ3", value); } diff --git a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs index e373fdda4d..6ed7f590e0 100644 --- a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs @@ -10,7 +10,7 @@ namespace Umbraco.Tests.Cache [TestFixture] public class ObjectCacheProviderTests : RuntimeCacheProviderTests { - private ObjectCacheRuntimeCacheProvider _provider; + private ObjectCacheAppCache _provider; protected override int GetTotalItemCount { @@ -20,15 +20,15 @@ namespace Umbraco.Tests.Cache public override void Setup() { base.Setup(); - _provider = new ObjectCacheRuntimeCacheProvider(); + _provider = new ObjectCacheAppCache(); } - internal override ICacheProvider Provider + internal override IAppCache Provider { get { return _provider; } } - internal override IRuntimeCacheProvider RuntimeProvider + internal override IAppPolicedCache RuntimeProvider { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 12ea87087d..79d0dfb9da 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -63,7 +63,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml = new XmlDocument(); _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); - var cacheProvider = new StaticCacheProvider(); + var cacheProvider = new DictionaryCacheProvider(); var domainCache = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot( new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs index 6add88009d..ee16a1dede 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var mChild2 = MakeNewMedia("Child2", mType, user, mRoot2.Id); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var roots = cache.GetAtRoot(); Assert.AreEqual(2, roots.Count()); Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id})); @@ -93,7 +93,7 @@ namespace Umbraco.Tests.Cache.PublishedCache //var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234)); var umbracoContext = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var publishedMedia = cache.GetById(mRoot.Id); Assert.IsNotNull(publishedMedia); @@ -204,7 +204,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var result = new SearchResult("1234", 1, () => fields.ToDictionary(x => x.Key, x => new List { x.Value })); - var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result)); DoAssert(doc, 1234, key, templateIdVal: null, 0, "/media/test.jpg", "Image", 23, "Shannon", "Shannon", 0, 0, "-1,1234", DateTime.Parse("2012-07-17T10:34:09"), DateTime.Parse("2012-07-16T10:34:09"), 2); @@ -220,7 +220,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var xmlDoc = GetMediaXml(); ((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString()); var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator(); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true)); DoAssert(doc, 2000, key, templateIdVal: null, 2, "image1", "Image", 23, "Shannon", "Shannon", 33, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1); diff --git a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs index e45dfd4250..08eb5e9a60 100644 --- a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs @@ -8,7 +8,7 @@ namespace Umbraco.Tests.Cache public abstract class RuntimeCacheProviderTests : CacheProviderTests { - internal abstract IRuntimeCacheProvider RuntimeProvider { get; } + internal abstract IAppPolicedCache RuntimeProvider { get; } [Test] @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Cache public void Can_Add_And_Expire_Struct_Strongly_Typed_With_Null() { var now = DateTime.Now; - RuntimeProvider.InsertCacheItem("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); + RuntimeProvider.Insert("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); diff --git a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs index 1c2227f79b..2b37d85801 100644 --- a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs @@ -28,14 +28,14 @@ namespace Umbraco.Tests.Cache public void Get_All_Doesnt_Cache() { var cached = new List(); - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => { cached.Add(cacheKey); }); - cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny())).Returns(new AuditItem[] { }); + cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new AuditItem[] { }); var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -52,8 +52,8 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); - cache.Setup(x => x.InsertCacheItem(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), + var cache = new Mock(); + cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => { diff --git a/src/Umbraco.Tests/Composing/ComposingTestBase.cs b/src/Umbraco.Tests/Composing/ComposingTestBase.cs index 48850afd97..407d953509 100644 --- a/src/Umbraco.Tests/Composing/ComposingTestBase.cs +++ b/src/Umbraco.Tests/Composing/ComposingTestBase.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Composing { ProfilingLogger = new ProfilingLogger(Mock.Of(), Mock.Of()); - TypeLoader = new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, ProfilingLogger, detectChanges: false) + TypeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, ProfilingLogger, detectChanges: false) { AssembliesToScan = AssembliesToScan }; diff --git a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs index 1649f3675d..add3424599 100644 --- a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Composing public void Initialize() { // this ensures it's reset - _typeLoader = new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of())); + _typeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of())); foreach (var file in Directory.GetFiles(IOHelper.MapPath(SystemDirectories.TempData.EnsureEndsWith('/') + "TypesCache"))) File.Delete(file); diff --git a/src/Umbraco.Tests/CoreThings/UdiTests.cs b/src/Umbraco.Tests/CoreThings/UdiTests.cs index 2b4ace8810..35080e8c24 100644 --- a/src/Umbraco.Tests/CoreThings/UdiTests.cs +++ b/src/Umbraco.Tests/CoreThings/UdiTests.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.CoreThings var container = new Mock(); var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); container.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns( - new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); + new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); Current.Factory = container.Object; Udi.ResetUdiTypes(); diff --git a/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs b/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs index 7508395c64..088ef6b54b 100644 --- a/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs +++ b/src/Umbraco.Tests/FrontEnd/UmbracoHelperTests.cs @@ -413,7 +413,7 @@ namespace Umbraco.Tests.FrontEnd container .Setup(x => x.GetInstance(typeof(TypeLoader))) .Returns(new TypeLoader( - NullCacheProvider.Instance, + NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()) ) diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 23e198b778..225bd17618 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -22,10 +22,10 @@ namespace Umbraco.Tests.Macros { //we DO want cache enabled for these tests var cacheHelper = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new ObjectCacheAppCache())); //Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of(), Mock.Of())); Current.Reset(); diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index ce3d1d705c..74f9fd7157 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.Manifest new RequiredValidator(Mock.Of()), new RegexValidator(Mock.Of(), null) }; - _parser = new ManifestParser(NullCacheProvider.Instance, new ManifestValueValidatorCollection(validators), Mock.Of()); + _parser = new ManifestParser(NoAppCache.Instance, new ManifestValueValidatorCollection(validators), Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Models/ContentTests.cs b/src/Umbraco.Tests/Models/ContentTests.cs index ea5614fb85..14f766fba1 100644 --- a/src/Umbraco.Tests/Models/ContentTests.cs +++ b/src/Umbraco.Tests/Models/ContentTests.cs @@ -232,8 +232,8 @@ namespace Umbraco.Tests.Models content.UpdateDate = DateTime.Now; content.WriterId = 23; - var runtimeCache = new ObjectCacheRuntimeCacheProvider(); - runtimeCache.InsertCacheItem(content.Id.ToString(CultureInfo.InvariantCulture), () => content); + var runtimeCache = new ObjectCacheAppCache(); + runtimeCache.Insert(content.Id.ToString(CultureInfo.InvariantCulture), () => content); var proflog = GetTestProfilingLogger(); @@ -241,7 +241,7 @@ namespace Umbraco.Tests.Models { for (int j = 0; j < 1000; j++) { - var clone = runtimeCache.GetCacheItem(content.Id.ToString(CultureInfo.InvariantCulture)); + var clone = runtimeCache.Get(content.Id.ToString(CultureInfo.InvariantCulture)); } } diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index 772147f5ad..1641631f43 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -76,10 +76,10 @@ namespace Umbraco.Tests.Persistence.Repositories public void CacheActiveForIntsAndGuids() { var realCache = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - new StaticCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + new DictionaryCacheProvider(), + new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs index 5e1900b29e..33c8524bb4 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs @@ -47,10 +47,10 @@ namespace Umbraco.Tests.Persistence.Repositories MediaTypeRepository mediaTypeRepository; var realCache = new AppCaches( - new ObjectCacheRuntimeCacheProvider(), - new StaticCacheProvider(), - new StaticCacheProvider(), - new IsolatedRuntimeCache(t => new ObjectCacheRuntimeCacheProvider())); + new ObjectCacheAppCache(), + new DictionaryCacheProvider(), + new DictionaryCacheProvider(), + new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) diff --git a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs index 33a595626e..04444855fb 100644 --- a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs +++ b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs @@ -118,8 +118,8 @@ namespace Umbraco.Tests.Published publishedContentTypeFactory.CreatePropertyType("prop1", 1), }); - var elementsCache = new DictionaryCacheProvider(); - var snapshotCache = new DictionaryCacheProvider(); + var elementsCache = new FastDictionaryCacheProvider(); + var snapshotCache = new FastDictionaryCacheProvider(); var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.SnapshotCache).Returns(snapshotCache); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs index 6b280832da..5b1dcde728 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs @@ -40,7 +40,7 @@ namespace Umbraco.Tests.PublishedContent Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); } - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 603464e18b..e798be82c4 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -74,7 +74,7 @@ namespace Umbraco.Tests.PublishedContent ContentTypesCache.GetPublishedContentTypeByAlias = alias => alias.InvariantEquals("home") ? homeType : anythingType; } - protected override TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 4f55b4fd71..4257e3dabb 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -68,7 +68,7 @@ namespace Umbraco.Tests.PublishedContent internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) { var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), - ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, + ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var doc = cache.GetById(id); Assert.IsNotNull(doc); @@ -126,7 +126,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -156,7 +156,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //ensure it is found var publishedMedia = cache.GetById(3113); @@ -203,7 +203,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -231,7 +231,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -259,7 +259,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -288,7 +288,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -314,7 +314,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -482,7 +482,7 @@ namespace Umbraco.Tests.PublishedContent "); var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var nav = node.CreateNavigator(); @@ -502,7 +502,7 @@ namespace Umbraco.Tests.PublishedContent var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); var nav = errorXml.CreateNavigator(); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new StaticCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); Assert.IsNull(converted); diff --git a/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs index deaecf821e..f7077ecb3a 100644 --- a/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs +++ b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs @@ -36,9 +36,9 @@ namespace Umbraco.Tests.PublishedContent public void Resync() { } - public ICacheProvider SnapshotCache => null; + public IAppCache SnapshotCache => null; - public ICacheProvider ElementsCache => null; + public IAppCache ElementsCache => null; } class SolidPublishedContentCache : PublishedCacheBase, IPublishedContentCache, IPublishedMediaCache diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 5d4fa4f182..6e01de1670 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -41,10 +41,10 @@ namespace Umbraco.Tests.Scoping { // this is what's created core web runtime return new AppCaches( - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()), - new StaticCacheProvider(), - NullCacheProvider.Instance, - new IsolatedRuntimeCache(type => new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()), + new DictionaryCacheProvider(), + NoAppCache.Instance, + new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } [TearDown] @@ -60,13 +60,13 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.UserService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof(IUser)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User("name", "email", "username", "rawPassword"); service.Save(user); // global cache contains the entity - var globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + var globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -85,20 +85,20 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (IUser)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IUser)); Assert.AreNotSame(globalCache, scopedCache); user.Name = "changed"; service.Save(user); // scoped cache contains the "new" entity - var scopeCached = (IUser) scopedCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + var scopeCached = (IUser) scopedCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(user.Id, scopeCached.Id); Assert.AreEqual("changed", scopeCached.Name); // global cache is unchanged - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); @@ -108,7 +108,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); if (complete) { // global cache has been cleared @@ -125,7 +125,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "changed" : "name", user.Name); // global cache contains the entity again - globalCached = (IUser) globalCache.GetCacheItem(GetCacheIdKey(user.Id), () => null); + globalCached = (IUser) globalCache.Get(GetCacheIdKey(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual(complete ? "changed" : "name", globalCached.Name); @@ -137,18 +137,18 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof (ILanguage)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (ILanguage)); var lang = (ILanguage) new Language("fr-FR"); service.Save(lang); // global cache has been flushed, reload - var globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + var globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(globalFullCached); var reload = service.GetLanguageById(lang.Id); // global cache contains the entity - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); var globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -166,19 +166,19 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (ILanguage)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (ILanguage)); Assert.AreNotSame(globalCache, scopedCache); lang.IsoCode = "de-DE"; service.Save(lang); // scoped cache has been flushed, reload - var scopeFullCached = (IEnumerable) scopedCache.GetCacheItem(GetCacheTypeKey(), () => null); + var scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNull(scopeFullCached); reload = service.GetLanguageById(lang.Id); // scoped cache contains the "new" entity - scopeFullCached = (IEnumerable) scopedCache.GetCacheItem(GetCacheTypeKey(), () => null); + scopeFullCached = (IEnumerable) scopedCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(scopeFullCached); var scopeCached = scopeFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(scopeCached); @@ -186,7 +186,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual("de-DE", scopeCached.IsoCode); // global cache is unchanged - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -198,7 +198,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); if (complete) { // global cache has been cleared @@ -215,7 +215,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "de-DE" : "fr-FR", lang.IsoCode); // global cache contains the entity again - globalFullCached = (IEnumerable) globalCache.GetCacheItem(GetCacheTypeKey(), () => null); + globalFullCached = (IEnumerable) globalCache.Get(GetCacheTypeKey(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); @@ -229,7 +229,7 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedRuntimeCache.GetOrCreateCache(typeof (IDictionaryItem)); + var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); var lang = (ILanguage)new Language("fr-FR"); service.Save(lang); @@ -242,7 +242,7 @@ namespace Umbraco.Tests.Scoping service.Save(item); // global cache contains the entity - var globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + var globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -258,20 +258,20 @@ namespace Umbraco.Tests.Scoping Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache - var scopedCache = scope.IsolatedRuntimeCache.GetOrCreateCache(typeof (IDictionaryItem)); + var scopedCache = scope.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); Assert.AreNotSame(globalCache, scopedCache); item.ItemKey = "item-changed"; service.Save(item); // scoped cache contains the "new" entity - var scopeCached = (IDictionaryItem) scopedCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + var scopeCached = (IDictionaryItem) scopedCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(item.Id, scopeCached.Id); Assert.AreEqual("item-changed", scopeCached.ItemKey); // global cache is unchanged - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); @@ -281,7 +281,7 @@ namespace Umbraco.Tests.Scoping } Assert.IsNull(scopeProvider.AmbientScope); - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); if (complete) { // global cache has been cleared @@ -298,7 +298,7 @@ namespace Umbraco.Tests.Scoping Assert.AreEqual(complete ? "item-changed" : "item-key", item.ItemKey); // global cache contains the entity again - globalCached = (IDictionaryItem) globalCache.GetCacheItem(GetCacheIdKey(item.Id), () => null); + globalCached = (IDictionaryItem) globalCache.Get(GetCacheIdKey(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", globalCached.ItemKey); diff --git a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs index 7fd2f0f18b..35fcc853d4 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs @@ -38,7 +38,7 @@ namespace Umbraco.Tests.TestHelpers var container = RegisterFactory.Create(); var logger = new ProfilingLogger(Mock.Of(), Mock.Of()); - var typeLoader = new TypeLoader(NullCacheProvider.Instance, + var typeLoader = new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, logger, false); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 0729aa0b6e..2deb30bbdd 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -246,7 +246,7 @@ namespace Umbraco.Tests.TestHelpers protected virtual IPublishedSnapshotService CreatePublishedSnapshotService() { - var cache = NullCacheProvider.Instance; + var cache = NoAppCache.Instance; ContentTypesCache = new PublishedContentTypeCache( Factory.GetInstance(), diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index c980f9c1ee..2d6e01b6bb 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -245,7 +245,7 @@ namespace Umbraco.Tests.Testing .ComposeWebMappingProfiles(); } - protected virtual TypeLoader GetTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) + protected virtual TypeLoader GetTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) { switch (option) { @@ -260,13 +260,13 @@ namespace Umbraco.Tests.Testing } } - protected virtual TypeLoader CreateTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected virtual TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return CreateCommonTypeLoader(runtimeCache, globalSettings, logger); } // common to all tests = cannot be overriden - private static TypeLoader CreateCommonTypeLoader(IRuntimeCacheProvider runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + private static TypeLoader CreateCommonTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return new TypeLoader(runtimeCache, globalSettings.LocalTempStorageLocation, logger, false) { diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index 192b0975d1..133cbb2ee7 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -415,7 +415,7 @@ namespace Umbraco.Tests.Web.Mvc // CacheHelper.CreateDisabledCacheHelper(), // new ProfilingLogger(logger, Mock.Of())) { /*IsReady = true*/ }; - var cache = NullCacheProvider.Instance; + var cache = NoAppCache.Instance; //var provider = new ScopeUnitOfWorkProvider(databaseFactory, new RepositoryFactory(Mock.Of())); var scopeProvider = TestObjects.GetScopeProvider(Mock.Of()); var factory = Mock.Of(); diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index 047d0b0b8f..e95ae7b785 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -39,7 +39,7 @@ namespace Umbraco.Tests.Web // fixme - bad in a unit test - but Udi has a static ctor that wants it?! var factory = new Mock(); factory.Setup(x => x.GetInstance(typeof(TypeLoader))).Returns( - new TypeLoader(NullCacheProvider.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); + new TypeLoader(NoAppCache.Instance, LocalTempStorage.Default, new ProfilingLogger(Mock.Of(), Mock.Of()))); factory.Setup(x => x.GetInstance(typeof (ServiceContext))).Returns(serviceContext); var settings = SettingsForTests.GetDefaultUmbracoSettings(); diff --git a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs index cf93b44215..751b2194b7 100644 --- a/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationCacheRefresher.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs index 72fceec631..4d2dcd8efb 100644 --- a/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ApplicationTreeCacheRefresher.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); base.RefreshAll(); } @@ -37,7 +37,7 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - AppCaches.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + AppCaches.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs index 3ae2f8e3dd..36397540b6 100644 --- a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs @@ -44,14 +44,14 @@ namespace Umbraco.Web.Cache public override void Refresh(JsonPayload[] payloads) { - AppCaches.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearOfType(); var idsRemoved = new HashSet(); - var isolatedCache = AppCaches.IsolatedRuntimeCache.GetOrCreateCache(); + var isolatedCache = AppCaches.IsolatedCaches.GetOrCreate(); foreach (var payload in payloads) { - isolatedCache.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + isolatedCache.Clear(RepositoryCacheKeys.GetKey(payload.Id)); _idkMap.ClearCache(payload.Id); @@ -59,7 +59,7 @@ namespace Umbraco.Web.Cache if (payload.ChangeTypes.HasTypesAny(TreeChangeTypes.RefreshBranch | TreeChangeTypes.Remove)) { var pathid = "," + payload.Id + ","; - isolatedCache.ClearCacheObjectTypes((k, v) => v.Path.Contains(pathid)); + isolatedCache.ClearOfType((k, v) => v.Path.Contains(pathid)); } //if the item is being completely removed, we need to refresh the domains cache if any domain was assigned to the content @@ -162,8 +162,8 @@ namespace Umbraco.Web.Cache appCaches.ClearPartialViewCache(); MacroCacheRefresher.ClearMacroContentCache(appCaches); // just the content - appCaches.IsolatedRuntimeCache.ClearCache(); - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs index e1a8f05e39..f3d1337403 100644 --- a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache ClearAllIsolatedCacheByEntityType(); ClearAllIsolatedCacheByEntityType(); - var dataTypeCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var dataTypeCache = AppCaches.IsolatedCaches.Get(); foreach (var payload in payloads) { diff --git a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs index cdeb2ffdd0..6b739b4f49 100644 --- a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs @@ -33,11 +33,11 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { foreach (var prefix in GetAllMacroCacheKeys()) - AppCaches.RuntimeCache.ClearCacheByKeySearch(prefix); + AppCaches.RuntimeCache.ClearByKey(prefix); ClearAllIsolatedCacheByEntityType(); - AppCaches.RuntimeCache.ClearCacheObjectTypes(); + AppCaches.RuntimeCache.ClearOfType(); base.RefreshAll(); } @@ -49,12 +49,12 @@ namespace Umbraco.Web.Cache foreach (var payload in payloads) { foreach (var alias in GetCacheKeysForAlias(payload.Alias)) - AppCaches.RuntimeCache.ClearCacheByKeySearch(alias); + AppCaches.RuntimeCache.ClearByKey(alias); - var macroRepoCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var macroRepoCache = AppCaches.IsolatedCaches.Get(); if (macroRepoCache) { - macroRepoCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + macroRepoCache.Result.Clear(RepositoryCacheKeys.GetKey(payload.Id)); } }; @@ -112,7 +112,7 @@ namespace Umbraco.Web.Cache public static void ClearMacroContentCache(AppCaches appCaches) { - appCaches.RuntimeCache.ClearCacheObjectTypes(); + appCaches.RuntimeCache.ClearOfType(); } #endregion diff --git a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs index a6ccd7e005..cdaf43dac3 100644 --- a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache { Current.ApplicationCache.ClearPartialViewCache(); - var mediaCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var mediaCache = AppCaches.IsolatedCaches.Get(); foreach (var payload in payloads) { @@ -61,13 +61,13 @@ namespace Umbraco.Web.Cache // repository cache // it *was* done for each pathId but really that does not make sense // only need to do it for the current media - mediaCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(payload.Id)); + mediaCache.Result.Clear(RepositoryCacheKeys.GetKey(payload.Id)); // remove those that are in the branch if (payload.ChangeTypes.HasTypesAny(TreeChangeTypes.RefreshBranch | TreeChangeTypes.Remove)) { var pathid = "," + payload.Id + ","; - mediaCache.Result.ClearCacheObjectTypes((_, v) => v.Path.Contains(pathid)); + mediaCache.Result.ClearOfType((_, v) => v.Path.Contains(pathid)); } } } @@ -121,7 +121,7 @@ namespace Umbraco.Web.Cache public static void RefreshMediaTypes(AppCaches appCaches) { - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs index 29c102e7a2..1565b1c849 100644 --- a/src/Umbraco.Web/Cache/MemberCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberCacheRefresher.cs @@ -60,9 +60,9 @@ namespace Umbraco.Web.Cache _idkMap.ClearCache(id); AppCaches.ClearPartialViewCache(); - var memberCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var memberCache = AppCaches.IsolatedCaches.Get(); if (memberCache) - memberCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + memberCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); } #endregion @@ -71,7 +71,7 @@ namespace Umbraco.Web.Cache public static void RefreshMemberTypes(AppCaches appCaches) { - appCaches.IsolatedRuntimeCache.ClearCache(); + appCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs index 9368b0f9f4..3e195cec5e 100644 --- a/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MemberGroupCacheRefresher.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Cache // Since we cache by group name, it could be problematic when renaming to // previously existing names - see http://issues.umbraco.org/issue/U4-10846. // To work around this, just clear all the cache items - AppCaches.IsolatedRuntimeCache.ClearCache(); + AppCaches.IsolatedCaches.ClearCache(); } #endregion diff --git a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs index 8b1c8581cd..c9c8b47bbf 100644 --- a/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/RelationTypeCacheRefresher.cs @@ -34,8 +34,8 @@ namespace Umbraco.Web.Cache public override void Refresh(int id) { - var cache = AppCaches.IsolatedRuntimeCache.GetCache(); - if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + var cache = AppCaches.IsolatedCaches.Get(); + if (cache) cache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Refresh(id); } @@ -47,8 +47,8 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var cache = AppCaches.IsolatedRuntimeCache.GetCache(); - if (cache) cache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + var cache = AppCaches.IsolatedCaches.Get(); + if (cache) cache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs index 7ff7c6fdb6..eda3b6eef4 100644 --- a/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/TemplateCacheRefresher.cs @@ -52,7 +52,7 @@ namespace Umbraco.Web.Cache private void RemoveFromCache(int id) { _idkMap.ClearCache(id); - AppCaches.RuntimeCache.ClearCacheItem($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); + AppCaches.RuntimeCache.Clear($"{CacheKeys.TemplateFrontEndCacheKey}{id}"); //need to clear the runtime cache for templates ClearAllIsolatedCacheByEntityType(); diff --git a/src/Umbraco.Web/Cache/UserCacheRefresher.cs b/src/Umbraco.Web/Cache/UserCacheRefresher.cs index a502a7554f..922a9df385 100644 --- a/src/Umbraco.Web/Cache/UserCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserCacheRefresher.cs @@ -40,9 +40,9 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userCache = AppCaches.IsolatedCaches.Get(); if (userCache) - userCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); + userCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); base.Remove(id); } diff --git a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs index 4dea595c85..cfdf8f3669 100644 --- a/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/UserGroupCacheRefresher.cs @@ -35,10 +35,10 @@ namespace Umbraco.Web.Cache public override void RefreshAll() { ClearAllIsolatedCacheByEntityType(); - var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedCaches.Get(); if (userGroupCache) { - userGroupCache.Result.ClearCacheByKeySearch(UserGroupRepository.GetByAliasCacheKeyPrefix); + userGroupCache.Result.ClearByKey(UserGroupRepository.GetByAliasCacheKeyPrefix); } //We'll need to clear all user cache too @@ -55,11 +55,11 @@ namespace Umbraco.Web.Cache public override void Remove(int id) { - var userGroupCache = AppCaches.IsolatedRuntimeCache.GetCache(); + var userGroupCache = AppCaches.IsolatedCaches.Get(); if (userGroupCache) { - userGroupCache.Result.ClearCacheItem(RepositoryCacheKeys.GetKey(id)); - userGroupCache.Result.ClearCacheByKeySearch(UserGroupRepository.GetByAliasCacheKeyPrefix); + userGroupCache.Result.Clear(RepositoryCacheKeys.GetKey(id)); + userGroupCache.Result.ClearByKey(UserGroupRepository.GetByAliasCacheKeyPrefix); } //we don't know what user's belong to this group without doing a look up so we'll need to just clear them all diff --git a/src/Umbraco.Web/CacheHelperExtensions.cs b/src/Umbraco.Web/CacheHelperExtensions.cs index 3c5ea1930d..ae8df63415 100644 --- a/src/Umbraco.Web/CacheHelperExtensions.cs +++ b/src/Umbraco.Web/CacheHelperExtensions.cs @@ -56,7 +56,7 @@ namespace Umbraco.Web /// public static void ClearPartialViewCache(this AppCaches appCaches) { - appCaches.RuntimeCache.ClearCacheByKeySearch(PartialViewCacheKey); + appCaches.RuntimeCache.ClearByKey(PartialViewCacheKey); } } } diff --git a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs index f30f8e9745..5234bf9fa7 100644 --- a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs +++ b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.Dictionary public class DefaultCultureDictionary : Core.Dictionary.ICultureDictionary { private readonly ILocalizationService _localizationService; - private readonly ICacheProvider _requestCacheProvider; + private readonly IAppCache _requestCacheProvider; private readonly CultureInfo _specificCulture; public DefaultCultureDictionary() @@ -30,7 +30,7 @@ namespace Umbraco.Web.Dictionary } - public DefaultCultureDictionary(ILocalizationService localizationService, ICacheProvider requestCacheProvider) + public DefaultCultureDictionary(ILocalizationService localizationService, IAppCache requestCacheProvider) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); @@ -42,7 +42,7 @@ namespace Umbraco.Web.Dictionary _specificCulture = specificCulture ?? throw new ArgumentNullException(nameof(specificCulture)); } - public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, ICacheProvider requestCacheProvider) + public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, IAppCache requestCacheProvider) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); diff --git a/src/Umbraco.Web/Editors/ExamineManagementController.cs b/src/Umbraco.Web/Editors/ExamineManagementController.cs index b583babee3..db9de424a9 100644 --- a/src/Umbraco.Web/Editors/ExamineManagementController.cs +++ b/src/Umbraco.Web/Editors/ExamineManagementController.cs @@ -29,12 +29,12 @@ namespace Umbraco.Web.Editors { private readonly IExamineManager _examineManager; private readonly ILogger _logger; - private readonly IRuntimeCacheProvider _runtimeCacheProvider; + private readonly IAppPolicedCache _runtimeCacheProvider; private readonly IndexRebuilder _indexRebuilder; public ExamineManagementController(IExamineManager examineManager, ILogger logger, - IRuntimeCacheProvider runtimeCacheProvider, + IAppPolicedCache runtimeCacheProvider, IndexRebuilder indexRebuilder) { _examineManager = examineManager; @@ -114,7 +114,7 @@ namespace Umbraco.Web.Editors throw new HttpResponseException(validate); var cacheKey = "temp_indexing_op_" + indexName; - var found = ApplicationCache.RuntimeCache.GetCacheItem(cacheKey); + var found = ApplicationCache.RuntimeCache.Get(cacheKey); //if its still there then it's not done return found != null @@ -153,7 +153,7 @@ namespace Umbraco.Web.Editors var cacheKey = "temp_indexing_op_" + index.Name; //put temp val in cache which is used as a rudimentary way to know when the indexing is done - ApplicationCache.RuntimeCache.InsertCacheItem(cacheKey, () => "tempValue", TimeSpan.FromMinutes(5)); + ApplicationCache.RuntimeCache.Insert(cacheKey, () => "tempValue", TimeSpan.FromMinutes(5)); _indexRebuilder.RebuildIndex(indexName); @@ -269,7 +269,7 @@ namespace Umbraco.Web.Editors >($"Rebuilding index '{indexer.Name}' done, {indexer.CommitCount} items committed (can differ from the number of items in the index)"); var cacheKey = "temp_indexing_op_" + indexer.Name; - _runtimeCacheProvider.ClearCacheItem(cacheKey); + _runtimeCacheProvider.Clear(cacheKey); } } } diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index e46e83c6e4..15cfda9ffd 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -63,7 +63,7 @@ namespace Umbraco.Web.Editors return await PostSetAvatarInternal(Request, Services.UserService, ApplicationCache.StaticCache, id); } - internal static async Task PostSetAvatarInternal(HttpRequestMessage request, IUserService userService, ICacheProvider staticCache, int id) + internal static async Task PostSetAvatarInternal(HttpRequestMessage request, IUserService userService, IAppCache staticCache, int id) { if (request.Content.IsMimeMultipartContent() == false) { diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index e0a0fd65c8..0bcdb3225b 100755 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -152,7 +152,7 @@ namespace Umbraco.Web.Macros macroContent.Date = DateTime.Now; var cache = Current.ApplicationCache.RuntimeCache; - cache.InsertCacheItem( + cache.Insert( CacheKeys.MacroContentCacheKey + model.CacheIdentifier, () => macroContent, new TimeSpan(0, 0, model.CacheDuration), diff --git a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index 8261dda0d4..4b27af3120 100644 --- a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Models.Mapping => entity is ContentEntitySlim contentEntity ? contentEntity.ContentTypeIcon : null; public UserMapperProfile(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, - IRuntimeCacheProvider runtimeCache, ActionCollection actions, IGlobalSettings globalSettings) + IAppPolicedCache runtimeCache, ActionCollection actions, IGlobalSettings globalSettings) { var userGroupDefaultPermissionsResolver = new UserGroupDefaultPermissionsResolver(textService, actions); diff --git a/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs index 0636eb808c..0865e61f08 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs @@ -36,7 +36,7 @@ namespace Umbraco.Web.PublishedCache /// /// The snapshot-level cache belongs to this snapshot only. /// - ICacheProvider SnapshotCache { get; } + IAppCache SnapshotCache { get; } /// /// Gets the elements-level cache. @@ -45,7 +45,7 @@ namespace Umbraco.Web.PublishedCache /// The elements-level cache is shared by all snapshots relying on the same elements, /// ie all snapshots built on top of unchanging content / media / etc. /// - ICacheProvider ElementsCache { get; } + IAppCache ElementsCache { get; } /// /// Forces the preview mode. diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index 817c363fa5..566ab240c1 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -21,8 +21,8 @@ namespace Umbraco.Web.PublishedCache.NuCache internal class ContentCache : PublishedCacheBase, IPublishedContentCache, INavigableData, IDisposable { private readonly ContentStore.Snapshot _snapshot; - private readonly ICacheProvider _snapshotCache; - private readonly ICacheProvider _elementsCache; + private readonly IAppCache _snapshotCache; + private readonly IAppCache _elementsCache; private readonly DomainHelper _domainHelper; private readonly IGlobalSettings _globalSettings; private readonly ILocalizationService _localizationService; @@ -34,7 +34,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // it's too late for UmbracoContext which has captured previewDefault and stuff into these ctor vars // but, no, UmbracoContext returns snapshot.Content which comes from elements SO a resync should create a new cache - public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings, ILocalizationService localizationService) + public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings, ILocalizationService localizationService) : base(previewDefault) { _snapshot = snapshot; @@ -259,7 +259,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetAtRootNoCache(preview); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem( + return (IEnumerable)cache.Get( CacheKeys.ContentCacheRoots(preview), () => GetAtRootNoCache(preview).ToArray()); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs index f107b52a40..28c7c38c36 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/MediaCache.cs @@ -13,12 +13,12 @@ namespace Umbraco.Web.PublishedCache.NuCache internal class MediaCache : PublishedCacheBase, IPublishedMediaCache, INavigableData, IDisposable { private readonly ContentStore.Snapshot _snapshot; - private readonly ICacheProvider _snapshotCache; - private readonly ICacheProvider _elementsCache; + private readonly IAppCache _snapshotCache; + private readonly IAppCache _elementsCache; #region Constructors - public MediaCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache) + public MediaCache(bool previewDefault, ContentStore.Snapshot snapshot, IAppCache snapshotCache, IAppCache elementsCache) : base(previewDefault) { _snapshot = snapshot; @@ -63,7 +63,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetAtRootNoCache(); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem( + return (IEnumerable)cache.Get( CacheKeys.MediaCacheRoots(false), // ignore preview, only 1 key! () => GetAtRootNoCache().ToArray()); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs index f2392c9c3d..ecf099f90b 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/MemberCache.cs @@ -19,12 +19,12 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor; public readonly IVariationContextAccessor VariationContextAccessor; private readonly IEntityXmlSerializer _entitySerializer; - private readonly ICacheProvider _snapshotCache; + private readonly IAppCache _snapshotCache; private readonly IMemberService _memberService; private readonly PublishedContentTypeCache _contentTypeCache; private readonly bool _previewDefault; - public MemberCache(bool previewDefault, ICacheProvider snapshotCache, IMemberService memberService, PublishedContentTypeCache contentTypeCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IEntityXmlSerializer entitySerializer) + public MemberCache(bool previewDefault, IAppCache snapshotCache, IMemberService memberService, PublishedContentTypeCache contentTypeCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IEntityXmlSerializer entitySerializer) { _snapshotCache = snapshotCache; _publishedSnapshotAccessor = publishedSnapshotAccessor; diff --git a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs index 132c4b6d59..2c8bc94d90 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs @@ -125,7 +125,7 @@ namespace Umbraco.Web.PublishedCache.NuCache { CacheValues cacheValues; PublishedSnapshot publishedSnapshot; - ICacheProvider cache; + IAppCache cache; switch (cacheLevel) { case PropertyCacheLevel.None: @@ -161,11 +161,11 @@ namespace Umbraco.Web.PublishedCache.NuCache return cacheValues; } - private CacheValues GetCacheValues(ICacheProvider cache) + private CacheValues GetCacheValues(IAppCache cache) { if (cache == null) // no cache, don't cache return new CacheValues(); - return (CacheValues) cache.GetCacheItem(ValuesCacheKey, () => new CacheValues()); + return (CacheValues) cache.Get(ValuesCacheKey, () => new CacheValues()); } // this is always invoked from within a lock, so does not require its own lock diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 25e5244d32..65b7a1560a 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var cache = GetCurrentSnapshotCache(); return cache == null ? GetProfileNameByIdNoCache(id) - : (string)cache.GetCacheItem(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); + : (string)cache.Get(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); } private static string GetProfileNameByIdNoCache(int id) @@ -328,7 +328,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return GetChildren(); // note: ToArray is important here, we want to cache the result, not the function! - return (IEnumerable)cache.GetCacheItem(ChildrenCacheKey, () => GetChildren().ToArray()); + return (IEnumerable)cache.Get(ChildrenCacheKey, () => GetChildren().ToArray()); } } @@ -383,7 +383,7 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Caching // beware what you use that one for - you don't want to cache its result - private ICacheProvider GetAppropriateCache() + private IAppCache GetAppropriateCache() { var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; var cache = publishedSnapshot == null @@ -394,7 +394,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return cache; } - private ICacheProvider GetCurrentSnapshotCache() + private IAppCache GetCurrentSnapshotCache() { var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; return publishedSnapshot?.SnapshotCache; @@ -436,7 +436,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var cache = GetAppropriateCache(); if (cache == null) return new PublishedContent(this).CreateModel(); - return (IPublishedContent)cache.GetCacheItem(AsPreviewingCacheKey, () => new PublishedContent(this).CreateModel()); + return (IPublishedContent)cache.Get(AsPreviewingCacheKey, () => new PublishedContent(this).CreateModel()); } // used by Navigable.Source,... diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs index 9b8982c69c..2ceced75eb 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs @@ -25,8 +25,8 @@ namespace Umbraco.Web.PublishedCache.NuCache public MediaCache MediaCache; public MemberCache MemberCache; public DomainCache DomainCache; - public ICacheProvider SnapshotCache; - public ICacheProvider ElementsCache; + public IAppCache SnapshotCache; + public IAppCache ElementsCache; public void Dispose() { @@ -48,9 +48,9 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Caches - public ICacheProvider SnapshotCache => Elements.SnapshotCache; + public IAppCache SnapshotCache => Elements.SnapshotCache; - public ICacheProvider ElementsCache => Elements.ElementsCache; + public IAppCache ElementsCache => Elements.ElementsCache; #endregion diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 36f3472c31..bcb1c6ede3 100755 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -932,7 +932,7 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Create, Get Published Snapshot private long _contentGen, _mediaGen, _domainGen; - private ICacheProvider _elementsCache; + private IAppCache _elementsCache; public override IPublishedSnapshot CreatePublishedSnapshot(string previewToken) { @@ -960,7 +960,7 @@ namespace Umbraco.Web.PublishedCache.NuCache ContentStore.Snapshot contentSnap, mediaSnap; SnapDictionary.Snapshot domainSnap; - ICacheProvider elementsCache; + IAppCache elementsCache; lock (_storesLock) { var scopeContext = _scopeProvider.Context; @@ -998,11 +998,11 @@ namespace Umbraco.Web.PublishedCache.NuCache _contentGen = contentSnap.Gen; _mediaGen = mediaSnap.Gen; _domainGen = domainSnap.Gen; - elementsCache = _elementsCache = new DictionaryCacheProvider(); + elementsCache = _elementsCache = new FastDictionaryCacheProvider(); } } - var snapshotCache = new StaticCacheProvider(); + var snapshotCache = new DictionaryCacheProvider(); var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); diff --git a/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs b/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs index cff1e40b69..6d69b96e0c 100644 --- a/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs +++ b/src/Umbraco.Web/PublishedCache/PublishedElementPropertyBase.cs @@ -106,7 +106,7 @@ namespace Umbraco.Web.PublishedCache } } - private ICacheProvider GetSnapshotCache() + private IAppCache GetSnapshotCache() { // cache within the snapshot cache, unless previewing, then use the snapshot or // elements cache (if we don't want to pollute the elements cache with short-lived @@ -135,12 +135,12 @@ namespace Umbraco.Web.PublishedCache case PropertyCacheLevel.Elements: // cache within the elements cache, depending... var snapshotCache = GetSnapshotCache(); - cacheValues = (CacheValues) snapshotCache?.GetCacheItem(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); + cacheValues = (CacheValues) snapshotCache?.Get(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); break; case PropertyCacheLevel.Snapshot: // cache within the snapshot cache var facadeCache = _publishedSnapshotAccessor?.PublishedSnapshot?.SnapshotCache; - cacheValues = (CacheValues) facadeCache?.GetCacheItem(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); + cacheValues = (CacheValues) facadeCache?.Get(ValuesCacheKey, () => new CacheValues()) ?? new CacheValues(); break; default: throw new InvalidOperationException("Invalid cache level."); diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs index 6f6a39144a..ea38af314f 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache Func getParent, Func> getChildren, Func getProperty, - ICacheProvider cacheProvider, + IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, XPathNavigator nav, bool fromExamine) @@ -133,7 +133,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache //private readonly Func> _getChildren; private readonly Lazy> _getChildren; private readonly Func _getProperty; - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; /// /// Returns 'Media' as the item type diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index e022e36fc0..67813ce9f6 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -15,7 +15,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : PublishedCacheBase, IPublishedContentCache { - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; private readonly IGlobalSettings _globalSettings; private readonly RoutesCache _routesCache; private readonly IDomainCache _domainCache; @@ -30,7 +30,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public PublishedContentCache( XmlStore xmlStore, // an XmlStore containing the master xml IDomainCache domainCache, // an IDomainCache implementation - ICacheProvider cacheProvider, // an ICacheProvider that should be at request-level + IAppCache cacheProvider, // an ICacheProvider that should be at request-level IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache @@ -517,7 +517,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // clear recursive properties cached by XmlPublishedContent.GetProperty // assume that nothing else is going to cache IPublishedProperty items (else would need to do ByKeySearch) // NOTE also clears all the media cache properties, which is OK (see media cache) - _cacheProvider.ClearCacheObjectTypes(); + _cacheProvider.ClearOfType(); //_cacheProvider.ClearCacheByKeySearch("XmlPublishedCache.PublishedContentCache:RecursiveProperty-"); } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs index 09b76b5c2e..3ead5a5166 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs @@ -43,9 +43,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IEntityXmlSerializer _entitySerializer; // must be specified by the ctor - private readonly ICacheProvider _cacheProvider; + private readonly IAppCache _cacheProvider; - public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); @@ -66,7 +66,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// /// /// - internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); @@ -678,7 +678,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var cache = Current.ApplicationCache.RuntimeCache; var key = PublishedMediaCacheKey + id; - return (CacheValues)cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan); + return (CacheValues)cache.Get(key, () => func(id), _publishedMediaCacheTimespan); } internal static void ClearCache(int id) @@ -696,11 +696,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID")); // clear the item - cache.ClearCacheItem(key); + cache.Clear(key); // clear all children - in case we moved and their path has changed var fid = "/" + sid + "/"; - cache.ClearCacheObjectTypes((k, v) => + cache.ClearOfType((k, v) => GetValuesValue(v.Values, "path", "__Path").Contains(fid)); } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs index 2328a1cefd..a622a4934c 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs @@ -13,11 +13,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache class PublishedMemberCache : IPublishedMemberCache { private readonly IMemberService _memberService; - private readonly ICacheProvider _requestCache; + private readonly IAppCache _requestCache; private readonly XmlStore _xmlStore; private readonly PublishedContentTypeCache _contentTypeCache; - public PublishedMemberCache(XmlStore xmlStore, ICacheProvider requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache) + public PublishedMemberCache(XmlStore xmlStore, IAppCache requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache) { _requestCache = requestCacheProvider; _memberService = memberService; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs index 61ea7d2534..b9243309a2 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs @@ -38,10 +38,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public IDomainCache Domains { get; } /// - public ICacheProvider SnapshotCache => null; + public IAppCache SnapshotCache => null; /// - public ICacheProvider ElementsCache => null; + public IAppCache ElementsCache => null; /// public IDisposable ForcedPreview(bool preview, Action callback = null) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs index e286e9d95c..c4ce05c9a9 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IMemberService _memberService; private readonly IMediaService _mediaService; private readonly IUserService _userService; - private readonly ICacheProvider _requestCache; + private readonly IAppCache _requestCache; private readonly IGlobalSettings _globalSettings; private readonly IDefaultCultureAccessor _defaultCultureAccessor; private readonly ISiteDomainHelper _siteDomainHelper; @@ -42,7 +42,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public PublishedSnapshotService(ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IScopeProvider scopeProvider, - ICacheProvider requestCache, + IAppCache requestCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, @@ -63,7 +63,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache internal PublishedSnapshotService(ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IScopeProvider scopeProvider, - ICacheProvider requestCache, + IAppCache requestCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IVariationContextAccessor variationContextAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IDefaultCultureAccessor defaultCultureAccessor, diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index efd4535bd4..a1fda17df1 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -20,7 +20,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache [XmlType(Namespace = "http://umbraco.org/webservices/")] internal class XmlPublishedContent : PublishedContentBase { - private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache) + private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) { _xmlNode = xmlNode; _isPreviewing = isPreviewing; @@ -31,7 +31,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly XmlNode _xmlNode; private readonly bool _isPreviewing; - private readonly ICacheProvider _cacheProvider; // at snapshot/request level (see PublishedContentCache) + private readonly IAppCache _cacheProvider; // at snapshot/request level (see PublishedContentCache) private readonly PublishedContentTypeCache _contentTypeCache; private readonly object _initializeLock = new object(); @@ -426,7 +426,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// Maintains a per-request cache of IPublishedContent items in order to make /// sure that we create only one instance of each for the duration of a request. The /// returned IPublishedContent is a model, if models are enabled. - public static IPublishedContent Get(XmlNode node, bool isPreviewing, ICacheProvider cacheProvider, PublishedContentTypeCache contentTypeCache) + public static IPublishedContent Get(XmlNode node, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) { // only 1 per request @@ -434,12 +434,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var id = attrs?.GetNamedItem("id").Value; if (id.IsNullOrWhiteSpace()) throw new InvalidOperationException("Node has no ID attribute."); var key = CacheKeyPrefix + id; // dont bother with preview, wont change during request in Xml cache - return (IPublishedContent) cacheProvider.GetCacheItem(key, () => (new XmlPublishedContent(node, isPreviewing, cacheProvider, contentTypeCache)).CreateModel()); + return (IPublishedContent) cacheProvider.Get(key, () => (new XmlPublishedContent(node, isPreviewing, cacheProvider, contentTypeCache)).CreateModel()); } public static void ClearRequest() { - Current.ApplicationCache.RequestCache.ClearCacheByKeySearch(CacheKeyPrefix); + Current.ApplicationCache.RequestCache.ClearByKey(CacheKeyPrefix); } private const string CacheKeyPrefix = "CONTENTCACHE_XMLPUBLISHEDCONTENT_"; diff --git a/src/Umbraco.Web/Runtime/WebRuntime.cs b/src/Umbraco.Web/Runtime/WebRuntime.cs index c69a3bec8b..e9d27a2a1c 100644 --- a/src/Umbraco.Web/Runtime/WebRuntime.cs +++ b/src/Umbraco.Web/Runtime/WebRuntime.cs @@ -62,14 +62,14 @@ 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 DeepCloneRuntimeCacheProvider(new HttpRuntimeCacheProvider(HttpRuntime.Cache)), - new StaticCacheProvider(), + new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache)), + new DictionaryCacheProvider(), // we need request based cache when running in web-based context - new HttpRequestCacheProvider(), - new IsolatedRuntimeCache(type => + new HttpRequestAppCache(), + new IsolatedCaches(type => // we need to have the dep clone runtime cache provider to ensure // all entities are cached properly (cloned in and cloned out) - new DeepCloneRuntimeCacheProvider(new ObjectCacheRuntimeCacheProvider()))); + new DeepCloneAppCache(new ObjectCacheAppCache()))); #endregion } diff --git a/src/Umbraco.Web/Services/ApplicationTreeService.cs b/src/Umbraco.Web/Services/ApplicationTreeService.cs index 2ddec054c7..30d50e136c 100644 --- a/src/Umbraco.Web/Services/ApplicationTreeService.cs +++ b/src/Umbraco.Web/Services/ApplicationTreeService.cs @@ -357,7 +357,7 @@ namespace Umbraco.Web.Services //remove the cache now that it has changed SD: I'm leaving this here even though it // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey); + _cache.RuntimeCache.Clear(CacheKeys.ApplicationTreeCacheKey); } } } diff --git a/src/Umbraco.Web/Services/SectionService.cs b/src/Umbraco.Web/Services/SectionService.cs index 2d06141292..09972a6dca 100644 --- a/src/Umbraco.Web/Services/SectionService.cs +++ b/src/Umbraco.Web/Services/SectionService.cs @@ -132,7 +132,7 @@ namespace Umbraco.Web.Services //remove the cache so it gets re-read ... SD: I'm leaving this here even though it // is taken care of by events as well, I think unit tests may rely on it being cleared here. - _cache.RuntimeCache.ClearCacheItem(CacheKeys.ApplicationsCacheKey); + _cache.RuntimeCache.Clear(CacheKeys.ApplicationsCacheKey); } } } From d4c714eccd0a6097865998ca9d01ba39e4898517 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 17 Jan 2019 11:19:06 +0100 Subject: [PATCH 37/70] Stop injecting the runtime cache, use AppCaches --- src/Umbraco.Core/Cache/ObjectCacheAppCache.cs | 2 +- .../Composing/Composers/ServicesComposer.cs | 2 +- .../Composing/CompositionExtensions.cs | 1 - src/Umbraco.Core/ConfigsExtensions.cs | 4 ++-- .../Configuration/Grid/GridConfig.cs | 4 ++-- .../Configuration/Grid/GridEditorsConfig.cs | 10 +++++----- src/Umbraco.Core/Manifest/ManifestParser.cs | 9 +++++---- .../Implement/DictionaryRepository.cs | 4 ++-- .../Implement/RepositoryBaseOfTIdTEntity.cs | 12 ++++++------ .../Implement/ServerRegistrationRepository.cs | 2 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 3 +-- .../LocalizedTextServiceFileSources.cs | 17 ++++++----------- .../Manifest/ManifestParserTests.cs | 2 +- .../Models/Mapping/AutoMapperTests.cs | 2 +- .../Scoping/ScopedRepositoryTests.cs | 2 +- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 2 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 9 ++++----- .../Editors/ExamineManagementController.cs | 15 ++++----------- .../Models/Mapping/UserMapperProfile.cs | 8 ++++---- 19 files changed, 48 insertions(+), 62 deletions(-) diff --git a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs index 9c5917a53c..954622fc4b 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs @@ -31,7 +31,7 @@ namespace Umbraco.Core.Cache /// /// Gets the internal memory cache, for tests only! /// - internal readonly ObjectCache MemoryCache; + internal ObjectCache MemoryCache { get; private set; } /// public object Get(string key) diff --git a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs index 9ed4a7265c..2af7c5a011 100644 --- a/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs +++ b/src/Umbraco.Core/Composing/Composers/ServicesComposer.cs @@ -116,7 +116,7 @@ namespace Umbraco.Core.Composing.Composers return new LocalizedTextServiceFileSources( container.GetInstance(), - container.GetInstance().RuntimeCache, + container.GetInstance(), mainLangFolder, pluginLangFolders.Concat(userLangFolders)); } diff --git a/src/Umbraco.Core/Composing/CompositionExtensions.cs b/src/Umbraco.Core/Composing/CompositionExtensions.cs index 910062688c..c312259b82 100644 --- a/src/Umbraco.Core/Composing/CompositionExtensions.cs +++ b/src/Umbraco.Core/Composing/CompositionExtensions.cs @@ -28,7 +28,6 @@ namespace Umbraco.Core.Composing composition.RegisterUnique(profilingLogger); composition.RegisterUnique(mainDom); composition.RegisterUnique(appCaches); - composition.RegisterUnique(factory => factory.GetInstance().RuntimeCache); composition.RegisterUnique(databaseFactory); composition.RegisterUnique(factory => factory.GetInstance().SqlContext); composition.RegisterUnique(typeLoader); diff --git a/src/Umbraco.Core/ConfigsExtensions.cs b/src/Umbraco.Core/ConfigsExtensions.cs index 9b2abda53c..0fcea5f430 100644 --- a/src/Umbraco.Core/ConfigsExtensions.cs +++ b/src/Umbraco.Core/ConfigsExtensions.cs @@ -46,7 +46,7 @@ namespace Umbraco.Core configs.Add(() => new CoreDebug()); // GridConfig depends on runtime caches, manifest parsers... and cannot be available during composition - configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); + configs.Add(factory => new GridConfig(factory.GetInstance(), factory.GetInstance(), configDir, factory.GetInstance().Debug)); } } -} \ No newline at end of file +} diff --git a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs index 979eccb839..b2dae09fc9 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs @@ -6,9 +6,9 @@ namespace Umbraco.Core.Configuration.Grid { class GridConfig : IGridConfig { - public GridConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridConfig(ILogger logger, AppCaches appCaches, DirectoryInfo configFolder, bool isDebug) { - EditorsConfig = new GridEditorsConfig(logger, runtimeCache, configFolder, isDebug); + EditorsConfig = new GridEditorsConfig(logger, appCaches, configFolder, isDebug); } public IGridEditorsConfig EditorsConfig { get; } diff --git a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs index 121b74194c..e2f99a753b 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs @@ -13,14 +13,14 @@ namespace Umbraco.Core.Configuration.Grid internal class GridEditorsConfig : IGridEditorsConfig { private readonly ILogger _logger; - private readonly IAppPolicedCache _runtimeCache; + private readonly AppCaches _appCaches; private readonly DirectoryInfo _configFolder; private readonly bool _isDebug; - public GridEditorsConfig(ILogger logger, IAppPolicedCache runtimeCache, DirectoryInfo configFolder, bool isDebug) + public GridEditorsConfig(ILogger logger, AppCaches appCaches, DirectoryInfo configFolder, bool isDebug) { _logger = logger; - _runtimeCache = runtimeCache; + _appCaches = appCaches; _configFolder = configFolder; _isDebug = isDebug; } @@ -32,7 +32,7 @@ namespace Umbraco.Core.Configuration.Grid List GetResult() { // fixme - should use the common one somehow! + ignoring _appPlugins here! - var parser = new ManifestParser(_runtimeCache, Current.ManifestValidators, _logger); + var parser = new ManifestParser(_appCaches, Current.ManifestValidators, _logger); var editors = new List(); var gridConfig = Path.Combine(_configFolder.FullName, "grid.editors.config.js"); @@ -62,7 +62,7 @@ namespace Umbraco.Core.Configuration.Grid //cache the result if debugging is disabled var result = _isDebug ? GetResult() - : _runtimeCache.GetCacheItem>(typeof(GridEditorsConfig) + ".Editors",GetResult, TimeSpan.FromMinutes(10)); + : _appCaches.RuntimeCache.GetCacheItem>(typeof(GridEditorsConfig) + ".Editors",GetResult, TimeSpan.FromMinutes(10)); return result; } diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index fd344674af..40e99bb079 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -29,16 +29,17 @@ namespace Umbraco.Core.Manifest /// /// Initializes a new instance of the class. /// - public ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, ILogger logger) - : this(cache, validators, "~/App_Plugins", logger) + public ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, ILogger logger) + : this(appCaches, validators, "~/App_Plugins", logger) { } /// /// Initializes a new instance of the class. /// - private ManifestParser(IAppPolicedCache cache, ManifestValueValidatorCollection validators, string path, ILogger logger) + private ManifestParser(AppCaches appCaches, ManifestValueValidatorCollection validators, string path, ILogger logger) { - _cache = cache ?? throw new ArgumentNullException(nameof(cache)); + if (appCaches == null) throw new ArgumentNullException(nameof(appCaches)); + _cache = appCaches.RuntimeCache; _validators = validators ?? throw new ArgumentNullException(nameof(validators)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullOrEmptyException(nameof(path)); Path = path; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs index 9b191d830c..be1e28fcc1 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DictionaryRepository.cs @@ -224,13 +224,13 @@ namespace Umbraco.Core.Persistence.Repositories.Implement public IDictionaryItem Get(Guid uniqueId) { - var uniqueIdRepo = new DictionaryByUniqueIdRepository(this, ScopeAccessor, GlobalCache, Logger); + var uniqueIdRepo = new DictionaryByUniqueIdRepository(this, ScopeAccessor, AppCaches, Logger); return uniqueIdRepo.Get(uniqueId); } public IDictionaryItem Get(string key) { - var keyRepo = new DictionaryByKeyRepository(this, ScopeAccessor, GlobalCache, Logger); + var keyRepo = new DictionaryByKeyRepository(this, ScopeAccessor, AppCaches, Logger); return keyRepo.Get(key); } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs index f106949c77..6862173786 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs @@ -19,18 +19,18 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { private IRepositoryCachePolicy _cachePolicy; - protected RepositoryBase(IScopeAccessor scopeAccessor, AppCaches cache, ILogger logger) + protected RepositoryBase(IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger logger) { ScopeAccessor = scopeAccessor ?? throw new ArgumentNullException(nameof(scopeAccessor)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); - GlobalCache = cache ?? throw new ArgumentNullException(nameof(cache)); + AppCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches)); } protected ILogger Logger { get; } - protected AppCaches GlobalCache { get; } + protected AppCaches AppCaches { get; } - protected IAppPolicedCache GlobalIsolatedCache => GlobalCache.IsolatedCaches.GetOrCreate(); + protected IAppPolicedCache GlobalIsolatedCache => AppCaches.IsolatedCaches.GetOrCreate(); protected IScopeAccessor ScopeAccessor { get; } @@ -67,7 +67,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement switch (AmbientScope.RepositoryCacheMode) { case RepositoryCacheMode.Default: - return GlobalCache.IsolatedCaches.GetOrCreate(); + return AppCaches.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.Scoped: return AmbientScope.IsolatedCaches.GetOrCreate(); case RepositoryCacheMode.None: @@ -127,7 +127,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement { get { - if (GlobalCache == AppCaches.NoCache) + if (AppCaches == AppCaches.NoCache) return NoCacheRepositoryCachePolicy.Instance; // create the cache policy using IsolatedCache which is either global diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs index ead7c066be..298e503736 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ServerRegistrationRepository.cs @@ -28,7 +28,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement // and this is because the repository is special and should not participate in scopes // (cleanup in v8) // - return new FullDataSetRepositoryCachePolicy(GlobalCache.RuntimeCache, ScopeAccessor, GetEntityId, /*expires:*/ false); + return new FullDataSetRepositoryCachePolicy(AppCaches.RuntimeCache, ScopeAccessor, GetEntityId, /*expires:*/ false); } public void ClearCache() diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index e37b5e254e..6bfe9cdb55 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -102,7 +102,6 @@ namespace Umbraco.Core.Runtime // application caches var appCaches = GetAppCaches(); - var runtimeCache = appCaches.RuntimeCache; // database factory var databaseFactory = GetDatabaseFactory(); @@ -112,7 +111,7 @@ namespace Umbraco.Core.Runtime // type loader var localTempStorage = configs.Global().LocalTempStorageLocation; - var typeLoader = new TypeLoader(runtimeCache, localTempStorage, ProfilingLogger); + var typeLoader = new TypeLoader(appCaches.RuntimeCache, localTempStorage, ProfilingLogger); // runtime state // beware! must use '() => _factory.GetInstance()' and NOT '_factory.GetInstance' diff --git a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs index 5577508adb..8c2d277348 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs @@ -37,16 +37,16 @@ namespace Umbraco.Core.Services.Implement /// public LocalizedTextServiceFileSources( ILogger logger, - IAppPolicedCache cache, + AppCaches appCaches, DirectoryInfo fileSourceFolder, IEnumerable supplementFileSources) { if (logger == null) throw new ArgumentNullException("logger"); - if (cache == null) throw new ArgumentNullException("cache"); + if (appCaches == null) throw new ArgumentNullException("cache"); if (fileSourceFolder == null) throw new ArgumentNullException("fileSourceFolder"); _logger = logger; - _cache = cache; + _cache = appCaches.RuntimeCache; //Create the lazy source for the _xmlSources _xmlSources = new Lazy>>(() => @@ -137,14 +137,9 @@ namespace Umbraco.Core.Services.Implement /// /// Constructor /// - /// - /// - /// - public LocalizedTextServiceFileSources(ILogger logger, IAppPolicedCache cache, DirectoryInfo fileSourceFolder) - : this(logger, cache, fileSourceFolder, Enumerable.Empty()) - { - - } + public LocalizedTextServiceFileSources(ILogger logger, AppCaches appCaches, DirectoryInfo fileSourceFolder) + : this(logger, appCaches, fileSourceFolder, Enumerable.Empty()) + { } /// /// returns all xml sources for all culture files found in the folder diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index 74f9fd7157..3f1e668dc0 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.Manifest new RequiredValidator(Mock.Of()), new RegexValidator(Mock.Of(), null) }; - _parser = new ManifestParser(NoAppCache.Instance, new ManifestValueValidatorCollection(validators), Mock.Of()); + _parser = new ManifestParser(AppCaches.Disabled, new ManifestValueValidatorCollection(validators), Mock.Of()); } [Test] diff --git a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs index f48abc1233..57d38e342e 100644 --- a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Models.Mapping base.Compose(); var manifestBuilder = new ManifestParser( - AppCaches.Disabled.RuntimeCache, + AppCaches.Disabled, new ManifestValueValidatorCollection(Enumerable.Empty()), Composition.Logger) { diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 6e01de1670..12cd02d2e9 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -37,7 +37,7 @@ namespace Umbraco.Tests.Scoping .Add(() => Composition.TypeLoader.GetCacheRefreshers()); } - protected override AppCaches GetCacheHelper() + protected override AppCaches GetAppCaches() { // this is what's created core web runtime return new AppCaches( diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 29eb649c48..34c97fcea2 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -140,7 +140,7 @@ namespace Umbraco.Tests.TestHelpers return new LocalizedTextServiceFileSources( logger, - cache.RuntimeCache, + cache, mainLangFolder, pluginLangFolders.Concat(userLangFolders)); diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 2d6e01b6bb..fd617b5a21 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -125,9 +125,9 @@ namespace Umbraco.Tests.Testing var (logger, profiler) = GetLoggers(Options.Logger); var proflogger = new ProfilingLogger(logger, profiler); - var cacheHelper = GetCacheHelper(); + var appCaches = GetAppCaches(); var globalSettings = SettingsForTests.GetDefaultGlobalSettings(); - var typeLoader = GetTypeLoader(cacheHelper.RuntimeCache, globalSettings, proflogger, Options.TypeLoader); + var typeLoader = GetTypeLoader(appCaches.RuntimeCache, globalSettings, proflogger, Options.TypeLoader); var register = RegisterFactory.Create(); @@ -137,8 +137,7 @@ namespace Umbraco.Tests.Testing Composition.RegisterUnique(logger); Composition.RegisterUnique(profiler); Composition.RegisterUnique(proflogger); - Composition.RegisterUnique(cacheHelper); - Composition.RegisterUnique(cacheHelper.RuntimeCache); + Composition.RegisterUnique(appCaches); TestObjects = new TestObjects(register); Compose(); @@ -199,7 +198,7 @@ namespace Umbraco.Tests.Testing return (logger, profiler); } - protected virtual AppCaches GetCacheHelper() + protected virtual AppCaches GetAppCaches() { return AppCaches.Disabled; } diff --git a/src/Umbraco.Web/Editors/ExamineManagementController.cs b/src/Umbraco.Web/Editors/ExamineManagementController.cs index db9de424a9..8d930b8ed7 100644 --- a/src/Umbraco.Web/Editors/ExamineManagementController.cs +++ b/src/Umbraco.Web/Editors/ExamineManagementController.cs @@ -1,26 +1,19 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Net; using System.Net.Http; -using System.Reflection; using System.Web.Http; using Examine; -using Examine.LuceneEngine; using Examine.LuceneEngine.Providers; -using Lucene.Net.Analysis; -using Lucene.Net.QueryParsers; using Umbraco.Core; using Umbraco.Core.Cache; -using Umbraco.Core.Composing; using Umbraco.Core.Logging; using Umbraco.Examine; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using Umbraco.Web.Search; using SearchResult = Umbraco.Web.Models.ContentEditing.SearchResult; -using Version = Lucene.Net.Util.Version; namespace Umbraco.Web.Editors { @@ -29,17 +22,17 @@ namespace Umbraco.Web.Editors { private readonly IExamineManager _examineManager; private readonly ILogger _logger; - private readonly IAppPolicedCache _runtimeCacheProvider; + private readonly IAppPolicedCache _runtimeCache; private readonly IndexRebuilder _indexRebuilder; public ExamineManagementController(IExamineManager examineManager, ILogger logger, - IAppPolicedCache runtimeCacheProvider, + AppCaches appCaches, IndexRebuilder indexRebuilder) { _examineManager = examineManager; _logger = logger; - _runtimeCacheProvider = runtimeCacheProvider; + _runtimeCache = appCaches.RuntimeCache; _indexRebuilder = indexRebuilder; } @@ -269,7 +262,7 @@ namespace Umbraco.Web.Editors >($"Rebuilding index '{indexer.Name}' done, {indexer.CommitCount} items committed (can differ from the number of items in the index)"); var cacheKey = "temp_indexing_op_" + indexer.Name; - _runtimeCacheProvider.Clear(cacheKey); + _runtimeCache.Clear(cacheKey); } } } diff --git a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index 4b27af3120..b6fc94eb3c 100644 --- a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Models.Mapping => entity is ContentEntitySlim contentEntity ? contentEntity.ContentTypeIcon : null; public UserMapperProfile(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, - IAppPolicedCache runtimeCache, ActionCollection actions, IGlobalSettings globalSettings) + AppCaches appCaches, ActionCollection actions, IGlobalSettings globalSettings) { var userGroupDefaultPermissionsResolver = new UserGroupDefaultPermissionsResolver(textService, actions); @@ -243,7 +243,7 @@ namespace Umbraco.Web.Models.Mapping //Important! Currently we are never mapping to multiple UserDisplay objects but if we start doing that // this will cause an N+1 and we'll need to change how this works. CreateMap() - .ForMember(dest => dest.Avatars, opt => opt.MapFrom(user => user.GetUserAvatarUrls(runtimeCache))) + .ForMember(dest => dest.Avatars, opt => opt.MapFrom(user => user.GetUserAvatarUrls(appCaches.RuntimeCache))) .ForMember(dest => dest.Username, opt => opt.MapFrom(user => user.Username)) .ForMember(dest => dest.LastLoginDate, opt => opt.MapFrom(user => user.LastLoginDate == default(DateTime) ? null : (DateTime?)user.LastLoginDate)) .ForMember(dest => dest.UserGroups, opt => opt.MapFrom(user => user.Groups)) @@ -293,7 +293,7 @@ namespace Umbraco.Web.Models.Mapping //like the load time is waiting. .ForMember(detail => detail.Avatars, - opt => opt.MapFrom(user => user.GetUserAvatarUrls(runtimeCache))) + opt => opt.MapFrom(user => user.GetUserAvatarUrls(appCaches.RuntimeCache))) .ForMember(dest => dest.Username, opt => opt.MapFrom(user => user.Username)) .ForMember(dest => dest.UserGroups, opt => opt.MapFrom(user => user.Groups)) .ForMember(dest => dest.LastLoginDate, opt => opt.MapFrom(user => user.LastLoginDate == default(DateTime) ? null : (DateTime?)user.LastLoginDate)) @@ -313,7 +313,7 @@ namespace Umbraco.Web.Models.Mapping .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()); CreateMap() - .ForMember(dest => dest.Avatars, opt => opt.MapFrom(user => user.GetUserAvatarUrls(runtimeCache))) + .ForMember(dest => dest.Avatars, opt => opt.MapFrom(user => user.GetUserAvatarUrls(appCaches.RuntimeCache))) .ForMember(dest => dest.UserId, opt => opt.MapFrom(user => GetIntId(user.Id))) .ForMember(dest => dest.StartContentIds, opt => opt.MapFrom(user => user.CalculateContentStartNodeIds(entityService))) .ForMember(dest => dest.StartMediaIds, opt => opt.MapFrom(user => user.CalculateMediaStartNodeIds(entityService))) From cefa2c9040ed6033aa4774ff253a14fc38334673 Mon Sep 17 00:00:00 2001 From: Nicholas-Westby Date: Wed, 16 Jan 2019 13:42:23 -0800 Subject: [PATCH 38/70] Typo ("thist"). --- .../config/umbracoSettings.Release.config | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config index 2d663aa1fb..3442fefdfe 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config @@ -6,11 +6,11 @@ https://our.umbraco.com/documentation/using-umbraco/config-files/umbracoSettings/ Many of the optional settings are not explicitly listed here but can be found in the online documentation. - --> - + --> + - + @@ -32,7 +32,7 @@ - + your@email.here @@ -61,14 +61,14 @@ true - assets/img/installer.jpg + assets/img/installer.jpg false - + true false From 54faeee8370508fa2dafe9b8942622f216f91458 Mon Sep 17 00:00:00 2001 From: Callum Whyte Date: Thu, 17 Jan 2019 11:19:44 +1100 Subject: [PATCH 39/70] Updating number of active Umbraco sites in installer screen facts --- src/Umbraco.Web.UI.Client/src/installer/installer.service.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js index a174de1271..f89f6ae6e7 100644 --- a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js +++ b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js @@ -17,7 +17,7 @@ angular.module("umbraco.install").factory('installerService', function($rootScop //add to umbraco installer facts here var facts = ['Umbraco helped millions of people watch a man jump from the edge of space', - 'Over 440 000 websites are currently powered by Umbraco', + 'Over 500 000 websites are currently powered by Umbraco', "At least 2 people have named their cat 'Umbraco'", 'On an average day, more than 1000 people download Umbraco', 'umbraco.tv is the premier source of Umbraco video tutorials to get you started', From 5a78c000a06cd7db6bd8ed993bb43854cf569dee Mon Sep 17 00:00:00 2001 From: Callum Whyte Date: Thu, 17 Jan 2019 11:21:26 +1100 Subject: [PATCH 40/70] Correcting punctuation in installer screen facts --- .../src/installer/installer.service.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js index f89f6ae6e7..7b802d9f7b 100644 --- a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js +++ b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js @@ -19,14 +19,14 @@ angular.module("umbraco.install").factory('installerService', function($rootScop var facts = ['Umbraco helped millions of people watch a man jump from the edge of space', 'Over 500 000 websites are currently powered by Umbraco', "At least 2 people have named their cat 'Umbraco'", - 'On an average day, more than 1000 people download Umbraco', - 'umbraco.tv is the premier source of Umbraco video tutorials to get you started', - 'You can find the world\'s friendliest CMS community at our.umbraco.com', + 'On an average day more than 1000 people download Umbraco', + 'umbraco.tv is the premier source of Umbraco video tutorials to get you started', + 'You can find the world\'s friendliest CMS community at our.umbraco.com', 'You can become a certified Umbraco developer by attending one of the official courses', 'Umbraco works really well on tablets', 'You have 100% control over your markup and design when crafting a website in Umbraco', 'Umbraco is the best of both worlds: 100% free and open source, and backed by a professional and profitable company', - "There's a pretty big chance, you've visited a website powered by Umbraco today", + "There's a pretty big chance you've visited a website powered by Umbraco today", "'Umbraco-spotting' is the game of spotting big brands running Umbraco", "At least 4 people have the Umbraco logo tattooed on them", "'Umbraco' is the Danish name for an allen key", From e60417925bd02c16aea0ee54e8d393d367a26c24 Mon Sep 17 00:00:00 2001 From: Callum Whyte Date: Thu, 17 Jan 2019 11:28:22 +1100 Subject: [PATCH 41/70] Consistency is king! Fix up " vs ' in installer service facts array --- .../src/installer/installer.service.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js index 7b802d9f7b..4419289744 100644 --- a/src/Umbraco.Web.UI.Client/src/installer/installer.service.js +++ b/src/Umbraco.Web.UI.Client/src/installer/installer.service.js @@ -16,16 +16,16 @@ angular.module("umbraco.install").factory('installerService', function($rootScop }; //add to umbraco installer facts here - var facts = ['Umbraco helped millions of people watch a man jump from the edge of space', - 'Over 500 000 websites are currently powered by Umbraco', + var facts = ["Umbraco helped millions of people watch a man jump from the edge of space", + "Over 500 000 websites are currently powered by Umbraco", "At least 2 people have named their cat 'Umbraco'", - 'On an average day more than 1000 people download Umbraco', - 'umbraco.tv is the premier source of Umbraco video tutorials to get you started', - 'You can find the world\'s friendliest CMS community at our.umbraco.com', - 'You can become a certified Umbraco developer by attending one of the official courses', - 'Umbraco works really well on tablets', - 'You have 100% control over your markup and design when crafting a website in Umbraco', - 'Umbraco is the best of both worlds: 100% free and open source, and backed by a professional and profitable company', + "On an average day more than 1000 people download Umbraco", + "umbraco.tv is the premier source of Umbraco video tutorials to get you started", + "You can find the world's friendliest CMS community at our.umbraco.com", + "You can become a certified Umbraco developer by attending one of the official courses", + "Umbraco works really well on tablets", + "You have 100% control over your markup and design when crafting a website in Umbraco", + "Umbraco is the best of both worlds: 100% free and open source, and backed by a professional and profitable company", "There's a pretty big chance you've visited a website powered by Umbraco today", "'Umbraco-spotting' is the game of spotting big brands running Umbraco", "At least 4 people have the Umbraco logo tattooed on them", From 5aba1a6bd29c25101485f0b10e8321a3d2f81855 Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 18 Jan 2019 07:56:38 +0100 Subject: [PATCH 42/70] IAppPolicedCache is IAppPolicyCache --- src/Umbraco.Core/Cache/AppCaches.cs | 4 ++-- .../Cache/AppPolicedCacheDictionary.cs | 14 +++++++------- src/Umbraco.Core/Cache/CacheProviderExtensions.cs | 4 ++-- src/Umbraco.Core/Cache/DeepCloneAppCache.cs | 8 ++++---- .../Cache/DefaultRepositoryCachePolicy.cs | 2 +- .../Cache/FullDataSetRepositoryCachePolicy.cs | 2 +- .../{IAppPolicedCache.cs => IAppPolicyCache.cs} | 2 +- src/Umbraco.Core/Cache/IsolatedCaches.cs | 8 ++++---- src/Umbraco.Core/Cache/NoAppCache.cs | 4 ++-- .../Cache/NoCacheRepositoryCachePolicy.cs | 2 +- src/Umbraco.Core/Cache/ObjectCacheAppCache.cs | 4 ++-- .../Cache/RepositoryCachePolicyBase.cs | 6 +++--- .../Cache/SingleItemsOnlyRepositoryCachePolicy.cs | 2 +- src/Umbraco.Core/Cache/WebCachingAppCache.cs | 4 ++-- src/Umbraco.Core/Composing/TypeLoader.cs | 6 +++--- src/Umbraco.Core/Manifest/ManifestParser.cs | 2 +- .../Implement/RepositoryBaseOfTIdTEntity.cs | 6 +++--- .../Implement/LocalizedTextServiceFileSources.cs | 2 +- src/Umbraco.Core/Umbraco.Core.csproj | 2 +- .../Cache/DeepCloneRuntimeCacheProviderTests.cs | 2 +- src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs | 12 ++++++------ .../Cache/FullDataSetCachePolicyTests.cs | 14 +++++++------- .../Cache/HttpRuntimeCacheProviderTests.cs | 2 +- .../Cache/ObjectCacheProviderTests.cs | 2 +- .../Cache/RuntimeCacheProviderTests.cs | 2 +- .../Cache/SingleItemsOnlyCachePolicyTests.cs | 4 ++-- .../PublishedContentSnapshotTestBase.cs | 2 +- .../PublishedContent/PublishedContentTests.cs | 2 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 6 +++--- .../Editors/ExamineManagementController.cs | 2 +- 30 files changed, 67 insertions(+), 67 deletions(-) rename src/Umbraco.Core/Cache/{IAppPolicedCache.cs => IAppPolicyCache.cs} (97%) diff --git a/src/Umbraco.Core/Cache/AppCaches.cs b/src/Umbraco.Core/Cache/AppCaches.cs index 6372bccbab..7e5fa43682 100644 --- a/src/Umbraco.Core/Cache/AppCaches.cs +++ b/src/Umbraco.Core/Cache/AppCaches.cs @@ -30,7 +30,7 @@ namespace Umbraco.Core.Cache /// Initializes a new instance of the with cache providers. /// public AppCaches( - IAppPolicedCache runtimeCache, + IAppPolicyCache runtimeCache, IAppCache staticCacheProvider, IAppCache requestCache, IsolatedCaches isolatedCaches) @@ -82,7 +82,7 @@ namespace Umbraco.Core.Cache /// /// The runtime cache is the main application cache. /// - public IAppPolicedCache RuntimeCache { get; } + public IAppPolicyCache RuntimeCache { get; } /// /// Gets the isolated caches. diff --git a/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs index 51cc3c4c53..5c60dededa 100644 --- a/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs +++ b/src/Umbraco.Core/Cache/AppPolicedCacheDictionary.cs @@ -4,18 +4,18 @@ using System.Collections.Concurrent; namespace Umbraco.Core.Cache { /// - /// Provides a base class for implementing a dictionary of . + /// Provides a base class for implementing a dictionary of . /// /// The type of the dictionary key. public abstract class AppPolicedCacheDictionary { - private readonly ConcurrentDictionary _caches = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _caches = new ConcurrentDictionary(); /// /// Initializes a new instance of the class. /// /// - protected AppPolicedCacheDictionary(Func cacheFactory) + protected AppPolicedCacheDictionary(Func cacheFactory) { CacheFactory = cacheFactory; } @@ -23,19 +23,19 @@ namespace Umbraco.Core.Cache /// /// Gets the internal cache factory, for tests only! /// - internal readonly Func CacheFactory; + internal readonly Func CacheFactory; /// /// Gets or creates a cache. /// - public IAppPolicedCache GetOrCreate(TKey key) + public IAppPolicyCache GetOrCreate(TKey key) => _caches.GetOrAdd(key, k => CacheFactory(k)); /// /// Tries to get a cache. /// - public Attempt Get(TKey key) - => _caches.TryGetValue(key, out var cache) ? Attempt.Succeed(cache) : Attempt.Fail(); + public Attempt Get(TKey key) + => _caches.TryGetValue(key, out var cache) ? Attempt.Succeed(cache) : Attempt.Fail(); /// /// Removes a cache. diff --git a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs index 0e41b981fb..d943d19edb 100644 --- a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs +++ b/src/Umbraco.Core/Cache/CacheProviderExtensions.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.Cache /// public static class CacheProviderExtensions { - public static T GetCacheItem(this IAppPolicedCache provider, + public static T GetCacheItem(this IAppPolicyCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout, @@ -23,7 +23,7 @@ namespace Umbraco.Core.Cache return result == null ? default(T) : result.TryConvertTo().Result; } - public static void InsertCacheItem(this IAppPolicedCache provider, + public static void InsertCacheItem(this IAppPolicyCache provider, string cacheKey, Func getCacheItem, TimeSpan? timeout = null, diff --git a/src/Umbraco.Core/Cache/DeepCloneAppCache.cs b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs index cdc66f1db7..eff06e2aad 100644 --- a/src/Umbraco.Core/Cache/DeepCloneAppCache.cs +++ b/src/Umbraco.Core/Cache/DeepCloneAppCache.cs @@ -8,16 +8,16 @@ using Umbraco.Core.Models.Entities; namespace Umbraco.Core.Cache { /// - /// Implements by wrapping an inner other + /// Implements by wrapping an inner other /// instance, and ensuring that all inserts and returns are deep cloned copies of the cache item, /// when the item is deep-cloneable. /// - internal class DeepCloneAppCache : IAppPolicedCache + internal class DeepCloneAppCache : IAppPolicyCache { /// /// Initializes a new instance of the class. /// - public DeepCloneAppCache(IAppPolicedCache innerCache) + public DeepCloneAppCache(IAppPolicyCache innerCache) { var type = typeof (DeepCloneAppCache); @@ -30,7 +30,7 @@ namespace Umbraco.Core.Cache /// /// Gets the inner cache. /// - public IAppPolicedCache InnerCache { get; } + public IAppPolicyCache InnerCache { get; } /// public object Get(string key) diff --git a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs index 6f160cd552..c11309c827 100644 --- a/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/DefaultRepositoryCachePolicy.cs @@ -23,7 +23,7 @@ namespace Umbraco.Core.Cache private static readonly TEntity[] EmptyEntities = new TEntity[0]; // const private readonly RepositoryCachePolicyOptions _options; - public DefaultRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public DefaultRepositoryCachePolicy(IAppPolicyCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor) { _options = options ?? throw new ArgumentNullException(nameof(options)); diff --git a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs index 3bc4c9d059..c3b69d9a6d 100644 --- a/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/FullDataSetRepositoryCachePolicy.cs @@ -24,7 +24,7 @@ namespace Umbraco.Core.Cache private readonly Func _entityGetId; private readonly bool _expires; - public FullDataSetRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) + public FullDataSetRepositoryCachePolicy(IAppPolicyCache cache, IScopeAccessor scopeAccessor, Func entityGetId, bool expires) : base(cache, scopeAccessor) { _entityGetId = entityGetId; diff --git a/src/Umbraco.Core/Cache/IAppPolicedCache.cs b/src/Umbraco.Core/Cache/IAppPolicyCache.cs similarity index 97% rename from src/Umbraco.Core/Cache/IAppPolicedCache.cs rename to src/Umbraco.Core/Cache/IAppPolicyCache.cs index 0aee7584df..90b0ccb9fd 100644 --- a/src/Umbraco.Core/Cache/IAppPolicedCache.cs +++ b/src/Umbraco.Core/Cache/IAppPolicyCache.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.Cache /// /// A cache policy can be used to cache with timeouts, /// or depending on files, and with a remove callback, etc. - public interface IAppPolicedCache : IAppCache + public interface IAppPolicyCache : IAppCache { /// /// Gets an item identified by its key. diff --git a/src/Umbraco.Core/Cache/IsolatedCaches.cs b/src/Umbraco.Core/Cache/IsolatedCaches.cs index bc624be20d..f070fe8b55 100644 --- a/src/Umbraco.Core/Cache/IsolatedCaches.cs +++ b/src/Umbraco.Core/Cache/IsolatedCaches.cs @@ -3,7 +3,7 @@ namespace Umbraco.Core.Cache { /// - /// Represents a dictionary of for types. + /// Represents a dictionary of for types. /// /// /// Isolated caches are used by e.g. repositories, to ensure that each cached entity @@ -16,20 +16,20 @@ namespace Umbraco.Core.Cache /// Initializes a new instance of the class. /// /// - public IsolatedCaches(Func cacheFactory) + public IsolatedCaches(Func cacheFactory) : base(cacheFactory) { } /// /// Gets a cache. /// - public IAppPolicedCache GetOrCreate() + public IAppPolicyCache GetOrCreate() => GetOrCreate(typeof(T)); /// /// Tries to get a cache. /// - public Attempt Get() + public Attempt Get() => Get(typeof(T)); /// diff --git a/src/Umbraco.Core/Cache/NoAppCache.cs b/src/Umbraco.Core/Cache/NoAppCache.cs index 8a7e15cb29..d3359a30ba 100644 --- a/src/Umbraco.Core/Cache/NoAppCache.cs +++ b/src/Umbraco.Core/Cache/NoAppCache.cs @@ -6,9 +6,9 @@ using System.Web.Caching; namespace Umbraco.Core.Cache { /// - /// Implements and do not cache. + /// Implements and do not cache. /// - public class NoAppCache : IAppPolicedCache + public class NoAppCache : IAppPolicyCache { private NoAppCache() { } diff --git a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs index acc67be679..b1a12ec411 100644 --- a/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/NoCacheRepositoryCachePolicy.cs @@ -13,7 +13,7 @@ namespace Umbraco.Core.Cache public static NoCacheRepositoryCachePolicy Instance { get; } = new NoCacheRepositoryCachePolicy(); - public IRepositoryCachePolicy Scoped(IAppPolicedCache runtimeCache, IScope scope) + public IRepositoryCachePolicy Scoped(IAppPolicyCache runtimeCache, IScope scope) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs index 954622fc4b..449eb5d643 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs @@ -11,9 +11,9 @@ using CacheItemPriority = System.Web.Caching.CacheItemPriority; namespace Umbraco.Core.Cache { /// - /// Implements on top of a . + /// Implements on top of a . /// - public class ObjectCacheAppCache : IAppPolicedCache + public class ObjectCacheAppCache : IAppPolicyCache { private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); diff --git a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs index f8bba4b033..27fe4e3035 100644 --- a/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs +++ b/src/Umbraco.Core/Cache/RepositoryCachePolicyBase.cs @@ -13,16 +13,16 @@ namespace Umbraco.Core.Cache internal abstract class RepositoryCachePolicyBase : IRepositoryCachePolicy where TEntity : class, IEntity { - private readonly IAppPolicedCache _globalCache; + private readonly IAppPolicyCache _globalCache; private readonly IScopeAccessor _scopeAccessor; - protected RepositoryCachePolicyBase(IAppPolicedCache globalCache, IScopeAccessor scopeAccessor) + protected RepositoryCachePolicyBase(IAppPolicyCache globalCache, IScopeAccessor scopeAccessor) { _globalCache = globalCache ?? throw new ArgumentNullException(nameof(globalCache)); _scopeAccessor = scopeAccessor ?? throw new ArgumentNullException(nameof(scopeAccessor)); } - protected IAppPolicedCache Cache + protected IAppPolicyCache Cache { get { diff --git a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs index 714798a47c..9de7519edb 100644 --- a/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs +++ b/src/Umbraco.Core/Cache/SingleItemsOnlyRepositoryCachePolicy.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Cache internal class SingleItemsOnlyRepositoryCachePolicy : DefaultRepositoryCachePolicy where TEntity : class, IEntity { - public SingleItemsOnlyRepositoryCachePolicy(IAppPolicedCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) + public SingleItemsOnlyRepositoryCachePolicy(IAppPolicyCache cache, IScopeAccessor scopeAccessor, RepositoryCachePolicyOptions options) : base(cache, scopeAccessor, options) { } diff --git a/src/Umbraco.Core/Cache/WebCachingAppCache.cs b/src/Umbraco.Core/Cache/WebCachingAppCache.cs index b762fcda07..7fbdebf9ab 100644 --- a/src/Umbraco.Core/Cache/WebCachingAppCache.cs +++ b/src/Umbraco.Core/Cache/WebCachingAppCache.cs @@ -8,11 +8,11 @@ using System.Web.Caching; namespace Umbraco.Core.Cache { /// - /// Implements on top of a . + /// Implements on top of a . /// A CacheProvider that wraps the logic of the HttpRuntime.Cache /// /// The underlying cache is expected to be HttpRuntime.Cache. - internal class WebCachingAppCache : FastDictionaryAppCacheBase, IAppPolicedCache + 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 diff --git a/src/Umbraco.Core/Composing/TypeLoader.cs b/src/Umbraco.Core/Composing/TypeLoader.cs index fe277676d7..3950cf86e9 100644 --- a/src/Umbraco.Core/Composing/TypeLoader.cs +++ b/src/Umbraco.Core/Composing/TypeLoader.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Composing { private const string CacheKey = "umbraco-types.list"; - private readonly IAppPolicedCache _runtimeCache; + private readonly IAppPolicyCache _runtimeCache; private readonly IProfilingLogger _logger; private readonly Dictionary _types = new Dictionary(); @@ -51,7 +51,7 @@ namespace Umbraco.Core.Composing /// The application runtime cache. /// Files storage mode. /// A profiling logger. - public TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) + public TypeLoader(IAppPolicyCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger) : this(runtimeCache, localTempStorage, logger, true) { } @@ -62,7 +62,7 @@ namespace Umbraco.Core.Composing /// Files storage mode. /// A profiling logger. /// Whether to detect changes using hashes. - internal TypeLoader(IAppPolicedCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) + internal TypeLoader(IAppPolicyCache runtimeCache, LocalTempStorage localTempStorage, IProfilingLogger logger, bool detectChanges) { _runtimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); _localTempStorage = localTempStorage == LocalTempStorage.Unknown ? LocalTempStorage.Default : localTempStorage; diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index 40e99bb079..a80cd98466 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -20,7 +20,7 @@ namespace Umbraco.Core.Manifest { private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); - private readonly IAppPolicedCache _cache; + private readonly IAppPolicyCache _cache; private readonly ILogger _logger; private readonly ManifestValueValidatorCollection _validators; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs index 6862173786..c8329d1f32 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/RepositoryBaseOfTIdTEntity.cs @@ -30,7 +30,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement protected AppCaches AppCaches { get; } - protected IAppPolicedCache GlobalIsolatedCache => AppCaches.IsolatedCaches.GetOrCreate(); + protected IAppPolicyCache GlobalIsolatedCache => AppCaches.IsolatedCaches.GetOrCreate(); protected IScopeAccessor ScopeAccessor { get; } @@ -60,7 +60,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// Gets the isolated cache. /// /// Depends on the ambient scope cache mode. - protected IAppPolicedCache IsolatedCache + protected IAppPolicyCache IsolatedCache { get { @@ -157,7 +157,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// /// Adds or Updates an entity of type TEntity /// - /// This method is backed by an cache + /// This method is backed by an cache /// public void Save(TEntity entity) { diff --git a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs index 8c2d277348..430c2b3d3c 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizedTextServiceFileSources.cs @@ -17,7 +17,7 @@ namespace Umbraco.Core.Services.Implement public class LocalizedTextServiceFileSources { private readonly ILogger _logger; - private readonly IAppPolicedCache _cache; + private readonly IAppPolicyCache _cache; private readonly IEnumerable _supplementFileSources; private readonly DirectoryInfo _fileSourceFolder; diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index d72c0e5014..b94c718242 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -131,7 +131,7 @@ - + diff --git a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs index 5158989a8b..7483df1c44 100644 --- a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs @@ -34,7 +34,7 @@ namespace Umbraco.Tests.Cache get { return _provider; } } - internal override IAppPolicedCache RuntimeProvider + internal override IAppPolicyCache RuntimeProvider { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs index 0f649328fe..4161f576c9 100644 --- a/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/DefaultCachePolicyTests.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => @@ -45,7 +45,7 @@ namespace Umbraco.Tests.Cache [Test] public void Get_Single_From_Cache() { - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new DefaultRepositoryCachePolicy(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions()); @@ -58,7 +58,7 @@ namespace Umbraco.Tests.Cache public void Caches_Per_Id_For_Get_All() { var cached = new List(); - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => @@ -81,7 +81,7 @@ namespace Umbraco.Tests.Cache [Test] public void Get_All_Without_Ids_From_Cache() { - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.SearchByKey(It.IsAny())).Returns(new[] { new AuditItem(1, AuditType.Copy, 123, "test", "blah"), @@ -98,7 +98,7 @@ namespace Umbraco.Tests.Cache public void If_CreateOrUpdate_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { @@ -124,7 +124,7 @@ namespace Umbraco.Tests.Cache public void If_Removes_Throws_Cache_Is_Removed() { var cacheCleared = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { diff --git a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs index 7c5a1524d2..a4fbdf2224 100644 --- a/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/FullDataSetCachePolicyTests.cs @@ -37,7 +37,7 @@ namespace Umbraco.Tests.Cache }; var isCached = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => @@ -60,7 +60,7 @@ namespace Umbraco.Tests.Cache new AuditItem(2, AuditType.Copy, 123, "test", "blah2") }; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Get(It.IsAny())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah")); var defaultPolicy = new FullDataSetRepositoryCachePolicy(cache.Object, DefaultAccessor, item => item.Id, false); @@ -78,7 +78,7 @@ namespace Umbraco.Tests.Cache IList list = null; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Cache var cached = new List(); IList list = null; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => @@ -145,7 +145,7 @@ namespace Umbraco.Tests.Cache { var getAll = new[] { (AuditItem)null }; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Get(It.IsAny())).Returns(() => new DeepCloneableList(ListCloneBehavior.CloneOnce) { @@ -169,7 +169,7 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { @@ -201,7 +201,7 @@ namespace Umbraco.Tests.Cache }; var cacheCleared = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Clear(It.IsAny())) .Callback(() => { diff --git a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs index 56f3303e9c..6297539a1b 100644 --- a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Cache get { return _provider; } } - internal override IAppPolicedCache RuntimeProvider + internal override IAppPolicyCache RuntimeProvider { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs index 6ed7f590e0..4d34e81eff 100644 --- a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Cache get { return _provider; } } - internal override IAppPolicedCache RuntimeProvider + internal override IAppPolicyCache RuntimeProvider { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs index 08eb5e9a60..6391e4ec7a 100644 --- a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs @@ -8,7 +8,7 @@ namespace Umbraco.Tests.Cache public abstract class RuntimeCacheProviderTests : CacheProviderTests { - internal abstract IAppPolicedCache RuntimeProvider { get; } + internal abstract IAppPolicyCache RuntimeProvider { get; } [Test] diff --git a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs index 2b37d85801..2525eab45b 100644 --- a/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs +++ b/src/Umbraco.Tests/Cache/SingleItemsOnlyCachePolicyTests.cs @@ -28,7 +28,7 @@ namespace Umbraco.Tests.Cache public void Get_All_Doesnt_Cache() { var cached = new List(); - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string cacheKey, Func o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) => @@ -52,7 +52,7 @@ namespace Umbraco.Tests.Cache public void Caches_Single() { var isCached = false; - var cache = new Mock(); + var cache = new Mock(); cache.Setup(x => x.Insert(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback(() => diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs index 5b1dcde728..e293653c37 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs @@ -40,7 +40,7 @@ namespace Umbraco.Tests.PublishedContent Composition.RegisterUnique(f => new PublishedModelFactory(f.GetInstance().GetTypes())); } - protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicyCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index e798be82c4..705b2fd826 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -74,7 +74,7 @@ namespace Umbraco.Tests.PublishedContent ContentTypesCache.GetPublishedContentTypeByAlias = alias => alias.InvariantEquals("home") ? homeType : anythingType; } - protected override TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected override TypeLoader CreateTypeLoader(IAppPolicyCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { var pluginManager = base.CreateTypeLoader(runtimeCache, globalSettings, logger); diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index fd617b5a21..1b3f7f50bf 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -244,7 +244,7 @@ namespace Umbraco.Tests.Testing .ComposeWebMappingProfiles(); } - protected virtual TypeLoader GetTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) + protected virtual TypeLoader GetTypeLoader(IAppPolicyCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger, UmbracoTestOptions.TypeLoader option) { switch (option) { @@ -259,13 +259,13 @@ namespace Umbraco.Tests.Testing } } - protected virtual TypeLoader CreateTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + protected virtual TypeLoader CreateTypeLoader(IAppPolicyCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return CreateCommonTypeLoader(runtimeCache, globalSettings, logger); } // common to all tests = cannot be overriden - private static TypeLoader CreateCommonTypeLoader(IAppPolicedCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) + private static TypeLoader CreateCommonTypeLoader(IAppPolicyCache runtimeCache, IGlobalSettings globalSettings, IProfilingLogger logger) { return new TypeLoader(runtimeCache, globalSettings.LocalTempStorageLocation, logger, false) { diff --git a/src/Umbraco.Web/Editors/ExamineManagementController.cs b/src/Umbraco.Web/Editors/ExamineManagementController.cs index 8d930b8ed7..06334f86e7 100644 --- a/src/Umbraco.Web/Editors/ExamineManagementController.cs +++ b/src/Umbraco.Web/Editors/ExamineManagementController.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Editors { private readonly IExamineManager _examineManager; private readonly ILogger _logger; - private readonly IAppPolicedCache _runtimeCache; + private readonly IAppPolicyCache _runtimeCache; private readonly IndexRebuilder _indexRebuilder; From f952fe7aeb2acbf6ada02cf4454777e7def3b5df Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 18 Jan 2019 08:14:08 +0100 Subject: [PATCH 43/70] More renaming of caches --- ...derExtensions.cs => AppCacheExtensions.cs} | 2 +- src/Umbraco.Core/Cache/ObjectCacheAppCache.cs | 2 +- src/Umbraco.Core/Cache/WebCachingAppCache.cs | 1 - src/Umbraco.Core/Composing/Current.cs | 2 +- .../Implement/MemberGroupRepository.cs | 2 +- src/Umbraco.Core/Umbraco.Core.csproj | 2 +- ...CacheProviderTests.cs => AppCacheTests.cs} | 98 +++++++++---------- ...iderTests.cs => DeepCloneAppCacheTests.cs} | 7 +- ...erTests.cs => HttpRequestAppCacheTests.cs} | 8 +- .../Cache/HttpRuntimeCacheProviderTests.cs | 59 ----------- ...roviderTests.cs => ObjectAppCacheTests.cs} | 6 +- .../PublishedContentCacheTests.cs | 8 +- ...oviderTests.cs => RuntimeAppCacheTests.cs} | 16 ++- .../Cache/WebCachingAppCacheTests.cs | 50 ++++++++++ .../Scoping/ScopedRepositoryTests.cs | 6 +- src/Umbraco.Tests/Umbraco.Tests.csproj | 12 +-- .../Cache/ContentCacheRefresher.cs | 2 +- src/Umbraco.Web/Cache/MediaCacheRefresher.cs | 2 +- src/Umbraco.Web/Composing/Current.cs | 2 +- .../Dictionary/UmbracoCultureDictionary.cs | 20 ++-- .../Editors/CurrentUserController.cs | 2 +- src/Umbraco.Web/HtmlHelperRenderExtensions.cs | 2 +- src/Umbraco.Web/Macros/MacroRenderer.cs | 4 +- .../DictionaryPublishedContent.cs | 6 +- .../PublishedContentCache.cs | 16 +-- .../XmlPublishedCache/PublishedMediaCache.cs | 22 ++--- .../XmlPublishedCache/XmlPublishedContent.cs | 12 +-- 27 files changed, 178 insertions(+), 193 deletions(-) rename src/Umbraco.Core/Cache/{CacheProviderExtensions.cs => AppCacheExtensions.cs} (98%) rename src/Umbraco.Tests/Cache/{CacheProviderTests.cs => AppCacheTests.cs} (69%) rename src/Umbraco.Tests/Cache/{DeepCloneRuntimeCacheProviderTests.cs => DeepCloneAppCacheTests.cs} (94%) rename src/Umbraco.Tests/Cache/{HttpRequestCacheProviderTests.cs => HttpRequestAppCacheTests.cs} (82%) delete mode 100644 src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs rename src/Umbraco.Tests/Cache/{ObjectCacheProviderTests.cs => ObjectAppCacheTests.cs} (78%) rename src/Umbraco.Tests/Cache/{RuntimeCacheProviderTests.cs => RuntimeAppCacheTests.cs} (51%) create mode 100644 src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs diff --git a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs b/src/Umbraco.Core/Cache/AppCacheExtensions.cs similarity index 98% rename from src/Umbraco.Core/Cache/CacheProviderExtensions.cs rename to src/Umbraco.Core/Cache/AppCacheExtensions.cs index d943d19edb..ddba8be1b2 100644 --- a/src/Umbraco.Core/Cache/CacheProviderExtensions.cs +++ b/src/Umbraco.Core/Cache/AppCacheExtensions.cs @@ -8,7 +8,7 @@ namespace Umbraco.Core.Cache /// /// Extensions for strongly typed access /// - public static class CacheProviderExtensions + public static class AppCacheExtensions { public static T GetCacheItem(this IAppPolicyCache provider, string cacheKey, diff --git a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs index 449eb5d643..5c4f76f51d 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheAppCache.cs @@ -105,7 +105,7 @@ namespace Umbraco.Core.Cache /// public object Get(string key, Func factory, TimeSpan? timeout, bool isSliding = false, CacheItemPriority priority = CacheItemPriority.Normal, CacheItemRemovedCallback removedCallback = null, string[] dependentFiles = null) { - // see notes in HttpRuntimeCacheProvider + // see notes in HttpRuntimeAppCache Lazy result; diff --git a/src/Umbraco.Core/Cache/WebCachingAppCache.cs b/src/Umbraco.Core/Cache/WebCachingAppCache.cs index 7fbdebf9ab..c6e104221a 100644 --- a/src/Umbraco.Core/Cache/WebCachingAppCache.cs +++ b/src/Umbraco.Core/Cache/WebCachingAppCache.cs @@ -9,7 +9,6 @@ namespace Umbraco.Core.Cache { /// /// Implements on top of a . - /// A CacheProvider that wraps the logic of the HttpRuntime.Cache /// /// The underlying cache is expected to be HttpRuntime.Cache. internal class WebCachingAppCache : FastDictionaryAppCacheBase, IAppPolicyCache diff --git a/src/Umbraco.Core/Composing/Current.cs b/src/Umbraco.Core/Composing/Current.cs index bfc5cfd51c..429fee3317 100644 --- a/src/Umbraco.Core/Composing/Current.cs +++ b/src/Umbraco.Core/Composing/Current.cs @@ -180,7 +180,7 @@ namespace Umbraco.Core.Composing public static ICultureDictionaryFactory CultureDictionaryFactory => Factory.GetInstance(); - public static AppCaches ApplicationCache + public static AppCaches AppCaches => Factory.GetInstance(); public static ServiceContext Services diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs index 11166ce777..e6ee79470c 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberGroupRepository.cs @@ -124,7 +124,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var result = Get(qry); return result.FirstOrDefault(); }, - //cache for 5 mins since that is the default in the RuntimeCacheProvider + //cache for 5 mins since that is the default in the Runtime app cache TimeSpan.FromMinutes(5), //sliding is true true); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index b94c718242..5b2692359a 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -114,7 +114,7 @@ - + diff --git a/src/Umbraco.Tests/Cache/CacheProviderTests.cs b/src/Umbraco.Tests/Cache/AppCacheTests.cs similarity index 69% rename from src/Umbraco.Tests/Cache/CacheProviderTests.cs rename to src/Umbraco.Tests/Cache/AppCacheTests.cs index f2288cbaf2..f18e08d680 100644 --- a/src/Umbraco.Tests/Cache/CacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/AppCacheTests.cs @@ -7,9 +7,9 @@ using umbraco; namespace Umbraco.Tests.Cache { - public abstract class CacheProviderTests + public abstract class AppCacheTests { - internal abstract IAppCache Provider { get; } + internal abstract IAppCache AppCache { get; } protected abstract int GetTotalItemCount { get; } [SetUp] @@ -21,22 +21,22 @@ namespace Umbraco.Tests.Cache [TearDown] public virtual void TearDown() { - Provider.Clear(); + AppCache.Clear(); } [Test] public void Throws_On_Reentry() { // don't run for StaticCacheProvider - not making sense - if (GetType() == typeof (StaticCacheProviderTests)) + if (GetType() == typeof (StaticAppCacheTests)) Assert.Ignore("Do not run for StaticCacheProvider."); Exception exception = null; - var result = Provider.Get("blah", () => + var result = AppCache.Get("blah", () => { try { - var result2 = Provider.Get("blah"); + var result2 = AppCache.Get("blah"); } catch (Exception e) { @@ -56,7 +56,7 @@ namespace Umbraco.Tests.Cache object result; try { - result = Provider.Get("Blah", () => + result = AppCache.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -66,7 +66,7 @@ namespace Umbraco.Tests.Cache try { - result = Provider.Get("Blah", () => + result = AppCache.Get("Blah", () => { counter++; throw new Exception("Do not cache this"); @@ -85,13 +85,13 @@ namespace Umbraco.Tests.Cache object result; - result = Provider.Get("Blah", () => + result = AppCache.Get("Blah", () => { counter++; return ""; }); - result = Provider.Get("Blah", () => + result = AppCache.Get("Blah", () => { counter++; return ""; @@ -108,14 +108,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Tester2", () => cacheContent2); - Provider.Get("Tes3", () => cacheContent3); - Provider.Get("different4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Tester2", () => cacheContent2); + AppCache.Get("Tes3", () => cacheContent3); + AppCache.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - var result = Provider.SearchByKey("Tes"); + var result = AppCache.SearchByKey("Tes"); Assert.AreEqual(3, result.Count()); } @@ -127,14 +127,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("TTes1t", () => cacheContent1); - Provider.Get("Tester2", () => cacheContent2); - Provider.Get("Tes3", () => cacheContent3); - Provider.Get("different4", () => cacheContent4); + AppCache.Get("TTes1t", () => cacheContent1); + AppCache.Get("Tester2", () => cacheContent2); + AppCache.Get("Tes3", () => cacheContent3); + AppCache.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearByRegex("^\\w+es\\d.*"); + AppCache.ClearByRegex("^\\w+es\\d.*"); Assert.AreEqual(2, GetTotalItemCount); } @@ -146,14 +146,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Tester2", () => cacheContent2); - Provider.Get("Tes3", () => cacheContent3); - Provider.Get("different4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Tester2", () => cacheContent2); + AppCache.Get("Tes3", () => cacheContent3); + AppCache.Get("different4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearByKey("Test"); + AppCache.ClearByKey("Test"); Assert.AreEqual(2, GetTotalItemCount); } @@ -165,15 +165,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Test2", () => cacheContent2); - Provider.Get("Test3", () => cacheContent3); - Provider.Get("Test4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Test2", () => cacheContent2); + AppCache.Get("Test3", () => cacheContent3); + AppCache.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.Clear("Test1"); - Provider.Clear("Test2"); + AppCache.Clear("Test1"); + AppCache.Clear("Test2"); Assert.AreEqual(2, GetTotalItemCount); } @@ -185,14 +185,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Test2", () => cacheContent2); - Provider.Get("Test3", () => cacheContent3); - Provider.Get("Test4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Test2", () => cacheContent2); + AppCache.Get("Test3", () => cacheContent3); + AppCache.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.Clear(); + AppCache.Clear(); Assert.AreEqual(0, GetTotalItemCount); } @@ -201,7 +201,7 @@ namespace Umbraco.Tests.Cache public void Can_Add_When_Not_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - Provider.Get("Test1", () => cacheContent1); + AppCache.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); } @@ -209,8 +209,8 @@ namespace Umbraco.Tests.Cache public void Can_Get_When_Available() { var cacheContent1 = new MacroCacheContent(new LiteralControl(), "Test1"); - var result = Provider.Get("Test1", () => cacheContent1); - var result2 = Provider.Get("Test1", () => cacheContent1); + var result = AppCache.Get("Test1", () => cacheContent1); + var result2 = AppCache.Get("Test1", () => cacheContent1); Assert.AreEqual(1, GetTotalItemCount); Assert.AreEqual(result, result2); } @@ -222,15 +222,15 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Test2", () => cacheContent2); - Provider.Get("Test3", () => cacheContent3); - Provider.Get("Test4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Test2", () => cacheContent2); + AppCache.Get("Test3", () => cacheContent3); + AppCache.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); //Provider.ClearCacheObjectTypes("umbraco.MacroCacheContent"); - Provider.ClearOfType(typeof(MacroCacheContent).ToString()); + AppCache.ClearOfType(typeof(MacroCacheContent).ToString()); Assert.AreEqual(1, GetTotalItemCount); } @@ -242,14 +242,14 @@ namespace Umbraco.Tests.Cache var cacheContent2 = new MacroCacheContent(new LiteralControl(), "Test2"); var cacheContent3 = new MacroCacheContent(new LiteralControl(), "Test3"); var cacheContent4 = new LiteralControl(); - Provider.Get("Test1", () => cacheContent1); - Provider.Get("Test2", () => cacheContent2); - Provider.Get("Test3", () => cacheContent3); - Provider.Get("Test4", () => cacheContent4); + AppCache.Get("Test1", () => cacheContent1); + AppCache.Get("Test2", () => cacheContent2); + AppCache.Get("Test3", () => cacheContent3); + AppCache.Get("Test4", () => cacheContent4); Assert.AreEqual(4, GetTotalItemCount); - Provider.ClearOfType(); + AppCache.ClearOfType(); Assert.AreEqual(1, GetTotalItemCount); } diff --git a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs similarity index 94% rename from src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs rename to src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs index 7483df1c44..11e2c56873 100644 --- a/src/Umbraco.Tests/Cache/DeepCloneRuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/DeepCloneAppCacheTests.cs @@ -8,13 +8,12 @@ using Umbraco.Core.Cache; using Umbraco.Core.Collections; using Umbraco.Core.Models; using Umbraco.Core.Models.Entities; -using Umbraco.Core.Persistence.Repositories; using Umbraco.Tests.Collections; namespace Umbraco.Tests.Cache { [TestFixture] - public class DeepCloneRuntimeCacheProviderTests : RuntimeCacheProviderTests + public class DeepCloneAppCacheTests : RuntimeAppCacheTests { private DeepCloneAppCache _provider; @@ -29,12 +28,12 @@ namespace Umbraco.Tests.Cache _provider = new DeepCloneAppCache(new WebCachingAppCache(HttpRuntime.Cache)); } - internal override IAppCache Provider + internal override IAppCache AppCache { get { return _provider; } } - internal override IAppPolicyCache RuntimeProvider + internal override IAppPolicyCache AppPolicyCache { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs similarity index 82% rename from src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs rename to src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs index f442319d7f..635155f68e 100644 --- a/src/Umbraco.Tests/Cache/HttpRequestCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs @@ -5,7 +5,7 @@ using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Cache { [TestFixture] - public class HttpRequestCacheProviderTests : CacheProviderTests + public class HttpRequestAppCacheTests : AppCacheTests { private HttpRequestAppCache _provider; private FakeHttpContextFactory _ctx; @@ -17,7 +17,7 @@ namespace Umbraco.Tests.Cache _provider = new HttpRequestAppCache(_ctx.HttpContext); } - internal override IAppCache Provider + internal override IAppCache AppCache { get { return _provider; } } @@ -29,7 +29,7 @@ namespace Umbraco.Tests.Cache } [TestFixture] - public class StaticCacheProviderTests : CacheProviderTests + public class StaticAppCacheTests : AppCacheTests { private DictionaryCacheProvider _provider; @@ -39,7 +39,7 @@ namespace Umbraco.Tests.Cache _provider = new DictionaryCacheProvider(); } - internal override IAppCache Provider + internal override IAppCache AppCache { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs deleted file mode 100644 index 6297539a1b..0000000000 --- a/src/Umbraco.Tests/Cache/HttpRuntimeCacheProviderTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Diagnostics; -using System.Web; -using NUnit.Framework; -using Umbraco.Core.Cache; - -namespace Umbraco.Tests.Cache -{ - [TestFixture] - public class HttpRuntimeCacheProviderTests : RuntimeCacheProviderTests - { - private WebCachingAppCache _provider; - - protected override int GetTotalItemCount - { - get { return HttpRuntime.Cache.Count; } - } - - public override void Setup() - { - base.Setup(); - _provider = new WebCachingAppCache(HttpRuntime.Cache); - } - - internal override IAppCache Provider - { - get { return _provider; } - } - - internal override IAppPolicyCache RuntimeProvider - { - get { return _provider; } - } - - [Test] - public void DoesNotCacheExceptions() - { - string value; - Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(1)); }); - Assert.Throws(() => { value = (string)_provider.Get("key", () => GetValue(2)); }); - - // does not throw - value = (string)_provider.Get("key", () => GetValue(3)); - Assert.AreEqual("succ3", value); - - // cache - value = (string)_provider.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/Cache/ObjectCacheProviderTests.cs b/src/Umbraco.Tests/Cache/ObjectAppCacheTests.cs similarity index 78% rename from src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs rename to src/Umbraco.Tests/Cache/ObjectAppCacheTests.cs index 4d34e81eff..b9c729f891 100644 --- a/src/Umbraco.Tests/Cache/ObjectCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/ObjectAppCacheTests.cs @@ -8,7 +8,7 @@ using Umbraco.Core.Cache; namespace Umbraco.Tests.Cache { [TestFixture] - public class ObjectCacheProviderTests : RuntimeCacheProviderTests + public class ObjectAppCacheTests : RuntimeAppCacheTests { private ObjectCacheAppCache _provider; @@ -23,12 +23,12 @@ namespace Umbraco.Tests.Cache _provider = new ObjectCacheAppCache(); } - internal override IAppCache Provider + internal override IAppCache AppCache { get { return _provider; } } - internal override IAppPolicyCache RuntimeProvider + internal override IAppPolicyCache AppPolicyCache { get { return _provider; } } diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 79d0dfb9da..f740637602 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -63,12 +63,12 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml = new XmlDocument(); _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); - var cacheProvider = new DictionaryCacheProvider(); + var appCache = new DictionaryCacheProvider(); var domainCache = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot( - new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), - new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache, Factory.GetInstance()), - new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache), + new PublishedContentCache(xmlStore, domainCache, appCache, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), + new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, appCache, ContentTypesCache, Factory.GetInstance()), + new PublishedMemberCache(null, appCache, Current.Services.MemberService, ContentTypesCache), domainCache); var publishedSnapshotService = new Mock(); publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedShapshot); diff --git a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs b/src/Umbraco.Tests/Cache/RuntimeAppCacheTests.cs similarity index 51% rename from src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs rename to src/Umbraco.Tests/Cache/RuntimeAppCacheTests.cs index 6391e4ec7a..1beeae74db 100644 --- a/src/Umbraco.Tests/Cache/RuntimeCacheProviderTests.cs +++ b/src/Umbraco.Tests/Cache/RuntimeAppCacheTests.cs @@ -5,25 +5,23 @@ using Umbraco.Core.Cache; namespace Umbraco.Tests.Cache { - public abstract class RuntimeCacheProviderTests : CacheProviderTests + public abstract class RuntimeAppCacheTests : AppCacheTests { - - internal abstract IAppPolicyCache RuntimeProvider { get; } - + internal abstract IAppPolicyCache AppPolicyCache { get; } [Test] [Explicit("Testing for timeouts cannot work on VSTS.")] public void Can_Add_And_Expire_Struct_Strongly_Typed_With_Null() { var now = DateTime.Now; - RuntimeProvider.Insert("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); - Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); - Assert.AreEqual(now, Provider.GetCacheItem("DateTimeTest")); + AppPolicyCache.Insert("DateTimeTest", () => now, new TimeSpan(0, 0, 0, 0, 200)); + Assert.AreEqual(now, AppCache.GetCacheItem("DateTimeTest")); + Assert.AreEqual(now, AppCache.GetCacheItem("DateTimeTest")); Thread.Sleep(300); //sleep longer than the cache expiration - Assert.AreEqual(default(DateTime), Provider.GetCacheItem("DateTimeTest")); - Assert.AreEqual(null, Provider.GetCacheItem("DateTimeTest")); + Assert.AreEqual(default(DateTime), AppCache.GetCacheItem("DateTimeTest")); + Assert.AreEqual(null, AppCache.GetCacheItem("DateTimeTest")); } } } diff --git a/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs b/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs new file mode 100644 index 0000000000..e732ae5766 --- /dev/null +++ b/src/Umbraco.Tests/Cache/WebCachingAppCacheTests.cs @@ -0,0 +1,50 @@ +using System; +using System.Diagnostics; +using System.Web; +using NUnit.Framework; +using Umbraco.Core.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(); + _appCache = new WebCachingAppCache(HttpRuntime.Cache); + } + + 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/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index 12cd02d2e9..c56ec57db0 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -60,7 +60,7 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.UserService; - var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof(IUser)); + var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User("name", "email", "username", "rawPassword"); service.Save(user); @@ -137,7 +137,7 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (ILanguage)); + var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof (ILanguage)); var lang = (ILanguage) new Language("fr-FR"); service.Save(lang); @@ -229,7 +229,7 @@ namespace Umbraco.Tests.Scoping { var scopeProvider = ScopeProvider; var service = Current.Services.LocalizationService; - var globalCache = Current.ApplicationCache.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); + var globalCache = Current.AppCaches.IsolatedCaches.GetOrCreate(typeof (IDictionaryItem)); var lang = (ILanguage)new Language("fr-FR"); service.Save(lang); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index e49ba250fa..a2d33a1f31 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -225,7 +225,7 @@ - + @@ -286,11 +286,11 @@ - - - - - + + + + + diff --git a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs index 36397540b6..3f2ef1620c 100644 --- a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs @@ -102,7 +102,7 @@ namespace Umbraco.Web.Cache if (payloads.Any(x => x.ChangeTypes.HasType(TreeChangeTypes.RefreshAll)) || publishedChanged) { // when a public version changes - Current.ApplicationCache.ClearPartialViewCache(); + Current.AppCaches.ClearPartialViewCache(); MacroCacheRefresher.ClearMacroContentCache(AppCaches); // just the content } diff --git a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs index cdaf43dac3..fc62d38e62 100644 --- a/src/Umbraco.Web/Cache/MediaCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MediaCacheRefresher.cs @@ -47,7 +47,7 @@ namespace Umbraco.Web.Cache if (anythingChanged) { - Current.ApplicationCache.ClearPartialViewCache(); + Current.AppCaches.ClearPartialViewCache(); var mediaCache = AppCaches.IsolatedCaches.Get(); diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index ed1853c351..8759193964 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -203,7 +203,7 @@ namespace Umbraco.Web.Composing public static IProfilingLogger ProfilingLogger => CoreCurrent.ProfilingLogger; - public static AppCaches ApplicationCache => CoreCurrent.ApplicationCache; + public static AppCaches AppCaches => CoreCurrent.AppCaches; public static ServiceContext Services => CoreCurrent.Services; diff --git a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs index 5234bf9fa7..6e1c35352a 100644 --- a/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs +++ b/src/Umbraco.Web/Dictionary/UmbracoCultureDictionary.cs @@ -21,31 +21,29 @@ namespace Umbraco.Web.Dictionary public class DefaultCultureDictionary : Core.Dictionary.ICultureDictionary { private readonly ILocalizationService _localizationService; - private readonly IAppCache _requestCacheProvider; + private readonly IAppCache _requestCache; private readonly CultureInfo _specificCulture; public DefaultCultureDictionary() - : this(Current.Services.LocalizationService, Current.ApplicationCache.RequestCache) - { + : this(Current.Services.LocalizationService, Current.AppCaches.RequestCache) + { } - } - - public DefaultCultureDictionary(ILocalizationService localizationService, IAppCache requestCacheProvider) + public DefaultCultureDictionary(ILocalizationService localizationService, IAppCache requestCache) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); - _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); + _requestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache)); } public DefaultCultureDictionary(CultureInfo specificCulture) - : this(Current.Services.LocalizationService, Current.ApplicationCache.RequestCache) + : this(Current.Services.LocalizationService, Current.AppCaches.RequestCache) { _specificCulture = specificCulture ?? throw new ArgumentNullException(nameof(specificCulture)); } - public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, IAppCache requestCacheProvider) + public DefaultCultureDictionary(CultureInfo specificCulture, ILocalizationService localizationService, IAppCache requestCache) { _localizationService = localizationService ?? throw new ArgumentNullException(nameof(localizationService)); - _requestCacheProvider = requestCacheProvider ?? throw new ArgumentNullException(nameof(requestCacheProvider)); + _requestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache)); _specificCulture = specificCulture ?? throw new ArgumentNullException(nameof(specificCulture)); } @@ -123,7 +121,7 @@ namespace Umbraco.Web.Dictionary { //ensure it's stored/retrieved from request cache //NOTE: This is no longer necessary since these are cached at the runtime level, but we can leave it here for now. - return _requestCacheProvider.GetCacheItem(typeof (DefaultCultureDictionary).Name + "Culture" + Culture.Name, + return _requestCache.GetCacheItem(typeof (DefaultCultureDictionary).Name + "Culture" + Culture.Name, () => _localizationService.GetLanguageByIsoCode(Culture.Name)); } } diff --git a/src/Umbraco.Web/Editors/CurrentUserController.cs b/src/Umbraco.Web/Editors/CurrentUserController.cs index b0f4af0f57..02470e8ea1 100644 --- a/src/Umbraco.Web/Editors/CurrentUserController.cs +++ b/src/Umbraco.Web/Editors/CurrentUserController.cs @@ -157,7 +157,7 @@ namespace Umbraco.Web.Editors public async Task PostSetAvatar() { //borrow the logic from the user controller - return await UsersController.PostSetAvatarInternal(Request, Services.UserService, Current.ApplicationCache.StaticCache, Security.GetUserId().ResultOr(0)); + return await UsersController.PostSetAvatarInternal(Request, Services.UserService, Current.AppCaches.StaticCache, Security.GetUserId().ResultOr(0)); } /// diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index 9c30f74ea7..626a19a369 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -105,7 +105,7 @@ namespace Umbraco.Web var contextualKey = contextualKeyBuilder(model, viewData); cacheKey.AppendFormat("c{0}-", contextualKey); } - return Current.ApplicationCache.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData); + return Current.AppCaches.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData); } public static MvcHtmlString EditorFor(this HtmlHelper htmlHelper, string templateName = "", string htmlFieldName = "", object additionalViewData = null) diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index 0bcdb3225b..b7187da743 100755 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -94,7 +94,7 @@ namespace Umbraco.Web.Macros // only if cache is enabled if (UmbracoContext.Current.InPreviewMode || model.CacheDuration <= 0) return null; - var cache = Current.ApplicationCache.RuntimeCache; + var cache = Current.AppCaches.RuntimeCache; var macroContent = cache.GetCacheItem(CacheKeys.MacroContentCacheKey + model.CacheIdentifier); if (macroContent == null) return null; @@ -151,7 +151,7 @@ namespace Umbraco.Web.Macros // remember when we cache the content macroContent.Date = DateTime.Now; - var cache = Current.ApplicationCache.RuntimeCache; + var cache = Current.AppCaches.RuntimeCache; cache.Insert( CacheKeys.MacroContentCacheKey + model.CacheIdentifier, () => macroContent, diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs index e040e7e926..83bd84dab6 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DictionaryPublishedContent.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache Func getParent, Func> getChildren, Func getProperty, - IAppCache cacheProvider, + IAppCache appCache, PublishedContentTypeCache contentTypeCache, XPathNavigator nav, bool fromExamine) @@ -47,7 +47,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _getParent = new Lazy(() => getParent(ParentId)); _getChildren = new Lazy>(() => getChildren(Id, nav)); _getProperty = getProperty; - _cacheProvider = cacheProvider; + _appCache = appCache; LoadedFromExamine = fromExamine; @@ -133,7 +133,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache //private readonly Func> _getChildren; private readonly Lazy> _getChildren; private readonly Func _getProperty; - private readonly IAppCache _cacheProvider; + private readonly IAppCache _appCache; /// /// Returns 'Media' as the item type diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index 67813ce9f6..d8c7c41ea1 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -15,7 +15,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : PublishedCacheBase, IPublishedContentCache { - private readonly IAppCache _cacheProvider; + private readonly IAppCache _appCache; private readonly IGlobalSettings _globalSettings; private readonly RoutesCache _routesCache; private readonly IDomainCache _domainCache; @@ -24,13 +24,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // initialize a PublishedContentCache instance with // an XmlStore containing the master xml - // an ICacheProvider that should be at request-level + // an IAppCache that should be at request-level // a RoutesCache - need to cleanup that one // a preview token string (or null if not previewing) public PublishedContentCache( XmlStore xmlStore, // an XmlStore containing the master xml IDomainCache domainCache, // an IDomainCache implementation - IAppCache cacheProvider, // an ICacheProvider that should be at request-level + IAppCache appCache, // an IAppCache that should be at request-level IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache @@ -38,7 +38,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache string previewToken) // a preview token string (or null if not previewing) : base(previewToken.IsNullOrWhiteSpace() == false) { - _cacheProvider = cacheProvider; + _appCache = appCache; _globalSettings = globalSettings; _routesCache = routesCache; // may be null for unit-testing _contentTypeCache = contentTypeCache; @@ -315,13 +315,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing) { - return xmlNode == null ? null : XmlPublishedContent.Get(xmlNode, isPreviewing, _cacheProvider, _contentTypeCache); + return xmlNode == null ? null : XmlPublishedContent.Get(xmlNode, isPreviewing, _appCache, _contentTypeCache); } private IEnumerable ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing) { return xmlNodes.Cast() - .Select(xmlNode => XmlPublishedContent.Get(xmlNode, isPreviewing, _cacheProvider, _contentTypeCache)); + .Select(xmlNode => XmlPublishedContent.Get(xmlNode, isPreviewing, _appCache, _contentTypeCache)); } #endregion @@ -517,8 +517,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // clear recursive properties cached by XmlPublishedContent.GetProperty // assume that nothing else is going to cache IPublishedProperty items (else would need to do ByKeySearch) // NOTE also clears all the media cache properties, which is OK (see media cache) - _cacheProvider.ClearOfType(); - //_cacheProvider.ClearCacheByKeySearch("XmlPublishedCache.PublishedContentCache:RecursiveProperty-"); + _appCache.ClearOfType(); + //_appCache.ClearCacheByKeySearch("XmlPublishedCache.PublishedContentCache:RecursiveProperty-"); } #endregion diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs index 3ead5a5166..dadf40a33b 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs @@ -43,15 +43,15 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IEntityXmlSerializer _entitySerializer; // must be specified by the ctor - private readonly IAppCache _cacheProvider; + private readonly IAppCache _appCache; - public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + public PublishedMediaCache(XmlStore xmlStore, IMediaService mediaService, IUserService userService, IAppCache appCache, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); _userService = userService ?? throw new ArgumentNullException(nameof(userService)); - _cacheProvider = cacheProvider; + _appCache = appCache; _xmlStore = xmlStore; _contentTypeCache = contentTypeCache; _entitySerializer = entitySerializer; @@ -63,16 +63,16 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// /// /// - /// + /// /// /// - internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) + internal PublishedMediaCache(IMediaService mediaService, IUserService userService, ISearcher searchProvider, IAppCache appCache, PublishedContentTypeCache contentTypeCache, IEntityXmlSerializer entitySerializer) : base(false) { _mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService)); _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _searchProvider = searchProvider ?? throw new ArgumentNullException(nameof(searchProvider)); - _cacheProvider = cacheProvider; + _appCache = appCache; _contentTypeCache = contentTypeCache; _entitySerializer = entitySerializer; } @@ -598,8 +598,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // clear recursive properties cached by XmlPublishedContent.GetProperty // assume that nothing else is going to cache IPublishedProperty items (else would need to do ByKeySearch) // NOTE all properties cleared when clearing the content cache (see content cache) - //_cacheProvider.ClearCacheObjectTypes(); - //_cacheProvider.ClearCacheByKeySearch("XmlPublishedCache.PublishedMediaCache:RecursiveProperty-"); + //_appCache.ClearCacheObjectTypes(); + //_appCache.ClearCacheByKeySearch("XmlPublishedCache.PublishedMediaCache:RecursiveProperty-"); } #region Content types @@ -663,7 +663,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache parentId => parentId < 0 ? null : GetUmbracoMedia(parentId), GetChildrenMedia, GetProperty, - _cacheProvider, + _appCache, _contentTypeCache, cacheValues.XPath, // though, outside of tests, that should be null cacheValues.FromExamine @@ -676,14 +676,14 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache if (_publishedMediaCacheEnabled == false) return func(id); - var cache = Current.ApplicationCache.RuntimeCache; + var cache = Current.AppCaches.RuntimeCache; var key = PublishedMediaCacheKey + id; return (CacheValues)cache.Get(key, () => func(id), _publishedMediaCacheTimespan); } internal static void ClearCache(int id) { - var cache = Current.ApplicationCache.RuntimeCache; + var cache = Current.AppCaches.RuntimeCache; var sid = id.ToString(); var key = PublishedMediaCacheKey + sid; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index a313d6947d..eb54c85984 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -20,18 +20,18 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache [XmlType(Namespace = "http://umbraco.org/webservices/")] internal class XmlPublishedContent : PublishedContentBase { - private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) + private XmlPublishedContent(XmlNode xmlNode, bool isPreviewing, IAppCache appCache, PublishedContentTypeCache contentTypeCache) { _xmlNode = xmlNode; _isPreviewing = isPreviewing; - _cacheProvider = cacheProvider; + _appCache = appCache; _contentTypeCache = contentTypeCache; } private readonly XmlNode _xmlNode; private readonly bool _isPreviewing; - private readonly IAppCache _cacheProvider; // at snapshot/request level (see PublishedContentCache) + private readonly IAppCache _appCache; // at snapshot/request level (see PublishedContentCache) private readonly PublishedContentTypeCache _contentTypeCache; private readonly object _initializeLock = new object(); @@ -252,7 +252,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache if (parent == null) return; if (parent.Attributes?.GetNamedItem("isDoc") != null) - _parent = Get(parent, _isPreviewing, _cacheProvider, _contentTypeCache); + _parent = Get(parent, _isPreviewing, _appCache, _contentTypeCache); _parentInitialized = true; } @@ -409,7 +409,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var iterator = nav.Select(expr); _children = iterator.Cast() - .Select(n => Get(((IHasXmlNode) n).GetNode(), _isPreviewing, _cacheProvider, _contentTypeCache)) + .Select(n => Get(((IHasXmlNode) n).GetNode(), _isPreviewing, _appCache, _contentTypeCache)) .OrderBy(x => x.SortOrder) .ToList(); @@ -440,7 +440,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public static void ClearRequest() { - Current.ApplicationCache.RequestCache.ClearByKey(CacheKeyPrefix); + Current.AppCaches.RequestCache.ClearByKey(CacheKeyPrefix); } private const string CacheKeyPrefix = "CONTENTCACHE_XMLPUBLISHEDCONTENT_"; From ec58532f7bf70b055703b18bc7ded1e2278bfe1c Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 18 Jan 2019 08:29:16 +0100 Subject: [PATCH 44/70] More renaming of caches --- src/Umbraco.Core/Cache/AppCaches.cs | 6 +++--- ...CacheProvider.cs => DictionaryAppCache.cs} | 2 +- ...eProvider.cs => FastDictionaryAppCache.cs} | 2 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 2 +- src/Umbraco.Core/Umbraco.Core.csproj | 4 ++-- src/Umbraco.Tests/Cache/AppCacheTests.cs | 6 +++--- .../Cache/HttpRequestAppCacheTests.cs | 16 +++++++-------- .../PublishedContentCacheTests.cs | 2 +- .../PublishedMediaCacheTests.cs | 8 ++++---- src/Umbraco.Tests/Macros/MacroTests.cs | 2 +- .../Repositories/DocumentRepositoryTest.cs | 4 ++-- .../Repositories/MediaRepositoryTest.cs | 4 ++-- .../Published/PropertyCacheLevelTests.cs | 4 ++-- .../PublishedContent/PublishedMediaTests.cs | 20 +++++++++---------- .../Scoping/ScopedRepositoryTests.cs | 2 +- .../NuCache/PublishedSnapshotService.cs | 13 ++++++------ .../XmlPublishedCache/PublishedMemberCache.cs | 4 ++-- .../XmlPublishedCache/XmlPublishedContent.cs | 6 +++--- src/Umbraco.Web/Runtime/WebRuntime.cs | 2 +- 19 files changed, 55 insertions(+), 54 deletions(-) rename src/Umbraco.Core/Cache/{DictionaryCacheProvider.cs => DictionaryAppCache.cs} (98%) rename src/Umbraco.Core/Cache/{FastDictionaryCacheProvider.cs => FastDictionaryAppCache.cs} (99%) diff --git a/src/Umbraco.Core/Cache/AppCaches.cs b/src/Umbraco.Core/Cache/AppCaches.cs index 7e5fa43682..d81e79f7d8 100644 --- a/src/Umbraco.Core/Cache/AppCaches.cs +++ b/src/Umbraco.Core/Cache/AppCaches.cs @@ -21,7 +21,7 @@ namespace Umbraco.Core.Cache public AppCaches(System.Web.Caching.Cache cache) : this( new WebCachingAppCache(cache), - new DictionaryCacheProvider(), + new DictionaryAppCache(), new HttpRequestAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())) { } @@ -31,12 +31,12 @@ namespace Umbraco.Core.Cache /// public AppCaches( IAppPolicyCache runtimeCache, - IAppCache staticCacheProvider, + IAppCache staticCache, IAppCache requestCache, IsolatedCaches isolatedCaches) { RuntimeCache = runtimeCache ?? throw new ArgumentNullException(nameof(runtimeCache)); - StaticCache = staticCacheProvider ?? throw new ArgumentNullException(nameof(staticCacheProvider)); + StaticCache = staticCache ?? throw new ArgumentNullException(nameof(staticCache)); RequestCache = requestCache ?? throw new ArgumentNullException(nameof(requestCache)); IsolatedCaches = isolatedCaches ?? throw new ArgumentNullException(nameof(isolatedCaches)); } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/DictionaryAppCache.cs similarity index 98% rename from src/Umbraco.Core/Cache/DictionaryCacheProvider.cs rename to src/Umbraco.Core/Cache/DictionaryAppCache.cs index 2ff5f6ea83..4c08bd0524 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs +++ b/src/Umbraco.Core/Cache/DictionaryAppCache.cs @@ -8,7 +8,7 @@ namespace Umbraco.Core.Cache /// /// Implements on top of a concurrent dictionary. /// - public class DictionaryCacheProvider : IAppCache + public class DictionaryAppCache : IAppCache { /// /// Gets the internal items dictionary, for tests only! diff --git a/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/FastDictionaryAppCache.cs similarity index 99% rename from src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs rename to src/Umbraco.Core/Cache/FastDictionaryAppCache.cs index a3863dac52..bd545694f7 100644 --- a/src/Umbraco.Core/Cache/FastDictionaryCacheProvider.cs +++ b/src/Umbraco.Core/Cache/FastDictionaryAppCache.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.Cache /// /// Implements a fast on top of a concurrent dictionary. /// - internal class FastDictionaryCacheProvider : IAppCache + internal class FastDictionaryAppCache : IAppCache { /// /// Gets the internal items dictionary, for tests only! diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index 6bfe9cdb55..8f1fa54a0c 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -332,7 +332,7 @@ namespace Umbraco.Core.Runtime return new AppCaches( new DeepCloneAppCache(new ObjectCacheAppCache()), - new DictionaryCacheProvider(), + new DictionaryAppCache(), NoAppCache.Instance, new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 5b2692359a..49a1cf8d8f 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -121,7 +121,7 @@ - + @@ -141,7 +141,7 @@ - + diff --git a/src/Umbraco.Tests/Cache/AppCacheTests.cs b/src/Umbraco.Tests/Cache/AppCacheTests.cs index f18e08d680..29d61cc14a 100644 --- a/src/Umbraco.Tests/Cache/AppCacheTests.cs +++ b/src/Umbraco.Tests/Cache/AppCacheTests.cs @@ -27,9 +27,9 @@ namespace Umbraco.Tests.Cache [Test] public void Throws_On_Reentry() { - // don't run for StaticCacheProvider - not making sense - if (GetType() == typeof (StaticAppCacheTests)) - Assert.Ignore("Do not run for StaticCacheProvider."); + // don't run for DictionaryAppCache - not making sense + if (GetType() == typeof (DictionaryAppCacheTests)) + Assert.Ignore("Do not run for DictionaryAppCache."); Exception exception = null; var result = AppCache.Get("blah", () => diff --git a/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs b/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs index 635155f68e..0be38d2c55 100644 --- a/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs +++ b/src/Umbraco.Tests/Cache/HttpRequestAppCacheTests.cs @@ -7,19 +7,19 @@ namespace Umbraco.Tests.Cache [TestFixture] public class HttpRequestAppCacheTests : AppCacheTests { - private HttpRequestAppCache _provider; + private HttpRequestAppCache _appCache; private FakeHttpContextFactory _ctx; public override void Setup() { base.Setup(); _ctx = new FakeHttpContextFactory("http://localhost/test"); - _provider = new HttpRequestAppCache(_ctx.HttpContext); + _appCache = new HttpRequestAppCache(_ctx.HttpContext); } internal override IAppCache AppCache { - get { return _provider; } + get { return _appCache; } } protected override int GetTotalItemCount @@ -29,24 +29,24 @@ namespace Umbraco.Tests.Cache } [TestFixture] - public class StaticAppCacheTests : AppCacheTests + public class DictionaryAppCacheTests : AppCacheTests { - private DictionaryCacheProvider _provider; + private DictionaryAppCache _appCache; public override void Setup() { base.Setup(); - _provider = new DictionaryCacheProvider(); + _appCache = new DictionaryAppCache(); } internal override IAppCache AppCache { - get { return _provider; } + get { return _appCache; } } protected override int GetTotalItemCount { - get { return _provider.Items.Count; } + get { return _appCache.Items.Count; } } } } diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index f740637602..147a159d5f 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -63,7 +63,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml = new XmlDocument(); _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); - var appCache = new DictionaryCacheProvider(); + var appCache = new DictionaryAppCache(); var domainCache = new DomainCache(ServiceContext.DomainService, DefaultCultureAccessor); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedSnapshot( new PublishedContentCache(xmlStore, domainCache, appCache, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs index ee16a1dede..cfc45b8f53 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedMediaCacheTests.cs @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var mChild2 = MakeNewMedia("Child2", mType, user, mRoot2.Id); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument) null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var roots = cache.GetAtRoot(); Assert.AreEqual(2, roots.Count()); Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id})); @@ -93,7 +93,7 @@ namespace Umbraco.Tests.Cache.PublishedCache //var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234)); var umbracoContext = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), Current.Services.MediaService, Current.Services.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var publishedMedia = cache.GetById(mRoot.Id); Assert.IsNotNull(publishedMedia); @@ -204,7 +204,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var result = new SearchResult("1234", 1, () => fields.ToDictionary(x => x.Key, x => new List { x.Value })); - var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var store = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result)); DoAssert(doc, 1234, key, templateIdVal: null, 0, "/media/test.jpg", "Image", 23, "Shannon", "Shannon", 0, 0, "-1,1234", DateTime.Parse("2012-07-17T10:34:09"), DateTime.Parse("2012-07-16T10:34:09"), 2); @@ -220,7 +220,7 @@ namespace Umbraco.Tests.Cache.PublishedCache var xmlDoc = GetMediaXml(); ((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString()); var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator(); - var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true)); DoAssert(doc, 2000, key, templateIdVal: null, 2, "image1", "Image", 23, "Shannon", "Shannon", 33, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1); diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 225bd17618..15549d5d46 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -23,7 +23,7 @@ namespace Umbraco.Tests.Macros //we DO want cache enabled for these tests var cacheHelper = new AppCaches( new ObjectCacheAppCache(), - new DictionaryCacheProvider(), + new DictionaryAppCache(), NoAppCache.Instance, new IsolatedCaches(type => new ObjectCacheAppCache())); //Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of(), Mock.Of())); diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index 1641631f43..9b1c4defa2 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -77,8 +77,8 @@ namespace Umbraco.Tests.Persistence.Repositories { var realCache = new AppCaches( new ObjectCacheAppCache(), - new DictionaryCacheProvider(), - new DictionaryCacheProvider(), + new DictionaryAppCache(), + new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs index 33c8524bb4..5635def412 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MediaRepositoryTest.cs @@ -48,8 +48,8 @@ namespace Umbraco.Tests.Persistence.Repositories var realCache = new AppCaches( new ObjectCacheAppCache(), - new DictionaryCacheProvider(), - new DictionaryCacheProvider(), + new DictionaryAppCache(), + new DictionaryAppCache(), new IsolatedCaches(t => new ObjectCacheAppCache())); var provider = TestObjects.GetScopeProvider(Logger); diff --git a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs index 04444855fb..76fdd81ec2 100644 --- a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs +++ b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs @@ -118,8 +118,8 @@ namespace Umbraco.Tests.Published publishedContentTypeFactory.CreatePropertyType("prop1", 1), }); - var elementsCache = new FastDictionaryCacheProvider(); - var snapshotCache = new FastDictionaryCacheProvider(); + var elementsCache = new FastDictionaryAppCache(); + var snapshotCache = new FastDictionaryAppCache(); var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.SnapshotCache).Returns(snapshotCache); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 4257e3dabb..dfb51e83fb 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -68,7 +68,7 @@ namespace Umbraco.Tests.PublishedContent internal IPublishedContent GetNode(int id, UmbracoContext umbracoContext) { var cache = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), - ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, + ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var doc = cache.GetById(id); Assert.IsNotNull(doc); @@ -126,7 +126,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -156,7 +156,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //ensure it is found var publishedMedia = cache.GetById(3113); @@ -203,7 +203,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -231,7 +231,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -259,7 +259,7 @@ namespace Umbraco.Tests.PublishedContent var searcher = indexer.GetSearcher(); var ctx = GetUmbracoContext("/test"); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); @@ -288,7 +288,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -314,7 +314,7 @@ namespace Umbraco.Tests.PublishedContent var ctx = GetUmbracoContext("/test"); var searcher = indexer.GetSearcher(); - var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var cache = new PublishedMediaCache(ServiceContext.MediaService, ServiceContext.UserService, searcher, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); @@ -482,7 +482,7 @@ namespace Umbraco.Tests.PublishedContent "); var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var nav = node.CreateNavigator(); @@ -502,7 +502,7 @@ namespace Umbraco.Tests.PublishedContent var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); var nav = errorXml.CreateNavigator(); - var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryCacheProvider(), ContentTypesCache, Factory.GetInstance()); + var publishedMedia = new PublishedMediaCache(new XmlStore((XmlDocument)null, null, null, null), ServiceContext.MediaService, ServiceContext.UserService, new DictionaryAppCache(), ContentTypesCache, Factory.GetInstance()); var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); Assert.IsNull(converted); diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index c56ec57db0..99d2fbd222 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -42,7 +42,7 @@ namespace Umbraco.Tests.Scoping // this is what's created core web runtime return new AppCaches( new DeepCloneAppCache(new ObjectCacheAppCache()), - new DictionaryCacheProvider(), + new DictionaryAppCache(), NoAppCache.Instance, new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index bcb1c6ede3..3cca34fe77 100755 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -949,14 +949,15 @@ namespace Umbraco.Web.PublishedCache.NuCache // even though the underlying elements may not change (store snapshots) public PublishedSnapshot.PublishedSnapshotElements GetElements(bool previewDefault) { - // note: using ObjectCacheRuntimeCacheProvider for elements and snapshot caches + // note: using ObjectCacheAppCache for elements and snapshot caches // is not recommended because it creates an inner MemoryCache which is a heavy - // thing - better use a StaticCacheProvider which "just" creates a concurrent + // thing - better use a dictionary-based cache which "just" creates a concurrent // dictionary - // for snapshot cache, StaticCacheProvider MAY be OK but it is not thread-safe, + // for snapshot cache, DictionaryAppCache MAY be OK but it is not thread-safe, // nothing like that... - // for elements cache, StaticCacheProvider is a No-No, use something better. + // for elements cache, DictionaryAppCache is a No-No, use something better. + // ie FastDictionaryAppCache (thread safe and all) ContentStore.Snapshot contentSnap, mediaSnap; SnapDictionary.Snapshot domainSnap; @@ -998,11 +999,11 @@ namespace Umbraco.Web.PublishedCache.NuCache _contentGen = contentSnap.Gen; _mediaGen = mediaSnap.Gen; _domainGen = domainSnap.Gen; - elementsCache = _elementsCache = new FastDictionaryCacheProvider(); + elementsCache = _elementsCache = new FastDictionaryAppCache(); } } - var snapshotCache = new DictionaryCacheProvider(); + var snapshotCache = new DictionaryAppCache(); var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs index a622a4934c..816eb3c545 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMemberCache.cs @@ -17,9 +17,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly XmlStore _xmlStore; private readonly PublishedContentTypeCache _contentTypeCache; - public PublishedMemberCache(XmlStore xmlStore, IAppCache requestCacheProvider, IMemberService memberService, PublishedContentTypeCache contentTypeCache) + public PublishedMemberCache(XmlStore xmlStore, IAppCache requestCache, IMemberService memberService, PublishedContentTypeCache contentTypeCache) { - _requestCache = requestCacheProvider; + _requestCache = requestCache; _memberService = memberService; _xmlStore = xmlStore; _contentTypeCache = contentTypeCache; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index eb54c85984..2e19fc423b 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -421,13 +421,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// /// The Xml node. /// A value indicating whether we are previewing or not. - /// A cache provider. + /// A cache. /// A content type cache. /// The IPublishedContent corresponding to the Xml cache node. /// Maintains a per-request cache of IPublishedContent items in order to make /// sure that we create only one instance of each for the duration of a request. The /// returned IPublishedContent is a model, if models are enabled. - public static IPublishedContent Get(XmlNode node, bool isPreviewing, IAppCache cacheProvider, PublishedContentTypeCache contentTypeCache) + public static IPublishedContent Get(XmlNode node, bool isPreviewing, IAppCache appCache, PublishedContentTypeCache contentTypeCache) { // only 1 per request @@ -435,7 +435,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var id = attrs?.GetNamedItem("id").Value; if (id.IsNullOrWhiteSpace()) throw new InvalidOperationException("Node has no ID attribute."); var key = CacheKeyPrefix + id; // dont bother with preview, wont change during request in Xml cache - return (IPublishedContent) cacheProvider.Get(key, () => (new XmlPublishedContent(node, isPreviewing, cacheProvider, contentTypeCache)).CreateModel()); + return (IPublishedContent) appCache.Get(key, () => (new XmlPublishedContent(node, isPreviewing, appCache, contentTypeCache)).CreateModel()); } public static void ClearRequest() diff --git a/src/Umbraco.Web/Runtime/WebRuntime.cs b/src/Umbraco.Web/Runtime/WebRuntime.cs index e9d27a2a1c..90da402849 100644 --- a/src/Umbraco.Web/Runtime/WebRuntime.cs +++ b/src/Umbraco.Web/Runtime/WebRuntime.cs @@ -63,7 +63,7 @@ namespace Umbraco.Web.Runtime // 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)), - new DictionaryCacheProvider(), + new DictionaryAppCache(), // we need request based cache when running in web-based context new HttpRequestAppCache(), new IsolatedCaches(type => From a83ac4a24dd6ced3c6f993cd6c4e9c048191df67 Mon Sep 17 00:00:00 2001 From: Dave Woestenborghs Date: Fri, 18 Jan 2019 09:31:38 +0100 Subject: [PATCH 45/70] #3417 retreive data for edit screen --- .../src/common/resources/macro.resource.js | 6 + .../macros/infiniteeditors/parameter.html | 2 +- .../views/macros/macros.edit.controller.js | 48 ++++---- .../src/views/macros/views/settings.html | 3 +- src/Umbraco.Web/Editors/MacrosController.cs | 116 ++++++++++++++---- .../Models/ContentEditing/MacroDisplay.cs | 67 ++++++++++ .../ContentEditing/MacroParameterDisplay.cs | 29 +++++ src/Umbraco.Web/Umbraco.Web.csproj | 2 + 8 files changed, 220 insertions(+), 53 deletions(-) create mode 100644 src/Umbraco.Web/Models/ContentEditing/MacroDisplay.cs create mode 100644 src/Umbraco.Web/Models/ContentEditing/MacroParameterDisplay.cs diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js index 5313eadcaa..1471abd8d3 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/macro.resource.js @@ -101,6 +101,12 @@ function macroResource($q, $http, umbRequestHelper) { $http.get(umbRequestHelper.getApiUrl("macroApiBaseUrl", "GetParameterEditors"), "Failed to get parameter editors") ); + }, + + getById: function(id) { + return umbRequestHelper.resourcePromise( + $http.get(umbRequestHelper.getApiUrl("macroApiBaseUrl", "GetById", { "id" : id}), "Failed to get macro") + ); } }; } diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html index bf9dbf86a3..402c3c4984 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/infiniteeditors/parameter.html @@ -26,7 +26,7 @@ - + diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js index f8cde110e6..91af9b0f09 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/macros/macros.edit.controller.js @@ -83,11 +83,24 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta return deferred.promise; } + function getMacro() { + var deferred = $q.defer(); + + macroResource.getById($routeParams.id).then(function (data) { + deferred.resolve(data); + }, function () { + deferred.reject(); + }); + + return deferred.promise; + } + function init() { vm.page.loading = true; vm.promises['partialViews'] = getPartialViews(); vm.promises['parameterEditors'] = getParameterEditors(); + vm.promises['macro'] = getMacro(); $q.all(vm.promises).then(function (values) { var keys = Object.keys(values); @@ -102,12 +115,20 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta if (keys[i] === 'parameterEditors') { vm.parameterEditors = values[key]; } + + if (keys[i] === 'macro') { + vm.macro = values[key]; + editorState.set(vm.macro); + + navigationService.syncTree({ tree: "macros", path: vm.macro.path, forceReload: true }).then(function (syncArgs) { + vm.page.menu.currentNode = syncArgs.node; + }); + } } vm.page.loading = false; }); - vm.page.navigation = [ { "name": "Settings", @@ -123,31 +144,6 @@ function MacrosEditController($scope, $q, $routeParams, macroResource, editorSta "view": "views/macros/views/parameters.html" } ]; - - vm.macro = { - "name": "Test macro", - "alias": "testMacro", - "id": 1, - "key": "unique key goes here", - "useInEditor": true, - "renderInEditor": false, - "cachePeriod": 2400, - "cacheByPage": true, - "cacheByUser": false, - "view": "Second", - "parameters": [ - { - "key": "title", - "label": "Label", - "editor": "editor" - }, - { - "key": "link", - "label": "Link", - "editor": "Link picker" - } - ] - } } init(); diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html index 51e83a9134..ba5b324837 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html @@ -2,7 +2,8 @@ - + diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 6e2d032ad4..d604137e19 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -1,25 +1,24 @@ -using System; -using System.Net; -using System.Net.Http; -using System.Web.Http; - -using Umbraco.Core; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Web.Mvc; -using Umbraco.Web.WebApi; -using Umbraco.Web.WebApi.Filters; - -using Constants = Umbraco.Core.Constants; - -namespace Umbraco.Web.Editors +namespace Umbraco.Web.Editors { + using System; using System.Collections.Generic; using System.IO; using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + using Umbraco.Core; using Umbraco.Core.IO; + using Umbraco.Core.Logging; + using Umbraco.Core.Models; using Umbraco.Web.Composing; + using Umbraco.Web.Models.ContentEditing; + using Umbraco.Web.Mvc; + using Umbraco.Web.WebApi; + using Umbraco.Web.WebApi.Filters; + + using Constants = Umbraco.Core.Constants; /// /// The API controller used for editing dictionary items @@ -41,33 +40,75 @@ namespace Umbraco.Web.Editors public HttpResponseMessage Create(string name) { if (string.IsNullOrWhiteSpace(name)) - return Request - .CreateNotificationValidationErrorResponse("Name can not be empty;"); + { + return this.ReturnErrorResponse("Name can not be empty"); + } var alias = name.ToSafeAlias(); - var existingMacro = this.Services.MacroService.GetByAlias(alias); - - if (existingMacro != null) + if (this.Services.MacroService.GetByAlias(alias) != null) { - return Request.CreateNotificationValidationErrorResponse("Macro with this name already exists"); + return this.ReturnErrorResponse("Macro with this name already exists"); } try { - var macro = new Macro { Alias = alias, Name = name, MacroSource = string.Empty }; + var macro = new Macro + { + Alias = alias, + Name = name, + MacroSource = string.Empty, + MacroType = MacroTypes.PartialView + }; this.Services.MacroService.Save(macro, this.Security.CurrentUser.Id); - return Request.CreateResponse(HttpStatusCode.OK, macro.Id); + return this.Request.CreateResponse(HttpStatusCode.OK, macro.Id); } catch (Exception exception) { - this.Logger.Error(exception, "Error creating macro"); - return Request.CreateNotificationValidationErrorResponse("Error creating dictionary item"); + return this.ReturnErrorResponse("Error creating macro", true, exception); } } + [HttpGet] + public HttpResponseMessage GetById(int id) + { + var macro = this.Services.MacroService.GetById(id); + + if (macro == null) + { + return this.ReturnErrorResponse($"Macro with id {id} does not exist"); + } + + var macroDisplay = new MacroDisplay + { + Alias = macro.Alias, Id = macro.Id, Key = macro.Key, Name = macro.Name, + CacheByPage = macro.CacheByPage, CacheByUser = macro.CacheByMember, + CachePeriod = macro.CacheDuration, + View = macro.MacroSource, + RenderInEditor = !macro.DontRender, + UseInEditor = macro.UseInEditor, + Path = $"-1,{macro.Id}" + }; + + var parameters = new List(); + + foreach (var param in macro.Properties.Values.OrderBy(x => x.SortOrder)) + { + parameters.Add(new MacroParameterDisplay + { + Editor = param.EditorAlias, + Key = param.Alias, + Label = param.Name + }); + } + + macroDisplay.Parameters = parameters; + + return this.Request.CreateResponse(HttpStatusCode.OK, macroDisplay); + } + /// /// Gets a list of available macro partials /// @@ -94,6 +135,31 @@ namespace Umbraco.Web.Editors return this.Request.CreateResponse(HttpStatusCode.OK, Current.ParameterEditors); } + /// + /// Returns a error response and optionally logs it + /// + /// + /// The error message. + /// + /// + /// Value to indicate if the error needs to be logged + /// + /// + /// The exception to log + /// + /// + /// The . + /// + private HttpResponseMessage ReturnErrorResponse(string message, bool logError = false, Exception exception = null) + { + if (logError && exception != null) + { + this.Logger.Error(exception, message); + } + + return this.Request.CreateNotificationValidationErrorResponse(message); + } + /// /// Finds all the macro partials /// diff --git a/src/Umbraco.Web/Models/ContentEditing/MacroDisplay.cs b/src/Umbraco.Web/Models/ContentEditing/MacroDisplay.cs new file mode 100644 index 0000000000..e84887b88b --- /dev/null +++ b/src/Umbraco.Web/Models/ContentEditing/MacroDisplay.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace Umbraco.Web.Models.ContentEditing +{ + /// + /// The macro display model + /// + [DataContract(Name = "dictionary", Namespace = "")] + public class MacroDisplay : EntityBasic, INotificationModel + { + /// + /// Initializes a new instance of the class. + /// + public MacroDisplay() + { + this.Notifications = new List(); + this.Parameters = new List(); + } + + /// + [DataMember(Name = "notifications")] + public List Notifications { get; } + + /// + /// Gets or sets a value indicating whether the macro can be used in a rich text editor. + /// + [DataMember(Name = "useInEditor")] + public bool UseInEditor { get; set; } + + /// + /// Gets or sets a value indicating whether the macro should be rendered a rich text editor. + /// + [DataMember(Name = "renderInEditor")] + public bool RenderInEditor { get; set; } + + /// + /// Gets or sets the cache period. + /// + [DataMember(Name = "cachePeriod")] + public int CachePeriod { get; set; } + + /// + /// Gets or sets a value indicating whether the macro should be cached by page + /// + [DataMember(Name = "cacheByPage")] + public bool CacheByPage { get; set; } + + /// + /// Gets or sets a value indicating whether the macro should be cached by user + /// + [DataMember(Name = "cacheByUser")] + public bool CacheByUser { get; set; } + + /// + /// Gets or sets the view. + /// + [DataMember(Name = "view")] + public string View { get; set; } + + /// + /// Gets or sets the parameters. + /// + [DataMember(Name = "parameters")] + public IEnumerable Parameters { get; set; } + } +} diff --git a/src/Umbraco.Web/Models/ContentEditing/MacroParameterDisplay.cs b/src/Umbraco.Web/Models/ContentEditing/MacroParameterDisplay.cs new file mode 100644 index 0000000000..56d3d1b76e --- /dev/null +++ b/src/Umbraco.Web/Models/ContentEditing/MacroParameterDisplay.cs @@ -0,0 +1,29 @@ +namespace Umbraco.Web.Models.ContentEditing +{ + using System.Runtime.Serialization; + + /// + /// The macro parameter display. + /// + [DataContract(Name = "parameter", Namespace = "")] + public class MacroParameterDisplay + { + /// + /// Gets or sets the key. + /// + [DataMember(Name = "key")] + public string Key { get; set; } + + /// + /// Gets or sets the label. + /// + [DataMember(Name = "label")] + public string Label { get; set; } + + /// + /// Gets or sets the editor. + /// + [DataMember(Name = "editor")] + public string Editor { get; set; } + } +} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 7186835ba8..dbf422531d 100755 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -158,6 +158,8 @@ + + From 6dd4d7f475b72ced50578f9a16e2e99d5c4ce7f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Fri, 18 Jan 2019 10:12:24 +0100 Subject: [PATCH 46/70] V8 FE Gulp Fastdev script --- .editorconfig | 6 +- .../gulp/tasks/fastdev.js | 13 ++ .../gulp/util/processJs.js | 24 ++- .../gulp/util/processLess.js | 21 ++- src/Umbraco.Web.UI.Client/gulpfile.js | 2 + src/Umbraco.Web.UI.Client/package-lock.json | 154 +++++++++++++++--- src/Umbraco.Web.UI.Client/package.json | 5 +- 7 files changed, 185 insertions(+), 40 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/gulp/tasks/fastdev.js diff --git a/.editorconfig b/.editorconfig index c63ef39430..2305dd4b32 100644 --- a/.editorconfig +++ b/.editorconfig @@ -34,4 +34,8 @@ dotnet_naming_style.prefix_underscore.required_prefix = _ csharp_style_var_for_built_in_types = true:suggestion csharp_style_var_when_type_is_apparent = true:suggestion csharp_style_var_elsewhere = true:suggestion -csharp_prefer_braces = false : none +csharp_prefer_braces = false : none + +[*.{js,less}] +trim_trailing_whitespace = false +insert_final_newline = false diff --git a/src/Umbraco.Web.UI.Client/gulp/tasks/fastdev.js b/src/Umbraco.Web.UI.Client/gulp/tasks/fastdev.js new file mode 100644 index 0000000000..888ed38fec --- /dev/null +++ b/src/Umbraco.Web.UI.Client/gulp/tasks/fastdev.js @@ -0,0 +1,13 @@ +'use strict'; + +var config = require('../config'); +var gulp = require('gulp'); +var runSequence = require('run-sequence'); + +// Dev - build the files ready for development and start watchers +gulp.task('fastdev', function(cb) { + + global.isProd = false; + + runSequence(["dependencies", "js", "less", "views"], "watch", cb); +}); \ No newline at end of file diff --git a/src/Umbraco.Web.UI.Client/gulp/util/processJs.js b/src/Umbraco.Web.UI.Client/gulp/util/processJs.js index c110fa9cae..45927dc0e6 100644 --- a/src/Umbraco.Web.UI.Client/gulp/util/processJs.js +++ b/src/Umbraco.Web.UI.Client/gulp/util/processJs.js @@ -9,18 +9,24 @@ var concat = require('gulp-concat'); var wrap = require("gulp-wrap-js"); module.exports = function(files, out) { - - return gulp.src(files) + + var task = gulp.src(files); + + if (global.isProd === true) { // check for js errors - .pipe(eslint()) + task = task.pipe(eslint()); // outputs the lint results to the console - .pipe(eslint.format()) - // sort files in stream by path or any custom sort comparator - .pipe(babel()) + task = task.pipe(eslint.format()); + } + + // sort files in stream by path or any custom sort comparator + task = task.pipe(babel()) .pipe(sort()) .pipe(concat(out)) .pipe(wrap('(function(){\n%= body %\n})();')) .pipe(gulp.dest(config.root + config.targets.js)); - - console.log(out + " compiled"); -}; + + + return task; + +}; \ No newline at end of file diff --git a/src/Umbraco.Web.UI.Client/gulp/util/processLess.js b/src/Umbraco.Web.UI.Client/gulp/util/processLess.js index e2bb758499..26f69865d9 100644 --- a/src/Umbraco.Web.UI.Client/gulp/util/processLess.js +++ b/src/Umbraco.Web.UI.Client/gulp/util/processLess.js @@ -10,17 +10,24 @@ var cleanCss = require("gulp-clean-css"); var rename = require('gulp-rename'); module.exports = function(files, out) { + var processors = [ autoprefixer, cssnano({zindex: false}) ]; - return gulp.src(files) - .pipe(less()) - .pipe(cleanCss()) - .pipe(postcss(processors)) + var task = gulp.src(files) + .pipe(less()); + + + if (global.isProd === true) { + task = task.pipe(cleanCss()); + } + + task = task.pipe(postcss(processors)) .pipe(rename(out)) .pipe(gulp.dest(config.root + config.targets.css)); - - console.log(out + " compiled"); -} + + return task; + +}; \ No newline at end of file diff --git a/src/Umbraco.Web.UI.Client/gulpfile.js b/src/Umbraco.Web.UI.Client/gulpfile.js index f01d992013..79a9d04156 100755 --- a/src/Umbraco.Web.UI.Client/gulpfile.js +++ b/src/Umbraco.Web.UI.Client/gulpfile.js @@ -11,4 +11,6 @@ * To add a new task, simply add a new task file to gulp/tasks. */ +global.isProd = true; + require('./gulp'); diff --git a/src/Umbraco.Web.UI.Client/package-lock.json b/src/Umbraco.Web.UI.Client/package-lock.json index 02ad091f75..fe657ae470 100644 --- a/src/Umbraco.Web.UI.Client/package-lock.json +++ b/src/Umbraco.Web.UI.Client/package-lock.json @@ -5115,6 +5115,12 @@ "integrity": "sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=", "dev": true }, + "fs": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.2.tgz", + "integrity": "sha1-4fJE7zkzwbKmS9R5kTYGDQ9ZFPg=", + "dev": true + }, "fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -5204,14 +5210,12 @@ "balanced-match": { "version": "1.0.0", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, "dev": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5226,20 +5230,17 @@ "code-point-at": { "version": "1.1.0", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "concat-map": { "version": "0.0.1", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "console-control-strings": { "version": "1.1.0", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "core-util-is": { "version": "1.0.2", @@ -5356,8 +5357,7 @@ "inherits": { "version": "2.0.3", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "ini": { "version": "1.3.5", @@ -5369,7 +5369,6 @@ "version": "1.0.0", "bundled": true, "dev": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5384,7 +5383,6 @@ "version": "3.0.4", "bundled": true, "dev": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } @@ -5392,14 +5390,12 @@ "minimist": { "version": "0.0.8", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "minipass": { "version": "2.2.4", "bundled": true, "dev": true, - "optional": true, "requires": { "safe-buffer": "^5.1.1", "yallist": "^3.0.0" @@ -5418,7 +5414,6 @@ "version": "0.5.1", "bundled": true, "dev": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -5499,8 +5494,7 @@ "number-is-nan": { "version": "1.0.1", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "object-assign": { "version": "4.1.1", @@ -5512,7 +5506,6 @@ "version": "1.4.0", "bundled": true, "dev": true, - "optional": true, "requires": { "wrappy": "1" } @@ -5634,7 +5627,6 @@ "version": "1.0.2", "bundled": true, "dev": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -6133,6 +6125,12 @@ "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU=", "dev": true }, + "growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", + "dev": true + }, "gulp": { "version": "3.9.1", "resolved": "http://registry.npmjs.org/gulp/-/gulp-3.9.1.tgz", @@ -6930,6 +6928,102 @@ } } }, + "gulp-notify": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/gulp-notify/-/gulp-notify-3.2.0.tgz", + "integrity": "sha512-qEocs1UVoDKKUjfsxJNMNwkRla0PbsyJwsqNNXpzYWsLQ29LhxRMY3wnTGZcc4hMHtalnvah/Dwlwb4NijH/0A==", + "dev": true, + "requires": { + "ansi-colors": "^1.0.1", + "fancy-log": "^1.3.2", + "lodash.template": "^4.4.0", + "node-notifier": "^5.2.1", + "node.extend": "^2.0.0", + "plugin-error": "^0.1.2", + "through2": "^2.0.3" + }, + "dependencies": { + "arr-diff": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", + "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1", + "array-slice": "^0.2.3" + } + }, + "arr-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", + "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", + "dev": true + }, + "array-slice": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", + "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", + "dev": true + }, + "extend-shallow": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", + "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", + "dev": true, + "requires": { + "kind-of": "^1.1.0" + } + }, + "kind-of": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", + "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", + "dev": true + }, + "lodash.template": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.4.0.tgz", + "integrity": "sha1-5zoDhcg1VZF0bgILmWecaQ5o+6A=", + "dev": true, + "requires": { + "lodash._reinterpolate": "~3.0.0", + "lodash.templatesettings": "^4.0.0" + } + }, + "lodash.templatesettings": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/lodash.templatesettings/-/lodash.templatesettings-4.1.0.tgz", + "integrity": "sha1-K01OlbpEDZFf8IvImeRVNmZxMxY=", + "dev": true, + "requires": { + "lodash._reinterpolate": "~3.0.0" + } + }, + "node.extend": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/node.extend/-/node.extend-2.0.2.tgz", + "integrity": "sha512-pDT4Dchl94/+kkgdwyS2PauDFjZG0Hk0IcHIB+LkW27HLDtdoeMxHTxZh39DYbPP8UflWXWj9JcdDozF+YDOpQ==", + "dev": true, + "requires": { + "has": "^1.0.3", + "is": "^3.2.1" + } + }, + "plugin-error": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", + "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", + "dev": true, + "requires": { + "ansi-cyan": "^0.1.1", + "ansi-red": "^0.1.1", + "arr-diff": "^1.0.1", + "arr-union": "^2.0.1", + "extend-shallow": "^1.1.2" + } + } + } + }, "gulp-open": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/gulp-open/-/gulp-open-3.0.1.tgz", @@ -9382,6 +9476,18 @@ "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", "dev": true }, + "node-notifier": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.3.0.tgz", + "integrity": "sha512-AhENzCSGZnZJgBARsUjnQ7DnZbzyP+HxlVXuD0xqAnvL8q+OqtSX7lGg9e8nHzwXkMMXNdVeqq4E2M3EUAqX6Q==", + "dev": true, + "requires": { + "growly": "^1.3.0", + "semver": "^5.5.0", + "shellwords": "^0.1.1", + "which": "^1.3.0" + } + }, "node-releases": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.0.5.tgz", @@ -14138,6 +14244,12 @@ "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, + "shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", + "dev": true + }, "sigmund": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", diff --git a/src/Umbraco.Web.UI.Client/package.json b/src/Umbraco.Web.UI.Client/package.json index 6e8159a940..61bdb88f17 100644 --- a/src/Umbraco.Web.UI.Client/package.json +++ b/src/Umbraco.Web.UI.Client/package.json @@ -3,8 +3,9 @@ "scripts": { "test": "karma start test/config/karma.conf.js --singlerun", "build": "gulp build", - "dev": "gulp dev", - "docs": "gulp docs" + "dev": "gulp dev", + "fastdev": "gulp fastdev", + "docs": "gulp docs" }, "dependencies": { "ace-builds": "1.4.2", From cee1171d39a93de59f862a2a7107edae3a93602f Mon Sep 17 00:00:00 2001 From: Callum Whyte Date: Fri, 18 Jan 2019 20:53:38 +1100 Subject: [PATCH 47/70] Removing masterpages support from V8 (#3971) --- .../Composers/ConfigurationComposer.cs | 1 - .../UmbracoSettings/ITemplatesSection.cs | 9 - .../IUmbracoSettingsSection.cs | 4 - .../UmbracoSettings/TemplatesElement.cs | 20 - .../UmbracoSettings/UmbracoSettingsSection.cs | 18 +- src/Umbraco.Core/IO/FileSystems.cs | 14 - src/Umbraco.Core/IO/IFileSystems.cs | 5 - src/Umbraco.Core/IO/MasterPageHelper.cs | 445 ------------------ src/Umbraco.Core/IO/SystemDirectories.cs | 4 - src/Umbraco.Core/Models/ITemplate.cs | 6 +- .../Packaging/PackageDataInstallation.cs | 17 +- .../Repositories/ITemplateRepository.cs | 19 +- .../Implement/TemplateRepository.cs | 136 +----- src/Umbraco.Core/Services/IFileService.cs | 15 - .../Services/Implement/FileService.cs | 24 +- src/Umbraco.Core/Umbraco.Core.csproj | 3 - .../TemplateElementDefaultTests.cs | 13 - .../UmbracoSettings/TemplateElementTests.cs | 16 - .../UmbracoSettings/umbracoSettings.config | 4 - .../umbracoSettings.minimal.config | 5 - src/Umbraco.Tests/IO/IoHelperTests.cs | 1 - .../Repositories/ContentTypeRepositoryTest.cs | 9 +- .../Repositories/DocumentRepositoryTest.cs | 2 +- .../Repositories/DomainRepositoryTest.cs | 4 +- .../PublicAccessRepositoryTest.cs | 4 +- .../Repositories/TagRepositoryTest.cs | 2 +- .../Repositories/TemplateRepositoryTest.cs | 135 +----- .../Repositories/UserRepositoryTest.cs | 2 +- .../Services/ContentServicePerformanceTest.cs | 8 +- .../Services/ContentServiceTests.cs | 2 +- .../Templates/MasterPageHelperTests.cs | 21 - .../Templates/TemplateRepositoryTests.cs | 121 ----- .../TestHelpers/SettingsForTests.cs | 3 - src/Umbraco.Tests/TestHelpers/TestHelper.cs | 5 +- .../TestHelpers/TestObjects-Mocks.cs | 3 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 1 - src/Umbraco.Tests/Umbraco.Tests.csproj | 4 - .../config/umbracoSettings.Release.config | 5 - .../config/umbracoSettings.config | 5 - .../FolderAndFilePermissionsCheck.cs | 1 - .../Install/FilePermissionHelper.cs | 3 +- src/Umbraco.Web/Routing/PublishedRouter.cs | 4 - .../Trees/TemplatesTreeController.cs | 13 +- .../umbraco.presentation/default.aspx.cs | 16 - 44 files changed, 38 insertions(+), 1114 deletions(-) delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/ITemplatesSection.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/TemplatesElement.cs delete mode 100644 src/Umbraco.Core/IO/MasterPageHelper.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementDefaultTests.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementTests.cs delete mode 100644 src/Umbraco.Tests/Templates/MasterPageHelperTests.cs delete mode 100644 src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs diff --git a/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs b/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs index ca86f623cc..7fba47a2cd 100644 --- a/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs +++ b/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs @@ -15,7 +15,6 @@ namespace Umbraco.Core.Composing.Composers // register others composition.RegisterUnique(factory => factory.GetInstance().Content); - composition.RegisterUnique(factory => factory.GetInstance().Templates); composition.RegisterUnique(factory => factory.GetInstance().RequestHandler); composition.RegisterUnique(factory => factory.GetInstance().Security); diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ITemplatesSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ITemplatesSection.cs deleted file mode 100644 index 67fd58030b..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ITemplatesSection.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface ITemplatesSection : IUmbracoConfigurationSection - { - RenderingEngine DefaultRenderingEngine { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs index 28da03ff2d..33416d38cc 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel; namespace Umbraco.Core.Configuration.UmbracoSettings { @@ -12,8 +11,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings ISecuritySection Security { get; } IRequestHandlerSection RequestHandler { get; } - - ITemplatesSection Templates { get; } ILoggingSection Logging { get; } @@ -22,6 +19,5 @@ namespace Umbraco.Core.Configuration.UmbracoSettings IProvidersSection Providers { get; } IWebRoutingSection WebRouting { get; } - } } diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/TemplatesElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/TemplatesElement.cs deleted file mode 100644 index 8c929b02d8..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/TemplatesElement.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class TemplatesElement : UmbracoConfigurationElement, ITemplatesSection - { - [ConfigurationProperty("defaultRenderingEngine", IsRequired = true)] - internal InnerTextConfigurationElement DefaultRenderingEngine - { - get { return GetOptionalTextElement("defaultRenderingEngine", RenderingEngine.Mvc); } - } - - RenderingEngine ITemplatesSection.DefaultRenderingEngine - { - get { return DefaultRenderingEngine; } - } - - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs index d36410f317..9ed635f6a9 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs @@ -1,11 +1,7 @@ -using System; -using System.ComponentModel; -using System.Configuration; -using System.Linq; +using System.Configuration; namespace Umbraco.Core.Configuration.UmbracoSettings { - public class UmbracoSettingsSection : ConfigurationSection, IUmbracoSettingsSection { [ConfigurationProperty("backOffice")] @@ -32,12 +28,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings get { return (RequestHandlerElement)this["requestHandler"]; } } - [ConfigurationProperty("templates")] - internal TemplatesElement Templates - { - get { return (TemplatesElement)this["templates"]; } - } - [ConfigurationProperty("logging")] internal LoggingElement Logging { @@ -77,11 +67,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings get { return RequestHandler; } } - ITemplatesSection IUmbracoSettingsSection.Templates - { - get { return Templates; } - } - IBackOfficeSection IUmbracoSettingsSection.BackOffice { get { return BackOffice; } @@ -106,6 +91,5 @@ namespace Umbraco.Core.Configuration.UmbracoSettings { get { return WebRouting; } } - } } diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 7fc846319b..63a1259acb 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -19,7 +19,6 @@ namespace Umbraco.Core.IO private ShadowWrapper _partialViewsFileSystem; private ShadowWrapper _stylesheetsFileSystem; private ShadowWrapper _scriptsFileSystem; - private ShadowWrapper _masterPagesFileSystem; private ShadowWrapper _mvcViewsFileSystem; // well-known file systems lazy initialization @@ -102,16 +101,6 @@ namespace Umbraco.Core.IO } } - /// - public IFileSystem MasterPagesFileSystem - { - get - { - if (Volatile.Read(ref _wkfsInitialized) == false) EnsureWellKnownFileSystems(); - return _masterPagesFileSystem; - } - } - /// public IFileSystem MvcViewsFileSystem { @@ -135,14 +124,12 @@ namespace Umbraco.Core.IO var partialViewsFileSystem = new PhysicalFileSystem(SystemDirectories.PartialViews); var stylesheetsFileSystem = new PhysicalFileSystem(SystemDirectories.Css); var scriptsFileSystem = new PhysicalFileSystem(SystemDirectories.Scripts); - var masterPagesFileSystem = new PhysicalFileSystem(SystemDirectories.Masterpages); var mvcViewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews); _macroPartialFileSystem = new ShadowWrapper(macroPartialFileSystem, "Views/MacroPartials", IsScoped); _partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, "Views/Partials", IsScoped); _stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, "css", IsScoped); _scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, "scripts", IsScoped); - _masterPagesFileSystem = new ShadowWrapper(masterPagesFileSystem, "masterpages", IsScoped); _mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, "Views", IsScoped); // fixme locking? @@ -150,7 +137,6 @@ namespace Umbraco.Core.IO _shadowWrappers.Add(_partialViewsFileSystem); _shadowWrappers.Add(_stylesheetsFileSystem); _shadowWrappers.Add(_scriptsFileSystem); - _shadowWrappers.Add(_masterPagesFileSystem); _shadowWrappers.Add(_mvcViewsFileSystem); return null; diff --git a/src/Umbraco.Core/IO/IFileSystems.cs b/src/Umbraco.Core/IO/IFileSystems.cs index d74ad48145..f7d35058e3 100644 --- a/src/Umbraco.Core/IO/IFileSystems.cs +++ b/src/Umbraco.Core/IO/IFileSystems.cs @@ -25,11 +25,6 @@ /// IFileSystem ScriptsFileSystem { get; } - /// - /// Gets the masterpages filesystem. - /// - IFileSystem MasterPagesFileSystem { get; } - /// /// Gets the MVC views filesystem. /// diff --git a/src/Umbraco.Core/IO/MasterPageHelper.cs b/src/Umbraco.Core/IO/MasterPageHelper.cs deleted file mode 100644 index 049db04b9a..0000000000 --- a/src/Umbraco.Core/IO/MasterPageHelper.cs +++ /dev/null @@ -1,445 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using Umbraco.Core.Models; -using Umbraco.Core.Persistence.Repositories; -using Umbraco.Core.Services; -using Umbraco.Core.Xml; - -namespace Umbraco.Core.IO -{ - internal class MasterPageHelper - { - private readonly IFileSystem _masterPageFileSystem; - internal static readonly string DefaultMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master"; - //private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray(); - - public MasterPageHelper(IFileSystem masterPageFileSystem) - { - if (masterPageFileSystem == null) throw new ArgumentNullException("masterPageFileSystem"); - _masterPageFileSystem = masterPageFileSystem; - } - - public bool MasterPageExists(ITemplate t) - { - return _masterPageFileSystem.FileExists(GetFilePath(t)); - } - - private string GetFilePath(ITemplate t) - { - return GetFilePath(t.Alias); - } - - private string GetFilePath(string alias) - { - return alias + ".master"; - } - - public string CreateMasterPage(ITemplate t, ITemplateRepository templateRepo, bool overWrite = false) - { - string masterpageContent = ""; - - var filePath = GetFilePath(t); - if (_masterPageFileSystem.FileExists(filePath) == false || overWrite) - { - masterpageContent = t.Content.IsNullOrWhiteSpace() ? CreateDefaultMasterPageContent(t, templateRepo) : t.Content; - - var data = Encoding.UTF8.GetBytes(masterpageContent); - var withBom = Encoding.UTF8.GetPreamble().Concat(data).ToArray(); - - using (var ms = new MemoryStream(withBom)) - { - _masterPageFileSystem.AddFile(filePath, ms, true); - } - } - else - { - using (var s = _masterPageFileSystem.OpenFile(filePath)) - using (var tr = new StreamReader(s, Encoding.UTF8)) - { - masterpageContent = tr.ReadToEnd(); - tr.Close(); - } - } - - return masterpageContent; - } - - //internal string GetFileContents(ITemplate t) - //{ - // var masterpageContent = ""; - // if (_masterPageFileSystem.FileExists(GetFilePath(t))) - // { - // using (var s = _masterPageFileSystem.OpenFile(GetFilePath(t))) - // using (var tr = new StreamReader(s)) - // { - // masterpageContent = tr.ReadToEnd(); - // tr.Close(); - // } - // } - - // return masterpageContent; - //} - - public string UpdateMasterPageFile(ITemplate t, string currentAlias, ITemplateRepository templateRepo) - { - var template = UpdateMasterPageContent(t, currentAlias); - UpdateChildTemplates(t, currentAlias, templateRepo); - var filePath = GetFilePath(t); - - var data = Encoding.UTF8.GetBytes(template); - var withBom = Encoding.UTF8.GetPreamble().Concat(data).ToArray(); - - using (var ms = new MemoryStream(withBom)) - { - _masterPageFileSystem.AddFile(filePath, ms, true); - } - return template; - } - - private string CreateDefaultMasterPageContent(ITemplate template, ITemplateRepository templateRepo) - { - var design = new StringBuilder(); - design.Append(GetMasterPageHeader(template) + Environment.NewLine); - - if (template.MasterTemplateAlias.IsNullOrWhiteSpace() == false) - { - var master = templateRepo.Get(template.MasterTemplateAlias); - if (master != null) - { - foreach (var cpId in GetContentPlaceholderIds(master)) - { - design.Append("" + - Environment.NewLine + - Environment.NewLine + - "" + - Environment.NewLine + - Environment.NewLine); - } - - return design.ToString(); - } - } - - design.Append(GetMasterContentElement(template) + Environment.NewLine); - design.Append(template.Content + Environment.NewLine); - design.Append("" + Environment.NewLine); - - return design.ToString(); - } - - public static IEnumerable GetContentPlaceholderIds(ITemplate template) - { - var retVal = new List(); - - var mp = template.Content; - var path = ""; - var r = new Regex(path, RegexOptions.IgnoreCase); - var m = r.Match(mp); - - while (m.Success) - { - var cc = m.Groups[3].Captures; - retVal.AddRange(cc.Cast().Where(c => c.Value != "server").Select(c => c.Value)); - - m = m.NextMatch(); - } - - return retVal; - } - - private static string UpdateMasterPageContent(ITemplate template, string currentAlias) - { - var masterPageContent = template.Content; - - if (string.IsNullOrEmpty(currentAlias) == false && currentAlias != template.Alias) - { - var masterHeader = - masterPageContent.Substring(0, masterPageContent.IndexOf("%>", StringComparison.Ordinal) + 2).Trim( - Environment.NewLine.ToCharArray()); - - // find the masterpagefile attribute - var m = Regex.Matches(masterHeader, "(?\\S*)=\"(?[^\"]*)\"", - RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - - foreach (Match attributeSet in m) - { - if (attributeSet.Groups["attributeName"].Value.ToLower() == "masterpagefile") - { - // validate the masterpagefile - var currentMasterPageFile = attributeSet.Groups["attributeValue"].Value; - var currentMasterTemplateFile = ParentTemplatePath(template); - - if (currentMasterPageFile != currentMasterTemplateFile) - { - masterPageContent = - masterPageContent.Replace( - attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterPageFile + "\"", - attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterTemplateFile + - "\""); - } - } - } - } - - return masterPageContent; - } - - private void UpdateChildTemplates(ITemplate template, string currentAlias, ITemplateRepository templateRepo) - { - //if we have a Old Alias if the alias and therefor the masterpage file name has changed... - //so before we save the new masterfile, we'll clear the old one, so we don't up with - //Unused masterpage files - if (string.IsNullOrEmpty(currentAlias) == false && currentAlias != template.Alias) - { - //Ensure that child templates have the right master masterpage file name - if (template.IsMasterTemplate) - { - var children = templateRepo.GetChildren(template.Id); - foreach (var t in children) - UpdateMasterPageFile(t, null, templateRepo); - } - } - } - - - //private void SaveDesignToFile(ITemplate t, string currentAlias, string design) - //{ - // //kill the old file.. - // if (string.IsNullOrEmpty(currentAlias) == false && currentAlias != t.Alias) - // { - // var oldFile = - // IOHelper.MapPath(SystemDirectories.Masterpages + "/" + currentAlias.Replace(" ", "") + ".master"); - // if (System.IO.File.Exists(oldFile)) - // System.IO.File.Delete(oldFile); - // } - - // // save the file in UTF-8 - // System.IO.File.WriteAllText(GetFilePath(t), design, Encoding.UTF8); - //} - - //internal static void RemoveMasterPageFile(string alias) - //{ - // if (string.IsNullOrWhiteSpace(alias) == false) - // { - // string file = IOHelper.MapPath(SystemDirectories.Masterpages + "/" + alias.Replace(" ", "") + ".master"); - // if (System.IO.File.Exists(file)) - // System.IO.File.Delete(file); - // } - //} - - //internal string SaveTemplateToFile(ITemplate template, string currentAlias, ITemplateRepository templateRepo) - //{ - // var masterPageContent = template.Content; - // if (IsMasterPageSyntax(masterPageContent) == false) - // masterPageContent = ConvertToMasterPageSyntax(template); - - // // Add header to master page if it doesn't exist - // if (masterPageContent.TrimStart().StartsWith("<%@") == false) - // { - // masterPageContent = GetMasterPageHeader(template) + Environment.NewLine + masterPageContent; - // } - // else - // { - // // verify that the masterpage attribute is the same as the masterpage - // var masterHeader = - // masterPageContent.Substring(0, masterPageContent.IndexOf("%>", StringComparison.Ordinal) + 2).Trim(NewLineChars); - - // // find the masterpagefile attribute - // var m = Regex.Matches(masterHeader, "(?\\S*)=\"(?[^\"]*)\"", - // RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - - // foreach (Match attributeSet in m) - // { - // if (attributeSet.Groups["attributeName"].Value.ToLower() == "masterpagefile") - // { - // // validate the masterpagefile - // var currentMasterPageFile = attributeSet.Groups["attributeValue"].Value; - // var currentMasterTemplateFile = ParentTemplatePath(template); - - // if (currentMasterPageFile != currentMasterTemplateFile) - // { - // masterPageContent = - // masterPageContent.Replace( - // attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterPageFile + "\"", - // attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterTemplateFile + - // "\""); - - // } - // } - // } - - // } - - // //we have a Old Alias if the alias and therefor the masterpage file name has changed... - // //so before we save the new masterfile, we'll clear the old one, so we don't up with - // //Unused masterpage files - // if (string.IsNullOrEmpty(currentAlias) == false && currentAlias != template.Alias) - // { - - // //Ensure that child templates have the right master masterpage file name - // if (template.IsMasterTemplate) - // { - // var children = templateRepo.GetChildren(template.Id); - - // foreach (var t in children) - // UpdateMasterPageFile(t, null, templateRepo); - // } - - // //then kill the old file.. - // var oldFile = GetFilePath(currentAlias); - // if (_masterPageFileSystem.FileExists(oldFile)) - // _masterPageFileSystem.DeleteFile(oldFile); - // } - - // // save the file in UTF-8 - // System.IO.File.WriteAllText(GetFilePath(template), masterPageContent, Encoding.UTF8); - - // return masterPageContent; - //} - - //internal static string ConvertToMasterPageSyntax(ITemplate template) - //{ - // string masterPageContent = GetMasterContentElement(template) + Environment.NewLine; - - // masterPageContent += template.Content; - - // // Parse the design for getitems - // masterPageContent = EnsureMasterPageSyntax(template.Alias, masterPageContent); - - // // append ending asp:content element - // masterPageContent += Environment.NewLine + "" + Environment.NewLine; - - // return masterPageContent; - //} - - public static bool IsMasterPageSyntax(string code) - { - return Regex.IsMatch(code, @"<%@\s*Master", RegexOptions.IgnoreCase) || - code.InvariantContains("", ParentTemplatePath(template)) + Environment.NewLine; - } - - private static string ParentTemplatePath(ITemplate template) - { - var masterTemplate = DefaultMasterTemplate; - if (template.MasterTemplateAlias.IsNullOrWhiteSpace() == false) - masterTemplate = SystemDirectories.Masterpages + "/" + template.MasterTemplateAlias + ".master"; - - return masterTemplate; - } - - internal static string GetMasterContentElement(ITemplate template) - { - if (template.MasterTemplateAlias.IsNullOrWhiteSpace() == false) - { - string masterAlias = template.MasterTemplateAlias; - return - String.Format("", masterAlias); - } - else - return - String.Format(""); - - } - - internal static string EnsureMasterPageSyntax(string templateAlias, string masterPageContent) - { - ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true); - ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false); - - // Parse the design for macros - ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true); - ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false); - - // Parse the design for load childs - masterPageContent = masterPageContent.Replace("", CreateDefaultPlaceHolder(templateAlias)) - .Replace("", CreateDefaultPlaceHolder(templateAlias)); - // Parse the design for aspnet forms - GetAspNetMasterPageForm(ref masterPageContent, templateAlias); - masterPageContent = masterPageContent.Replace("", ""); - // Parse the design for aspnet heads - masterPageContent = masterPageContent.Replace("", String.Format("", templateAlias.Replace(" ", ""))); - masterPageContent = masterPageContent.Replace("", ""); - return masterPageContent; - } - - - private static void GetAspNetMasterPageForm(ref string design, string templateAlias) - { - var formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - - if (string.IsNullOrEmpty(formElement.Value) == false) - { - string formReplace = String.Format("
", templateAlias.Replace(" ", "")); - if (formElement.Groups.Count == 0) - { - formReplace += ""; - } - design = design.Replace(formElement.Value, formReplace); - } - } - - private static string CreateDefaultPlaceHolder(string templateAlias) - { - return String.Format("", templateAlias.Replace(" ", "")); - } - - private static void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes) - { - var m = - Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes), - RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - - foreach (Match match in m) - { - GroupCollection groups = match.Groups; - - // generate new element (compensate for a closing trail on single elements ("/")) - string elementAttributes = groups[1].Value; - // test for macro alias - if (elementName == "?UMBRACO_MACRO") - { - var tags = XmlHelper.GetAttributesFromElement(match.Value); - if (tags["macroAlias"] != null) - elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"]) + elementAttributes; - else if (tags["macroalias"] != null) - elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"]) + elementAttributes; - } - string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">"; - if (elementAttributes.EndsWith("/")) - { - elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1); - } - else if (groups[0].Value.StartsWith(""; - - if (checkForQuotes) - { - // if it's inside quotes, we'll change element attribute quotes to single quotes - newElement = newElement.Replace("\"", "'"); - newElement = String.Format("\"{0}\"", newElement); - } - design = design.Replace(match.Value, newElement); - } - } - - private static string GetElementRegExp(string elementName, bool checkForQuotes) - { - if (checkForQuotes) - return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName); - else - return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName); - - } - - } -} diff --git a/src/Umbraco.Core/IO/SystemDirectories.cs b/src/Umbraco.Core/IO/SystemDirectories.cs index 4ea3ed64d5..8bea82ea4a 100644 --- a/src/Umbraco.Core/IO/SystemDirectories.cs +++ b/src/Umbraco.Core/IO/SystemDirectories.cs @@ -18,10 +18,6 @@ namespace Umbraco.Core.IO public static string Install => "~/install"; - //fixme: remove this - [Obsolete("Master pages are obsolete and code should be removed")] - public static string Masterpages => "~/masterpages"; - public static string AppCode => "~/App_Code"; public static string AppPlugins => "~/App_Plugins"; diff --git a/src/Umbraco.Core/Models/ITemplate.cs b/src/Umbraco.Core/Models/ITemplate.cs index 97b9324415..6548a49626 100644 --- a/src/Umbraco.Core/Models/ITemplate.cs +++ b/src/Umbraco.Core/Models/ITemplate.cs @@ -1,11 +1,9 @@ -using System; -using System.Runtime.Serialization; -using Umbraco.Core.Models.Entities; +using Umbraco.Core.Models.Entities; namespace Umbraco.Core.Models { /// - /// Defines a Template File (Masterpage or Mvc View) + /// Defines a Template File (Mvc View) /// public interface ITemplate : IFile, IRememberBeingDirty, ICanBeDirty { diff --git a/src/Umbraco.Core/Packaging/PackageDataInstallation.cs b/src/Umbraco.Core/Packaging/PackageDataInstallation.cs index 2e9fee9595..9bea527b91 100644 --- a/src/Umbraco.Core/Packaging/PackageDataInstallation.cs +++ b/src/Umbraco.Core/Packaging/PackageDataInstallation.cs @@ -1234,10 +1234,7 @@ namespace Umbraco.Core.Packaging var alias = templateElement.Element("Alias").Value; var design = templateElement.Element("Design").Value; var masterElement = templateElement.Element("Master"); - - var isMasterPage = IsMasterPageSyntax(design); - var path = isMasterPage ? MasterpagePath(alias) : ViewPath(alias); - + var existingTemplate = _fileService.GetTemplate(alias) as Template; var template = existingTemplate ?? new Template(templateName, alias); template.Content = design; @@ -1257,23 +1254,11 @@ namespace Umbraco.Core.Packaging return templates; } - - private bool IsMasterPageSyntax(string code) - { - return Regex.IsMatch(code, @"<%@\s*Master", RegexOptions.IgnoreCase) || - code.InvariantContains(" GetDescendants(int masterTemplateId); IEnumerable GetDescendants(string alias); - /// - /// This checks what the default rendering engine is set in config but then also ensures that there isn't already - /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate - /// rendering engine to use. - /// - /// - /// - /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx - /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml - /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. - /// This is mostly related to installing packages since packages install file templates to the file system and then create the - /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. - /// - RenderingEngine DetermineTemplateRenderingEngine(ITemplate template); - /// /// Validates a /// diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs index 19ef303ebe..ac0f4f0bed 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/TemplateRepository.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Text; using NPoco; using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -23,20 +22,14 @@ namespace Umbraco.Core.Persistence.Repositories.Implement ///
internal class TemplateRepository : NPocoRepositoryBase, ITemplateRepository { - private readonly IFileSystem _masterpagesFileSystem; private readonly IFileSystem _viewsFileSystem; - private readonly ITemplatesSection _templateConfig; private readonly ViewHelper _viewHelper; - private readonly MasterPageHelper _masterPageHelper; - public TemplateRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, ITemplatesSection templateConfig, IFileSystems fileSystems) + public TemplateRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger, IFileSystems fileSystems) : base(scopeAccessor, cache, logger) { - _masterpagesFileSystem = fileSystems.MasterPagesFileSystem; _viewsFileSystem = fileSystems.MvcViewsFileSystem; - _templateConfig = templateConfig; _viewHelper = new ViewHelper(_viewsFileSystem); - _masterPageHelper = new MasterPageHelper(_masterpagesFileSystem); } protected override IRepositoryCachePolicy CreateCachePolicy() @@ -255,18 +248,9 @@ namespace Umbraco.Core.Persistence.Repositories.Implement else { // else, create or write template.Content to disk - if (DetermineTemplateRenderingEngine(template) == RenderingEngine.Mvc) - { - content = originalAlias == null - ? _viewHelper.CreateView(template, true) - : _viewHelper.UpdateViewFile(template, originalAlias); - } - else - { - content = originalAlias == null - ? _masterPageHelper.CreateMasterPage(template, this, true) - : _masterPageHelper.UpdateMasterPageFile(template, originalAlias, this); - } + content = originalAlias == null + ? _viewHelper.CreateView(template, true) + : _viewHelper.UpdateViewFile(template, originalAlias); } // once content has been set, "template on disk" are not "on disk" anymore @@ -298,16 +282,8 @@ namespace Umbraco.Core.Persistence.Repositories.Implement Database.Execute(delete, new { id = GetEntityId(entity) }); } - if (DetermineTemplateRenderingEngine(entity) == RenderingEngine.Mvc) - { - var viewName = string.Concat(entity.Alias, ".cshtml"); - _viewsFileSystem.DeleteFile(viewName); - } - else - { - var masterpageName = string.Concat(entity.Alias, ".master"); - _masterpagesFileSystem.DeleteFile(masterpageName); - } + var viewName = string.Concat(entity.Alias, ".cshtml"); + _viewsFileSystem.DeleteFile(viewName); entity.DeleteDate = DateTime.Now; } @@ -388,27 +364,11 @@ namespace Umbraco.Core.Persistence.Repositories.Implement template.VirtualPath = _viewsFileSystem.GetUrl(path); return; } - path = string.Concat(template.Alias, ".master"); - if (_masterpagesFileSystem.FileExists(path)) - { - template.VirtualPath = _masterpagesFileSystem.GetUrl(path); - return; - } } else { // we know the path already - var ext = Path.GetExtension(path); - switch (ext) - { - case ".cshtml": - case ".vbhtml": - template.VirtualPath = _viewsFileSystem.GetUrl(path); - return; - case ".master": - template.VirtualPath = _masterpagesFileSystem.GetUrl(path); - return; - } + template.VirtualPath = _viewsFileSystem.GetUrl(path); } template.VirtualPath = string.Empty; // file not found... @@ -426,25 +386,15 @@ namespace Umbraco.Core.Persistence.Repositories.Implement path = string.Concat(template.Alias, ".vbhtml"); if (_viewsFileSystem.FileExists(path)) return GetFileContent(template, _viewsFileSystem, path, init); - path = string.Concat(template.Alias, ".master"); - if (_masterpagesFileSystem.FileExists(path)) - return GetFileContent(template, _masterpagesFileSystem, path, init); } else { // we know the path already - var ext = Path.GetExtension(path); - switch (ext) - { - case ".cshtml": - case ".vbhtml": - return GetFileContent(template, _viewsFileSystem, path, init); - case ".master": - return GetFileContent(template, _masterpagesFileSystem, path, init); - } + return GetFileContent(template, _viewsFileSystem, path, init); } template.VirtualPath = string.Empty; // file not found... + return string.Empty; } @@ -514,9 +464,6 @@ namespace Umbraco.Core.Persistence.Repositories.Implement case ".vbhtml": fs = _viewsFileSystem; break; - case ".master": - fs = _masterpagesFileSystem; - break; default: throw new Exception("Unsupported extension " + ext + "."); } @@ -625,56 +572,6 @@ namespace Umbraco.Core.Persistence.Repositories.Implement } } - /// - /// This checks what the default rendering engine is set in config but then also ensures that there isn't already - /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate - /// rendering engine to use. - /// - /// - /// - /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx - /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml - /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. - /// This is mostly related to installing packages since packages install file templates to the file system and then create the - /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. - /// - public RenderingEngine DetermineTemplateRenderingEngine(ITemplate template) - { - var engine = _templateConfig.DefaultRenderingEngine; - var viewHelper = new ViewHelper(_viewsFileSystem); - if (viewHelper.ViewExists(template) == false) - { - if (template.Content.IsNullOrWhiteSpace() == false && MasterPageHelper.IsMasterPageSyntax(template.Content)) - { - //there is a design but its definitely a webforms design and we haven't got a MVC view already for it - return RenderingEngine.WebForms; - } - } - - var masterPageHelper = new MasterPageHelper(_masterpagesFileSystem); - - switch (engine) - { - case RenderingEngine.Mvc: - //check if there's a view in ~/masterpages - if (masterPageHelper.MasterPageExists(template) && viewHelper.ViewExists(template) == false) - { - //change this to webforms since there's already a file there for this template alias - engine = RenderingEngine.WebForms; - } - break; - case RenderingEngine.WebForms: - //check if there's a view in ~/views - if (viewHelper.ViewExists(template) && masterPageHelper.MasterPageExists(template) == false) - { - //change this to mvc since there's already a file there for this template alias - engine = RenderingEngine.Mvc; - } - break; - } - return engine; - } - /// /// Validates a /// @@ -689,21 +586,12 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var path = template.VirtualPath; // get valid paths - var validDirs = _templateConfig.DefaultRenderingEngine == RenderingEngine.Mvc - ? new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews } - : new[] { SystemDirectories.Masterpages }; + var validDirs = new[] { SystemDirectories.MvcViews }; // get valid extensions var validExts = new List(); - if (_templateConfig.DefaultRenderingEngine == RenderingEngine.Mvc) - { - validExts.Add("cshtml"); - validExts.Add("vbhtml"); - } - else - { - validExts.Add("master"); - } + validExts.Add("cshtml"); + validExts.Add("vbhtml"); // validate path and extension var validFile = IOHelper.VerifyEditPath(path, validDirs); diff --git a/src/Umbraco.Core/Services/IFileService.cs b/src/Umbraco.Core/Services/IFileService.cs index 76e850beb2..daf5d9b80c 100644 --- a/src/Umbraco.Core/Services/IFileService.cs +++ b/src/Umbraco.Core/Services/IFileService.cs @@ -210,21 +210,6 @@ namespace Umbraco.Core.Services /// Optional id of the user void SaveTemplate(IEnumerable templates, int userId = 0); - /// - /// This checks what the default rendering engine is set in config but then also ensures that there isn't already - /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate - /// rendering engine to use. - /// - /// - /// - /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx - /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml - /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. - /// This is mostly related to installing packages since packages install file templates to the file system and then create the - /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. - /// - RenderingEngine DetermineTemplateRenderingEngine(ITemplate template); - /// /// Gets the content of a template as a stream. /// diff --git a/src/Umbraco.Core/Services/Implement/FileService.cs b/src/Umbraco.Core/Services/Implement/FileService.cs index f15f0d7d47..0c08404ab3 100644 --- a/src/Umbraco.Core/Services/Implement/FileService.cs +++ b/src/Umbraco.Core/Services/Implement/FileService.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -556,27 +555,6 @@ namespace Umbraco.Core.Services.Implement } } - /// - /// This checks what the default rendering engine is set in config but then also ensures that there isn't already - /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate - /// rendering engine to use. - /// - /// - /// - /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx - /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml - /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. - /// This is mostly related to installing packages since packages install file templates to the file system and then create the - /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package. - /// - public RenderingEngine DetermineTemplateRenderingEngine(ITemplate template) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _templateRepository.DetermineTemplateRenderingEngine(template); - } - } - /// /// Deletes a template by its alias /// @@ -1043,7 +1021,7 @@ namespace Umbraco.Core.Services.Implement _auditRepository.Save(new AuditItem(objectId, type, userId, entityType)); } - //TODO Method to change name and/or alias of view/masterpage template + //TODO Method to change name and/or alias of view template #region Event Handlers diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 13f1ff2025..81c5af104f 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -291,7 +291,6 @@ - @@ -304,7 +303,6 @@ - @@ -631,7 +629,6 @@ - diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementDefaultTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementDefaultTests.cs deleted file mode 100644 index 4f7e8c1800..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementDefaultTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class TemplateElementDefaultTests : TemplateElementTests - { - protected override bool TestingDefaults - { - get { return true; } - } - } -} diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementTests.cs deleted file mode 100644 index a2edf94ab5..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/TemplateElementTests.cs +++ /dev/null @@ -1,16 +0,0 @@ -using NUnit.Framework; -using Umbraco.Core; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class TemplateElementTests : UmbracoSettingsTests - { - [Test] - public void DefaultRenderingEngine() - { - Assert.IsTrue(SettingsSection.Templates.DefaultRenderingEngine == RenderingEngine.Mvc); - } - - } -} diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config index 4c64485503..dd44e23328 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config @@ -145,10 +145,6 @@ - - Mvc - - false true diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config index 21dfa1f19e..bee7133051 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config @@ -37,11 +37,6 @@ - - - Mvc - - diff --git a/src/Umbraco.Tests/IO/IoHelperTests.cs b/src/Umbraco.Tests/IO/IoHelperTests.cs index b2ef5e4d31..b0e59cbb55 100644 --- a/src/Umbraco.Tests/IO/IoHelperTests.cs +++ b/src/Umbraco.Tests/IO/IoHelperTests.cs @@ -37,7 +37,6 @@ namespace Umbraco.Tests.IO Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Css, true), IOHelper.MapPath(SystemDirectories.Css, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Data, true), IOHelper.MapPath(SystemDirectories.Data, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Install, true), IOHelper.MapPath(SystemDirectories.Install, false)); - Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Masterpages, true), IOHelper.MapPath(SystemDirectories.Masterpages, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Media, true), IOHelper.MapPath(SystemDirectories.Media, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Packages, true), IOHelper.MapPath(SystemDirectories.Packages, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Preview, true), IOHelper.MapPath(SystemDirectories.Preview, false)); diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs index aeaf76967f..f3af1cf73f 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -7,12 +7,9 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; using Umbraco.Core.Models; -using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; -using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.TestHelpers; @@ -36,7 +33,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeAccessor scopeAccessor, out ContentTypeRepository contentTypeRepository) { var cacheHelper = CacheHelper.Disabled; - var templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(scopeAccessor, cacheHelper, Logger); contentTypeRepository = new ContentTypeRepository(scopeAccessor, cacheHelper, Logger, templateRepository); var languageRepository = new LanguageRepository(scopeAccessor, cacheHelper, Logger); @@ -46,7 +43,7 @@ namespace Umbraco.Tests.Persistence.Repositories private ContentTypeRepository CreateRepository(IScopeAccessor scopeAccessor) { - var templateRepository = new TemplateRepository(scopeAccessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(scopeAccessor, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var contentTypeRepository = new ContentTypeRepository(scopeAccessor, CacheHelper.Disabled, Logger, templateRepository); return contentTypeRepository; } @@ -71,7 +68,7 @@ namespace Umbraco.Tests.Persistence.Repositories var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var templateRepo = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepo = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var repository = CreateRepository((IScopeAccessor) provider); var templates = new[] { diff --git a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs index c1fa5381ff..2619827705 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DocumentRepositoryTest.cs @@ -64,7 +64,7 @@ namespace Umbraco.Tests.Persistence.Repositories { cacheHelper = cacheHelper ?? CacheHelper; - templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + templateRepository = new TemplateRepository(scopeAccessor, cacheHelper, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(scopeAccessor, cacheHelper, Logger); contentTypeRepository = new ContentTypeRepository(scopeAccessor, cacheHelper, Logger, templateRepository); var languageRepository = new LanguageRepository(scopeAccessor, cacheHelper, Logger); diff --git a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs index a5402f964e..5511114d3e 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DomainRepositoryTest.cs @@ -4,9 +4,7 @@ using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; using Umbraco.Core.Models; -using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.TestHelpers; @@ -22,7 +20,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DomainRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository, out DocumentRepository documentRepository, out LanguageRepository languageRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger); contentTypeRepository = new ContentTypeRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger, templateRepository); languageRepository = new LanguageRepository(accessor, Core.Cache.CacheHelper.Disabled, Logger); diff --git a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs index e76d794e69..23d95163d0 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/PublicAccessRepositoryTest.cs @@ -4,10 +4,8 @@ using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Tests.TestHelpers; @@ -307,7 +305,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, CacheHelper, Logger); contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper, Logger, templateRepository); var languageRepository = new LanguageRepository(accessor, CacheHelper, Logger); diff --git a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs index 78eb736007..03295ea599 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TagRepositoryTest.cs @@ -953,7 +953,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateContentRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, CacheHelper.Disabled, Logger); contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper.Disabled, Logger, templateRepository); var languageRepository = new LanguageRepository(accessor, CacheHelper.Disabled, Logger); diff --git a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs index f4bed68315..7d4b413a11 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs @@ -25,11 +25,9 @@ namespace Umbraco.Tests.Persistence.Repositories { private IFileSystems _fileSystems; - private ITemplateRepository CreateRepository(IScopeProvider provider, ITemplatesSection templatesSection = null) + private ITemplateRepository CreateRepository(IScopeProvider provider) { - return new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, - templatesSection ?? Mock.Of(t => t.DefaultRenderingEngine == RenderingEngine.Mvc), - _fileSystems); + return new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, _fileSystems); } public override void SetUp() @@ -37,8 +35,6 @@ namespace Umbraco.Tests.Persistence.Repositories base.SetUp(); _fileSystems = Mock.Of(); - var masterPageFileSystem = new PhysicalFileSystem(SystemDirectories.Masterpages); - Mock.Get(_fileSystems).Setup(x => x.MasterPagesFileSystem).Returns(masterPageFileSystem); var viewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews); Mock.Get(_fileSystems).Setup(x => x.MvcViewsFileSystem).Returns(viewsFileSystem); } @@ -56,77 +52,6 @@ namespace Umbraco.Tests.Persistence.Repositories } } - [Test] - public void Can_Perform_Add_MasterPage_Detect_Content() - { - // Arrange - using (ScopeProvider.CreateScope()) - { - var repository = CreateRepository(ScopeProvider); - - // Act - var template = new Template("test", "test") - { - Content = @"<%@ Master Language=""C#"" %>" - }; - repository.Save(template); - - //Assert - Assert.That(repository.Get("test"), Is.Not.Null); - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.True); - } - } - - [Test] - public void Can_Perform_Add_MasterPage_With_Default_Content() - { - // Arrange - using (ScopeProvider.CreateScope()) - { - var repository = CreateRepository(ScopeProvider, Mock.Of(x => x.DefaultRenderingEngine == RenderingEngine.WebForms)); - - // Act - var template = new Template("test", "test"); - repository.Save(template); - - //Assert - Assert.That(repository.Get("test"), Is.Not.Null); - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.True); - Assert.AreEqual(@"<%@ Master Language=""C#"" MasterPageFile=""~/umbraco/masterpages/default.master"" AutoEventWireup=""true"" %> - - - - -".StripWhitespace(), template.Content.StripWhitespace()); - } - } - - [Test] - public void Can_Perform_Add_MasterPage_With_Default_Content_With_Parent() - { - // Arrange - using (ScopeProvider.CreateScope()) - { - var repository = CreateRepository(ScopeProvider, Mock.Of(x => x.DefaultRenderingEngine == RenderingEngine.WebForms)); - - //NOTE: This has to be persisted first - var template = new Template("test", "test"); - repository.Save(template); - - // Act - var template2 = new Template("test2", "test2"); - template2.SetMasterTemplate(template); - repository.Save(template2); - - //Assert - Assert.That(repository.Get("test2"), Is.Not.Null); - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test2.master"), Is.True); - Assert.AreEqual(@"<%@ Master Language=""C#"" MasterPageFile=""~/masterpages/test.master"" AutoEventWireup=""true"" %> - -".StripWhitespace(), template2.Content.StripWhitespace()); - } - } - [Test] public void Can_Perform_Add_View() { @@ -253,32 +178,6 @@ namespace Umbraco.Tests.Persistence.Repositories } } - [Test] - public void Can_Perform_Update_MasterPage() - { - // Arrange - using (ScopeProvider.CreateScope()) - { - var repository = CreateRepository(ScopeProvider); - - // Act - var template = new Template("test", "test") - { - Content = @"<%@ Master Language=""C#"" %>" - }; - repository.Save(template); - - template.Content = @"<%@ Master Language=""VB"" %>"; - repository.Save(template); - - var updated = repository.Get("test"); - - // Assert - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.True); - Assert.That(updated.Content, Is.EqualTo(@"<%@ Master Language=""VB"" %>")); - } - } - [Test] public void Can_Perform_Update_View() { @@ -305,31 +204,6 @@ namespace Umbraco.Tests.Persistence.Repositories } } - [Test] - public void Can_Perform_Delete_MasterPage() - { - // Arrange - using (ScopeProvider.CreateScope()) - { - var repository = CreateRepository(ScopeProvider); - - var template = new Template("test", "test") - { - Content = @"<%@ Master Language=""C#"" %>" - }; - repository.Save(template); - - // Act - var templates = repository.Get("test"); - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.True); - repository.Delete(templates); - - // Assert - Assert.IsNull(repository.Get("test")); - Assert.That(_fileSystems.MasterPagesFileSystem.FileExists("test.master"), Is.False); - } - } - [Test] public void Can_Perform_Delete_View() { @@ -651,11 +525,6 @@ namespace Umbraco.Tests.Persistence.Repositories _fileSystems = null; //Delete all files - var fsMaster = new PhysicalFileSystem(SystemDirectories.Masterpages); - var masterPages = fsMaster.GetFiles("", "*.master"); - foreach (var file in masterPages) - fsMaster.DeleteFile(file); - var fsViews = new PhysicalFileSystem(SystemDirectories.MvcViews); var views = fsViews.GetFiles("", "*.cshtml"); foreach (var file in views) diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs index 847972cc50..ba2a7de859 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserRepositoryTest.cs @@ -41,7 +41,7 @@ namespace Umbraco.Tests.Persistence.Repositories private DocumentRepository CreateContentRepository(IScopeProvider provider, out IContentTypeRepository contentTypeRepository, out ITemplateRepository templateRepository) { var accessor = (IScopeAccessor) provider; - templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + templateRepository = new TemplateRepository(accessor, CacheHelper, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, CacheHelper, Logger); contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper, Logger, templateRepository); var languageRepository = new LanguageRepository(accessor, CacheHelper, Logger); diff --git a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs index 3aefa88a50..fff88d7531 100644 --- a/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs +++ b/src/Umbraco.Tests/Services/ContentServicePerformanceTest.cs @@ -163,7 +163,7 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); @@ -196,7 +196,7 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); @@ -227,7 +227,7 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); @@ -261,7 +261,7 @@ namespace Umbraco.Tests.Services var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { - var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var tRepository = new TemplateRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepo = new TagRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); var ctRepository = new ContentTypeRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger, tRepository); var languageRepository = new LanguageRepository((IScopeAccessor) provider, CacheHelper.Disabled, Logger); diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index 0f48a9c99a..a9e48988f4 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -3037,7 +3037,7 @@ namespace Umbraco.Tests.Services private DocumentRepository CreateRepository(IScopeProvider provider, out ContentTypeRepository contentTypeRepository) { var accessor = (IScopeAccessor) provider; - var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, Mock.Of(), TestObjects.GetFileSystemsMock()); + var templateRepository = new TemplateRepository(accessor, CacheHelper.Disabled, Logger, TestObjects.GetFileSystemsMock()); var tagRepository = new TagRepository(accessor, CacheHelper.Disabled, Logger); contentTypeRepository = new ContentTypeRepository(accessor, CacheHelper.Disabled, Logger, templateRepository); var languageRepository = new LanguageRepository(accessor, CacheHelper.Disabled, Logger); diff --git a/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs b/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs deleted file mode 100644 index a8344893c0..0000000000 --- a/src/Umbraco.Tests/Templates/MasterPageHelperTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -using NUnit.Framework; -using Umbraco.Core.IO; - -namespace Umbraco.Tests.Templates -{ - [TestFixture] - public class MasterPageHelperTests - { - - [TestCase(@"<%@ master language=""C#"" masterpagefile=""~/masterpages/umbMaster.master"" autoeventwireup=""true"" %>")] - [TestCase(@"<%@ Master language=""C#"" masterpagefile=""~/masterpages/umbMaster.master"" autoeventwireup=""true"" %>")] - [TestCase(@"<%@Master language=""C#"" masterpagefile=""~/masterpages/umbMaster.master"" autoeventwireup=""true"" %>")] - [TestCase(@"<%@ Master language=""C#"" masterpagefile=""~/masterpages/umbMaster.master"" autoeventwireup=""true"" %>")] - [TestCase(@"<%@master language=""C#"" masterpagefile=""~/masterpages/umbMaster.master"" autoeventwireup=""true"" %>")] - public void IsMasterPageSyntax(string design) - { - Assert.IsTrue(MasterPageHelper.IsMasterPageSyntax(design)); - } - - } -} diff --git a/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs b/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs deleted file mode 100644 index 795d79ced1..0000000000 --- a/src/Umbraco.Tests/Templates/TemplateRepositoryTests.cs +++ /dev/null @@ -1,121 +0,0 @@ -using Moq; -using NUnit.Framework; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.Scoping; -using Umbraco.Tests.TestHelpers; - -namespace Umbraco.Tests.Templates -{ - [TestFixture] - public class TemplateRepositoryTests - { - private readonly Mock _cacheMock = new Mock(); - private readonly Mock _templateConfigMock = new Mock(); - private readonly IFileSystems _fileSystems = Mock.Of(); - private TemplateRepository _templateRepository; - - private readonly TestObjects _testObjects = new TestObjects(null); - - [SetUp] - public void Setup() - { - var logger = Mock.Of(); - - var accessorMock = new Mock(); - var scopeMock = new Mock(); - var database = _testObjects.GetUmbracoSqlCeDatabase(logger); - scopeMock.Setup(x => x.Database).Returns(database); - accessorMock.Setup(x => x.AmbientScope).Returns(scopeMock.Object); - - var mvcFs = Mock.Of(); - var masterFs = Mock.Of(); - Mock.Get(_fileSystems).Setup(x => x.MvcViewsFileSystem).Returns(mvcFs); - Mock.Get(_fileSystems).Setup(x => x.MasterPagesFileSystem).Returns(masterFs); - - _templateRepository = new TemplateRepository(accessorMock.Object, _cacheMock.Object, logger, _templateConfigMock.Object, _fileSystems); - } - - [Test] - public void DetermineTemplateRenderingEngine_Returns_MVC_When_ViewFile_Exists_And_Content_Has_Webform_Markup() - { - // Project in MVC mode - _templateConfigMock.Setup(x => x.DefaultRenderingEngine).Returns(RenderingEngine.Mvc); - - // Template has masterpage content - var templateMock = new Mock(); - templateMock.Setup(x => x.Alias).Returns("Something"); - templateMock.Setup(x => x.Content).Returns(""); - - // but MVC View already exists - Mock.Get(_fileSystems.MvcViewsFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(true); - - var res = _templateRepository.DetermineTemplateRenderingEngine(templateMock.Object); - Assert.AreEqual(RenderingEngine.Mvc, res); - } - - [Test] - public void DetermineTemplateRenderingEngine_Returns_WebForms_When_ViewFile_Doesnt_Exist_And_Content_Has_Webform_Markup() - { - // Project in MVC mode - _templateConfigMock.Setup(x => x.DefaultRenderingEngine).Returns(RenderingEngine.Mvc); - - // Template has masterpage content - var templateMock = new Mock(); - templateMock.Setup(x => x.Alias).Returns("Something"); - templateMock.Setup(x => x.Content).Returns(""); - - // MVC View doesn't exist - Mock.Get(_fileSystems.MvcViewsFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(false); - - var res = _templateRepository.DetermineTemplateRenderingEngine(templateMock.Object); - Assert.AreEqual(RenderingEngine.WebForms, res); - } - - [Test] - public void DetermineTemplateRenderingEngine_Returns_WebForms_When_MasterPage_Exists_And_In_Mvc_Mode() - { - // Project in MVC mode - _templateConfigMock.Setup(x => x.DefaultRenderingEngine).Returns(RenderingEngine.Mvc); - - var templateMock = new Mock(); - templateMock.Setup(x => x.Alias).Returns("Something"); - - // but masterpage already exists - Mock.Get(_fileSystems.MvcViewsFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(false); - Mock.Get(_fileSystems.MasterPagesFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(true); - - var res = _templateRepository.DetermineTemplateRenderingEngine(templateMock.Object); - Assert.AreEqual(RenderingEngine.WebForms, res); - } - - [Test] - public void DetermineTemplateRenderingEngine_Returns_Mvc_When_ViewPage_Exists_And_In_Webforms_Mode() - { - // Project in WebForms mode - _templateConfigMock.Setup(x => x.DefaultRenderingEngine).Returns(RenderingEngine.WebForms); - - var templateMock = new Mock(); - templateMock.Setup(x => x.Alias).Returns("Something"); - - // but MVC View already exists - Mock.Get(_fileSystems.MvcViewsFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(true); - Mock.Get(_fileSystems.MasterPagesFileSystem) - .Setup(x => x.FileExists(It.IsAny())).Returns(false); - - var res = _templateRepository.DetermineTemplateRenderingEngine(templateMock.Object); - Assert.AreEqual(RenderingEngine.Mvc, res); - } - - } -} diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index ea40ed9c84..cfd935cd82 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -38,7 +38,6 @@ namespace Umbraco.Tests.TestHelpers var content = new Mock(); var security = new Mock(); var requestHandler = new Mock(); - var templates = new Mock(); var logging = new Mock(); var tasks = new Mock(); var providers = new Mock(); @@ -47,7 +46,6 @@ namespace Umbraco.Tests.TestHelpers settings.Setup(x => x.Content).Returns(content.Object); settings.Setup(x => x.Security).Returns(security.Object); settings.Setup(x => x.RequestHandler).Returns(requestHandler.Object); - settings.Setup(x => x.Templates).Returns(templates.Object); settings.Setup(x => x.Logging).Returns(logging.Object); settings.Setup(x => x.ScheduledTasks).Returns(tasks.Object); settings.Setup(x => x.Providers).Returns(providers.Object); @@ -61,7 +59,6 @@ namespace Umbraco.Tests.TestHelpers settings.Setup(x => x.RequestHandler.UseDomainPrefixes).Returns(false); settings.Setup(x => x.RequestHandler.CharCollection).Returns(RequestHandlerElement.GetDefaultCharReplacements()); settings.Setup(x => x.WebRouting.UrlProviderMode).Returns("AutoLegacy"); - settings.Setup(x => x.Templates.DefaultRenderingEngine).Returns(RenderingEngine.Mvc); settings.Setup(x => x.Providers.DefaultBackOfficeUserProvider).Returns("UsersMembershipProvider"); return settings.Object; diff --git a/src/Umbraco.Tests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs index 1fe814e4c6..b6f597bf46 100644 --- a/src/Umbraco.Tests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -55,12 +55,12 @@ namespace Umbraco.Tests.TestHelpers public static void InitializeContentDirectories() { - CreateDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media, SystemDirectories.AppPlugins }); + CreateDirectories(new[] { SystemDirectories.MvcViews, SystemDirectories.Media, SystemDirectories.AppPlugins }); } public static void CleanContentDirectories() { - CleanDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media }); + CleanDirectories(new[] { SystemDirectories.MvcViews, SystemDirectories.Media }); } public static void CreateDirectories(string[] directories) @@ -77,7 +77,6 @@ namespace Umbraco.Tests.TestHelpers { var preserves = new Dictionary { - { SystemDirectories.Masterpages, new[] {"dummy.txt"} }, { SystemDirectories.MvcViews, new[] {"dummy.txt"} } }; foreach (var directory in directories) diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 8c230f98d0..563d81da05 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -145,8 +145,7 @@ namespace Umbraco.Tests.TestHelpers public IFileSystems GetFileSystemsMock() { var fileSystems = Mock.Of(); - - MockFs(fileSystems, x => x.MasterPagesFileSystem); + MockFs(fileSystems, x => x.MacroPartialsFileSystem); MockFs(fileSystems, x => x.MvcViewsFileSystem); MockFs(fileSystems, x => x.PartialViewsFileSystem); diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index a79531af74..304a13f20c 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -304,7 +304,6 @@ namespace Umbraco.Tests.Testing // register basic stuff that might need to be there for some container resolvers to work Composition.RegisterUnique(factory => factory.GetInstance().Content); - Composition.RegisterUnique(factory => factory.GetInstance().Templates); Composition.RegisterUnique(factory => factory.GetInstance().WebRouting); Composition.RegisterUnique(factory => ExamineManager.Instance); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index e49ba250fa..c22b765169 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -305,8 +305,6 @@ - - @@ -354,7 +352,6 @@ - @@ -453,7 +450,6 @@ - diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config index fb8ff63ab0..7299a397bc 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config @@ -85,11 +85,6 @@ - - - Mvc - - diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.config b/src/Umbraco.Web.UI/config/umbracoSettings.config index c3e146d6ce..4de0a04735 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.config @@ -162,11 +162,6 @@ - - - Mvc - - + + Add between {{model.config.minNumber}} and {{model.config.maxNumber}} items + + You can only have {{model.config.maxNumber}} items selected + + + + + + Add {{model.config.minNumber - renderModel.length}} item(s) + + You can only have {{model.config.maxNumber}} items selected + + + + + + Add up to {{model.config.maxNumber}} items + + You can only have {{model.config.maxNumber}} items selected + + + + + + Add at least {{model.config.minNumber}} item(s) + + + + + + + + +
+ You need to add at least {{model.config.minNumber}} items +
+ +
+ You can only have {{model.config.maxNumber}} items selected +
+ + + + diff --git a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs index 65d366e2ad..fe85263f3b 100644 --- a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs @@ -117,6 +117,7 @@ namespace Umbraco.Web.Cache LegacyMediaPickerPropertyConverter.ClearCaches(); SliderValueConverter.ClearCaches(); MediaPickerPropertyConverter.ClearCaches(); + MultiUrlPickerPropertyConverter.ClearCaches(); base.Refresh(jsonPayload); diff --git a/src/Umbraco.Web/Models/ContentEditing/LinkDisplay.cs b/src/Umbraco.Web/Models/ContentEditing/LinkDisplay.cs new file mode 100644 index 0000000000..857ae2c318 --- /dev/null +++ b/src/Umbraco.Web/Models/ContentEditing/LinkDisplay.cs @@ -0,0 +1,36 @@ +using System.Runtime.Serialization; +using Umbraco.Core; + +namespace Umbraco.Web.Models.ContentEditing +{ + [DataContract(Name = "link", Namespace = "")] + internal class LinkDisplay + { + [DataMember(Name = "icon")] + public string Icon { get; set; } + + [DataMember(Name = "isMedia")] + public bool IsMedia { get; set; } + + [DataMember(Name = "name")] + public string Name { get; set; } + + [DataMember(Name = "published")] + public bool Published { get; set; } + + [DataMember(Name = "queryString")] + public string QueryString { get; set; } + + [DataMember(Name = "target")] + public string Target { get; set; } + + [DataMember(Name = "trashed")] + public bool Trashed { get; set; } + + [DataMember(Name = "udi")] + public GuidUdi Udi { get; set; } + + [DataMember(Name = "url")] + public string Url { get; set; } + } +} diff --git a/src/Umbraco.Web/Models/Link.cs b/src/Umbraco.Web/Models/Link.cs new file mode 100644 index 0000000000..74ad4ad2af --- /dev/null +++ b/src/Umbraco.Web/Models/Link.cs @@ -0,0 +1,13 @@ +using Umbraco.Core; + +namespace Umbraco.Web.Models +{ + public class Link + { + public string Name { get; set; } + public string Target { get; set; } + public LinkType Type { get; set; } + public Udi Udi { get; set; } + public string Url { get; set; } + } +} diff --git a/src/Umbraco.Web/Models/LinkType.cs b/src/Umbraco.Web/Models/LinkType.cs new file mode 100644 index 0000000000..3db3165d7f --- /dev/null +++ b/src/Umbraco.Web/Models/LinkType.cs @@ -0,0 +1,9 @@ +namespace Umbraco.Web.Models +{ + public enum LinkType + { + Content, + Media, + External + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/MultiUrlPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MultiUrlPickerPropertyEditor.cs new file mode 100644 index 0000000000..84523f05c4 --- /dev/null +++ b/src/Umbraco.Web/PropertyEditors/MultiUrlPickerPropertyEditor.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Umbraco.Core; +using Umbraco.Core.Logging; +using Umbraco.Core.Models; +using Umbraco.Core.Models.Editors; +using Umbraco.Core.Models.EntityBase; +using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Services; +using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Routing; + +namespace Umbraco.Web.PropertyEditors +{ + [PropertyEditor(Constants.PropertyEditors.MultiUrlPickerAlias, "Multi Url Picker", PropertyEditorValueTypes.Json, "multiurlpicker", Group = "pickers", Icon = "icon-link", IsParameterEditor = true)] + public class MultiUrlPickerPropertyEditor : PropertyEditor + { + protected override PreValueEditor CreatePreValueEditor() + { + return new MultiUrlPickerPreValueEditor(); + } + + protected override PropertyValueEditor CreateValueEditor() + { + return new MultiUrlPickerPropertyValueEditor(base.CreateValueEditor()); + } + + private class MultiUrlPickerPreValueEditor : PreValueEditor + { + public MultiUrlPickerPreValueEditor() + { + Fields.Add(new PreValueField + { + Key = "minNumber", + View = "number", + Name = "Minimum number of items" + }); + Fields.Add(new PreValueField + { + Key = "maxNumber", + View = "number", + Name = "Maximum number of items" + }); + } + } + + private class MultiUrlPickerPropertyValueEditor : PropertyValueEditorWrapper + { + public MultiUrlPickerPropertyValueEditor(PropertyValueEditor wrapped) : base(wrapped) + { + } + + public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService) + { + if (property.Value == null) + return Enumerable.Empty(); + + var value = property.Value.ToString(); + + if (string.IsNullOrEmpty(value)) + return Enumerable.Empty(); + + try + { + var umbHelper = new UmbracoHelper(UmbracoContext.Current); + var services = ApplicationContext.Current.Services; + var entityService = services.EntityService; + var contentTypeService = services.ContentTypeService; + string deletedLocalization = null; + string recycleBinLocalization = null; + + var dtos = JsonConvert.DeserializeObject>(value); + + var documentLinks = dtos.FindAll(link => + link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document + ); + + var mediaLinks = dtos.FindAll(link => + link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media + ); + + var entities = new List(); + if (documentLinks.Count > 0) + { + entities.AddRange( + entityService.GetAll(UmbracoObjectTypes.Document, + documentLinks.Select(link => link.Udi.Guid).ToArray()) + ); + } + + if (mediaLinks.Count > 0) + { + entities.AddRange( + entityService.GetAll(UmbracoObjectTypes.Media, + mediaLinks.Select(link => link.Udi.Guid).ToArray()) + ); + } + + var links = new List(); + foreach (var dto in dtos) + { + var link = new LinkDisplay + { + Icon = "icon-link", + IsMedia = false, + Name = dto.Name, + Published = true, + QueryString = dto.QueryString, + Target = dto.Target, + Trashed = false, + Udi = dto.Udi, + Url = dto.Url, + }; + + links.Add(link); + + if (dto.Udi == null) + continue; + + var entity = entities.Find(e => e.Key == dto.Udi.Guid); + if (entity == null) + { + if (deletedLocalization == null) + deletedLocalization = services.TextService.Localize("general/deleted"); + + link.Published = false; + link.Trashed = true; + link.Url = deletedLocalization; + } + else + { + var entityType = + Equals(entity.AdditionalData["NodeObjectTypeId"], Constants.ObjectTypes.MediaGuid) + ? Constants.UdiEntityType.Media + : Constants.UdiEntityType.Document; + + var udi = new GuidUdi(entityType, entity.Key); + + var contentTypeAlias = (string)entity.AdditionalData["ContentTypeAlias"]; + if (entity.Trashed) + { + if (recycleBinLocalization == null) + recycleBinLocalization = services.TextService.Localize("general/recycleBin"); + + link.Trashed = true; + link.Url = recycleBinLocalization; + } + + if (udi.EntityType == Constants.UdiEntityType.Document) + { + var contentType = contentTypeService.GetContentType(contentTypeAlias); + + if (contentType == null) + continue; + + link.Icon = contentType.Icon; + link.Published = Equals(entity.AdditionalData["IsPublished"], true); + + if (link.Trashed == false) + link.Url = umbHelper.Url(entity.Id, UrlProviderMode.Relative); + } + else + { + link.IsMedia = true; + + var mediaType = contentTypeService.GetMediaType(contentTypeAlias); + + if (mediaType == null) + continue; + + link.Icon = mediaType.Icon; + + if (link.Trashed) + continue; + + var media = umbHelper.TypedMedia(entity.Id); + if (media != null) + link.Url = media.Url; + } + } + } + return links; + } + catch (Exception ex) + { + ApplicationContext.Current.ProfilingLogger.Logger.Error($"Error getting links.\r\n{property.Value}", ex); + } + + return base.ConvertDbToEditor(property, propertyType, dataTypeService); + } + + public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) + { + if (editorValue.Value == null) + return null; + + var value = editorValue.Value.ToString(); + + if (string.IsNullOrEmpty(value)) + return null; + + try + { + return JsonConvert.SerializeObject( + from link in JsonConvert.DeserializeObject>(value) + select new LinkDto + { + Name = link.Name, + QueryString = link.QueryString, + Target = link.Target, + Udi = link.Udi, + Url = link.Udi == null ? link.Url : null, // only save the url for external links + }, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore + }); + } + catch (Exception ex) + { + ApplicationContext.Current.ProfilingLogger.Logger.Error($"Error saving links.\r\n{editorValue.Value}", ex); + } + return base.ConvertEditorToDb(editorValue, currentValue); + } + } + + [DataContract] + internal class LinkDto + { + [DataMember(Name = "name")] + public string Name { get; set; } + + [DataMember(Name = "queryString")] + public string QueryString { get; set; } + + [DataMember(Name = "target")] + public string Target { get; set; } + + [DataMember(Name = "udi")] + public GuidUdi Udi { get; set; } + + [DataMember(Name = "url")] + public string Url { get; set; } + } + } +} diff --git a/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs index 3aaf191fd2..541dccaa4e 100644 --- a/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs @@ -1,10 +1,13 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { - [PropertyEditor(Constants.PropertyEditors.RelatedLinks2Alias, "Related links", "relatedlinks", ValueType = PropertyEditorValueTypes.Json, Icon = "icon-thumbnail-list", Group = "pickers")] + // TODO: Remove in V8 + [Obsolete("This editor is obsolete, use MultiUrlPickerPropertyEditor instead")] + [PropertyEditor(Constants.PropertyEditors.RelatedLinks2Alias, "Related links", "relatedlinks", ValueType = PropertyEditorValueTypes.Json, Icon = "icon-thumbnail-list", Group = "pickers", IsDeprecated = true)] public class RelatedLinks2PropertyEditor : PropertyEditor { public RelatedLinks2PropertyEditor() @@ -33,4 +36,4 @@ namespace Umbraco.Web.PropertyEditors public int Maximum { get; set; } } } -} \ No newline at end of file +} diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiUrlPickerPropertyConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiUrlPickerPropertyConverter.cs new file mode 100644 index 0000000000..397448983a --- /dev/null +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiUrlPickerPropertyConverter.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json.Linq; +using Umbraco.Core; +using Umbraco.Core.Logging; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.PropertyEditors; +using Umbraco.Core.PropertyEditors.ValueConverters; +using Umbraco.Core.Services; +using Umbraco.Web.Models; + +namespace Umbraco.Web.PropertyEditors.ValueConverters +{ + [DefaultPropertyValueConverter(typeof(JsonValueConverter))] + public class MultiUrlPickerPropertyConverter : PropertyValueConverterBase, IPropertyValueConverterMeta + { + private readonly IDataTypeService _dataTypeService; + + public MultiUrlPickerPropertyConverter(IDataTypeService dataTypeService) + { + if (dataTypeService == null) throw new ArgumentNullException("dataTypeService"); + _dataTypeService = dataTypeService; + } + + //TODO: Remove this ctor in v8 since the other one will use IoC + public MultiUrlPickerPropertyConverter() : this(ApplicationContext.Current.Services.DataTypeService) + { + } + + public override bool IsConverter(PublishedPropertyType propertyType) + { + return propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiUrlPickerAlias); + } + + public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) + { + if (source == null) + return null; + + if (source.ToString().Trim().StartsWith("[") == false) + return null; + + try + { + return JArray.Parse(source.ToString()); + } + catch (Exception ex) + { + LogHelper.Error("Error parsing JSON", ex); + } + return null; + } + + public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) + { + var isMultiple = IsMultipleDataType(propertyType.DataTypeId, out var maxNumber); + if (source == null) + return isMultiple + ? Enumerable.Empty() + : null; + + //TODO: Inject an UmbracoHelper and create a GetUmbracoHelper method based on either injected or singleton + if (UmbracoContext.Current == null) + return source; + + var umbHelper = new UmbracoHelper(UmbracoContext.Current); + + var links = new List(); + var dtos = ((JArray) source).ToObject>(); + + foreach (var dto in dtos) + { + var type = LinkType.External; + var url = dto.Url; + if (dto.Udi != null) + { + type = dto.Udi.EntityType == Constants.UdiEntityType.Media + ? LinkType.Media + : LinkType.Content; + + if (type == LinkType.Media) + { + var media = umbHelper.TypedMedia(dto.Udi); + if (media == null) + continue; + url = media.Url; + } + else + { + var content = umbHelper.TypedContent(dto.Udi); + if (content == null) + continue; + url = content.Url; + } + } + + var link = new Link + { + Name = dto.Name, + Target = dto.Target, + Type = type, + Udi = dto.Udi, + Url = url + dto.QueryString, + }; + + links.Add(link); + } + + if (isMultiple == false) + return links.FirstOrDefault(); + if (maxNumber > 0) + return links.Take(maxNumber); + + return links; + } + + public Type GetPropertyValueType(PublishedPropertyType propertyType) + { + return IsMultipleDataType(propertyType.DataTypeId, out var maxNumber) + ? typeof(IEnumerable) + : typeof(Link); + } + + public PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue) + { + switch (cacheValue) + { + case PropertyCacheValue.Source: + return PropertyCacheLevel.Content; + case PropertyCacheValue.Object: + case PropertyCacheValue.XPath: + return PropertyCacheLevel.ContentCache; + } + + return PropertyCacheLevel.None; + } + + private bool IsMultipleDataType(int dataTypeId, out int maxNumber) + { + // GetPreValuesCollectionByDataTypeId is cached at repository level; + // still, the collection is deep-cloned so this is kinda expensive, + // better to cache here + trigger refresh in DataTypeCacheRefresher + + maxNumber = Storages.GetOrAdd(dataTypeId, id => + { + var preValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(id).PreValuesAsDictionary; + + return preValues.TryGetValue("maxNumber", out var maxNumberPreValue) + ? maxNumberPreValue.Value.TryConvertTo().Result + : 0; + }); + + return maxNumber != 1; + } + + private static readonly ConcurrentDictionary Storages = new ConcurrentDictionary(); + + internal static void ClearCaches() + { + Storages.Clear(); + } + } +} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index e021de0011..1b668b06c8 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -419,6 +419,7 @@ + @@ -444,6 +445,8 @@ + + @@ -485,6 +488,7 @@ + @@ -499,6 +503,7 @@ + From d6855d18f967092dec5583169c535dece072bab4 Mon Sep 17 00:00:00 2001 From: Bjarne Fyrstenborg Date: Sun, 20 Jan 2019 21:19:06 +0100 Subject: [PATCH 66/70] v8: Nicer delete language confirm (#4108) --- .../src/less/components/html/umb-alert.less | 12 +++- .../src/less/utilities/_spacing.less | 13 ++-- .../src/views/languages/overlays/delete.html | 9 +++ .../views/languages/overview.controller.js | 53 ++++++++++------ .../src/views/languages/overview.html | 61 +++++++++---------- .../listview/overlays/delete.html | 4 +- .../listview/overlays/listviewpublish.html | 5 +- .../listview/overlays/listviewunpublish.html | 5 +- src/Umbraco.Web.UI/Umbraco/config/lang/da.xml | 14 +++++ src/Umbraco.Web.UI/Umbraco/config/lang/en.xml | 4 +- .../Umbraco/config/lang/en_us.xml | 1 + 11 files changed, 116 insertions(+), 65 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/src/views/languages/overlays/delete.html diff --git a/src/Umbraco.Web.UI.Client/src/less/components/html/umb-alert.less b/src/Umbraco.Web.UI.Client/src/less/components/html/umb-alert.less index ef8834f767..c9aff190ce 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/html/umb-alert.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/html/umb-alert.less @@ -8,4 +8,14 @@ .umb-alert--info { background-color: @turquoise-washed; border: 1px solid @turquoise; -} \ No newline at end of file +} + +.umb-alert--warning { + background-color: @yellow-washed; + border: 1px solid @yellow; +} + +.umb-alert--danger { + background-color: @red-washed; + border: 1px solid @red; +} diff --git a/src/Umbraco.Web.UI.Client/src/less/utilities/_spacing.less b/src/Umbraco.Web.UI.Client/src/less/utilities/_spacing.less index 64d86d7b6f..69bbeef0af 100644 --- a/src/Umbraco.Web.UI.Client/src/less/utilities/_spacing.less +++ b/src/Umbraco.Web.UI.Client/src/less/utilities/_spacing.less @@ -1,7 +1,5 @@ /* - Spacing - */ @spacing-none: 0; @@ -37,13 +35,11 @@ 7 = 7th step in spacing scale */ - .m-center { margin-left: auto; margin-right: auto; } - .mt0 { margin-top: @spacing-none; } .mt1 { margin-top: @spacing-extra-small; } .mt2 { margin-top: @spacing-small; } @@ -52,3 +48,12 @@ .mt5 { margin-top: @spacing-extra-large; } .mt6 { margin-top: @spacing-extra-extra-large; } .mt7 { margin-top: @spacing-extra-extra-extra-large; } + +.mb0 { margin-bottom: @spacing-none; } +.mb1 { margin-bottom: @spacing-extra-small; } +.mb2 { margin-bottom: @spacing-small; } +.mb3 { margin-bottom: @spacing-medium; } +.mb4 { margin-bottom: @spacing-large; } +.mb5 { margin-bottom: @spacing-extra-large; } +.mb6 { margin-bottom: @spacing-extra-extra-large; } +.mb7 { margin-bottom: @spacing-extra-extra-extra-large; } diff --git a/src/Umbraco.Web.UI.Client/src/views/languages/overlays/delete.html b/src/Umbraco.Web.UI.Client/src/views/languages/overlays/delete.html new file mode 100644 index 0000000000..59221fcea8 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/views/languages/overlays/delete.html @@ -0,0 +1,9 @@ +
+ +
+ This will delete the language {{model.language.name}} [{{model.language.culture}}]. +
+ + ? + +
diff --git a/src/Umbraco.Web.UI.Client/src/views/languages/overview.controller.js b/src/Umbraco.Web.UI.Client/src/views/languages/overview.controller.js index a5c446dfb5..c1972ec067 100644 --- a/src/Umbraco.Web.UI.Client/src/views/languages/overview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/languages/overview.controller.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function LanguagesOverviewController($location, $timeout, navigationService, notificationsService, localizationService, languageResource, eventsService) { + function LanguagesOverviewController($location, $timeout, navigationService, localizationService, languageResource, eventsService, overlayService) { var vm = this; @@ -65,30 +65,47 @@ } function deleteLanguage(language, event) { - var confirmed = confirm("Are you sure you want to delete " + language.name + "?"); - if(confirmed) { - language.deleteButtonState = "busy"; - languageResource.deleteById(language.id).then(function () { + const dialog = { + view: "views/languages/overlays/delete.html", + language: language, + submitButtonLabelKey: "contentTypeEditor_yesDelete", + submit: function (model) { + performDelete(model.language); + overlayService.close(); + }, + close: function () { + overlayService.close(); + } + }; - // emit event - var args = { language: language }; - eventsService.emit("editors.languages.languageDeleted", args); + localizationService.localize("general_delete").then(value => { + dialog.title = value; + overlayService.open(dialog); + }); - // remove from list - var index = vm.languages.indexOf(language); - vm.languages.splice(index, 1); - - }, function (err) { - language.deleteButtonState = "error"; - - }); - - } event.preventDefault() event.stopPropagation(); } + function performDelete(language) { + language.deleteButtonState = "busy"; + + languageResource.deleteById(language.id).then(function () { + + // emit event + var args = { language: language }; + eventsService.emit("editors.languages.languageDeleted", args); + + // remove from list + var index = vm.languages.indexOf(language); + vm.languages.splice(index, 1); + + }, function (err) { + language.deleteButtonState = "error"; + }); + } + init(); } diff --git a/src/Umbraco.Web.UI.Client/src/views/languages/overview.html b/src/Umbraco.Web.UI.Client/src/views/languages/overview.html index c55ce83417..15a9c84367 100644 --- a/src/Umbraco.Web.UI.Client/src/views/languages/overview.html +++ b/src/Umbraco.Web.UI.Client/src/views/languages/overview.html @@ -2,43 +2,41 @@ - + - + - + - + - + - - + + - + diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/delete.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/delete.html index 6ae3eba521..9b10b1d8b4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/delete.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/delete.html @@ -1,6 +1,6 @@
-
+
This will delete the node and all its languages. If you only want to delete one language go and unpublish it instead. @@ -8,4 +8,4 @@ ? -
\ No newline at end of file +
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewpublish.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewpublish.html index 0e2ced411c..8354b323fa 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewpublish.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewpublish.html @@ -6,7 +6,7 @@
-
+

@@ -16,7 +16,7 @@
-
+
- \ No newline at end of file diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewunpublish.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewunpublish.html index 03f91b1ad6..5cc46c5ce5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewunpublish.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/overlays/listviewunpublish.html @@ -8,13 +8,13 @@
-
+

-
+
- \ No newline at end of file diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml index b10f3d0be0..a257fb41d5 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml @@ -354,6 +354,7 @@ Indsæt link Indsæt makro Indsæt tabel + Dette vil slette sproget Sidst redigeret Link Internt link: @@ -407,6 +408,7 @@ konto Vælg editor Vælg snippet + Dette vil slette noden og alle dets sprog. Hvis du kun vil slette et sprog, så afpublicér det i stedet. Vis på medlemsprofil fane har ingen sorteringsrækkefølge + + Tilføj sprog + Påkrævet sprog + Egenskaber på dette sprog skal være udfyldt før noden kan blive udgivet. + Standard sprog + Et Umbraco site kan kun have et standard sprog. + Ved at skifte standardsprog kan resultere i standard indhold mangler. + Fallsback til + Ingen fallback sprog + For at tillade flersproget indhold til at falde tilbage på et andet sprog, hvis det ikke er tilgængelig i det anmodet sprog, vælg det her. + Fallback sprog + Alternativt felt Alternativ tekst diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index 99a35a5e3b..42a2c4c844 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -371,6 +371,7 @@ Insert link Click to add a Macro Insert table + This will delete the language Last Edited Link Internal link: @@ -429,6 +430,7 @@ account Select editor Select snippet + This will delete the node and all its languages. If you only want to delete one language go and unpublish it instead. Hide History Icon - Id + Id Import Info Inner margin diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml index 47f293c2a9..be33ee853a 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -399,6 +399,7 @@ Insert link Click to add a Macro Insert table + This will delete the language Last Edited Link Internal link: From a502be606ba331f6e32761eae9d14a981ed1c75b Mon Sep 17 00:00:00 2001 From: Bjarne Fyrstenborg Date: Sun, 20 Jan 2019 21:27:32 +0100 Subject: [PATCH 67/70] v8: Fix package localization (#4159) --- .../src/views/packages/edit.controller.js | 16 ++- .../src/views/packages/edit.html | 2 - .../src/views/packages/options.html | 2 +- .../src/views/packages/overview.controller.js | 119 +++++++++++------- .../src/views/packages/views/created.html | 8 +- .../views/packages/views/install-local.html | 3 - .../src/views/users/overview.controller.js | 3 +- src/Umbraco.Web.UI/Umbraco/config/lang/da.xml | 9 +- src/Umbraco.Web.UI/Umbraco/config/lang/en.xml | 13 +- .../Umbraco/config/lang/en_us.xml | 16 ++- 10 files changed, 120 insertions(+), 71 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index 0a44192041..282fd0472c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function EditController($scope, $location, $routeParams, umbRequestHelper, entityResource, packageResource, editorService, formHelper) { + function EditController($scope, $location, $routeParams, umbRequestHelper, entityResource, packageResource, editorService, formHelper, localizationService) { const vm = this; @@ -23,18 +23,23 @@ vm.removePackageView = removePackageView; vm.downloadFile = downloadFile; + vm.buttonLabel = ""; + const packageId = $routeParams.id; const create = $routeParams.create; function onInit() { - if(create) { + if (create) { //pre populate package with some values packageResource.getEmpty().then(scaffold => { vm.package = scaffold; vm.loading = false; }); - vm.buttonLabel = "Create"; + + localizationService.localize("general_create").then(function(value) { + vm.buttonLabel = value; + }); } else { // load package packageResource.getCreatedById(packageId).then(createdPackage => { @@ -49,7 +54,10 @@ } }); - vm.buttonLabel = "Save"; + + localizationService.localize("buttons_save").then(function (value) { + vm.buttonLabel = value; + }); } // get all doc types diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html index 5ad5ac2522..4c32e7e10c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.html @@ -323,8 +323,6 @@ disabled="vm.loading"> - - diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/options.html b/src/Umbraco.Web.UI.Client/src/views/packages/options.html index d75604d094..f34ac77ac2 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/options.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/options.html @@ -19,7 +19,7 @@

- This package has no configuration view + This package has no configuration view

+ label="Create package" + label-key="packager_createPackage"> @@ -24,7 +25,7 @@
{{ createdPackage.name }}
- {{ createdPackage.version }} | {{ createdPackage.url }}| {{ createdPackage.author }} + {{ createdPackage.version }} | {{ createdPackage.url }} | {{ createdPackage.author }}
@@ -34,7 +35,6 @@ button-style="danger" size="xxs" label-key="general_delete" - add-ellipsis="true" action="vm.deleteCreatedPackage($event, $index, createdPackage)"> @@ -45,7 +45,7 @@ - No packages have been created yet + No packages have been created yet
\ No newline at end of file diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.html b/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.html index b657c42877..6d95bcafa7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.html +++ b/src/Umbraco.Web.UI.Client/src/views/packages/views/install-local.html @@ -41,7 +41,6 @@
-

Upload package

Install a local package by selecting it from your machine. Only install packages from sources you know and trust. @@ -167,8 +166,6 @@

{{vm.installState.status}}

- -
diff --git a/src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js index 49e8007d8c..80e2322f6b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/overview.controller.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function UsersOverviewController($scope, $location, $timeout, navigationService, localizationService) { + function UsersOverviewController($scope, $location, localizationService) { var vm = this; var usersUri = $location.search().subview; @@ -24,7 +24,6 @@ loadNavigation(); setPageName(); - } function loadNavigation() { diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml index a257fb41d5..0742541484 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/da.xml @@ -804,6 +804,8 @@ Mange hilsner fra Umbraco robotten Notificeringer + Oprettet + Opret pakke Vælg pakken fra din computer. Umbraco pakker er oftest en ".zip" fil Slip her for at uploade eller klik her for at vælge pakkefil @@ -815,8 +817,12 @@ Mange hilsner fra Umbraco robotten Jeg accepterer betingelser for anvendelse Installér pakke - Afslut + Installeret Installeret pakker + Installér lokal + Afslut + Denne pakke har ingen konfigurationsvisning + Der er ikke blevet oprettet nogle pakker endnu Du har ingen pakker installeret 'Pakker' øverst til højre på din skærm]]> Søg efter pakker @@ -953,6 +959,7 @@ Mange hilsner fra Umbraco robotten Umbraco konfigurationsguide Mediearkiv Medlemmer + Pakker Nyhedsbreve Indstillinger Statistik diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index 42a2c4c844..a057bb060f 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -1049,6 +1049,8 @@ To manage your website, simply open the Umbraco back office and start adding con Notifications + Created + Create package button and locating the package. Umbraco packages usually have a ".umb" or ".zip" extension. @@ -1063,8 +1065,12 @@ To manage your website, simply open the Umbraco back office and start adding con I accept terms of use Install package - Finish + Installed Installed packages + Install local + Finish + This package has no configuration view + No packages have been created yet You don’t have any packages installed 'Packages' icon in the top right of your screen]]> Search for packages @@ -1212,16 +1218,17 @@ To manage your website, simply open the Umbraco back office and start adding con Content Courier Developer + Forms + Help Umbraco Configuration Wizard Media Members Newsletters + Packages Settings Statistics Translation Users - Help - Forms The best Umbraco video tutorials diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml index be33ee853a..8ce9282d71 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -606,7 +606,7 @@ Hide History Icon - Id + Id Import Info Inner margin @@ -657,7 +657,7 @@ Permissions Scheduled Publishing Search - Sorry, we can not find what you are looking for. + Sorry, we can not find what you are looking for. No items have been added Server Settings @@ -1075,6 +1075,8 @@ To manage your website, simply open the Umbraco back office and start adding con Notifications + Created + Create package button and locating the package. Umbraco packages usually have a ".umb" or ".zip" extension. @@ -1089,8 +1091,12 @@ To manage your website, simply open the Umbraco back office and start adding con I accept terms of use Install package - Finish + Installed Installed packages + Install local + Finish + This package has no configuration view + No packages have been created yet You don’t have any packages installed 'Packages' icon in the top right of your screen]]> Search for packages @@ -1239,13 +1245,13 @@ To manage your website, simply open the Umbraco back office and start adding con Content - Packages + Forms Media Members + Packages Settings Translation Users - Forms The best Umbraco video tutorials From d5c6e0c6e7fa9a85af51f1e99b99c9ccd114a2d5 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Mon, 21 Jan 2019 09:10:08 +0100 Subject: [PATCH 68/70] - Saving paramters --- src/Umbraco.Core/Collections/ObservableDictionary.cs | 12 ++++++++++++ src/Umbraco.Web/Editors/MacrosController.cs | 3 ++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Core/Collections/ObservableDictionary.cs b/src/Umbraco.Core/Collections/ObservableDictionary.cs index 6518533476..40269aa4eb 100644 --- a/src/Umbraco.Core/Collections/ObservableDictionary.cs +++ b/src/Umbraco.Core/Collections/ObservableDictionary.cs @@ -125,6 +125,18 @@ namespace Umbraco.Core.Collections } + public void ReplaceAll(IEnumerable values) + { + if (values == null) throw new ArgumentNullException(nameof(values)); + + Clear(); + + foreach (var value in values) + { + Add(value); + } + } + public bool Remove(TKey key) { if (!Indecies.ContainsKey(key)) return false; diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 933de89635..5ff2f7bf34 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -149,6 +149,7 @@ macro.UseInEditor = macroDisplay.UseInEditor; macro.MacroSource = macroDisplay.View; macro.MacroType = MacroTypes.PartialView; + macro.Properties.ReplaceAll(macroDisplay.Parameters.Select((x,i) => new MacroProperty(x.Key, x.Label, i, x.Editor))); try { @@ -218,7 +219,7 @@ } /// - /// Finds all the macro partials + /// Finds all the macro partials /// /// /// The . From 3fd8c6354275115405528f9a1261be7376b92c88 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Mon, 21 Jan 2019 09:10:39 +0100 Subject: [PATCH 69/70] - Show Ids - Hide "Render in rich text editor and the grid" if "Use in rich text editor and the grid" is false --- .../src/views/macros/views/settings.html | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html index ba5b324837..59ccf2bc7e 100644 --- a/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html +++ b/src/Umbraco.Web.UI.Client/src/views/macros/views/settings.html @@ -1,8 +1,17 @@  + + + + {{model.macro.id}}
+ {{model.macro.key}} +
+
+
+ - @@ -13,9 +22,9 @@ - - - + + + From 2744afab001214c71eac37daa15a6273e05a02df Mon Sep 17 00:00:00 2001 From: Matthew-Wise Date: Mon, 21 Jan 2019 08:49:00 +0000 Subject: [PATCH 70/70] Disable LastPass on page heading (#4153) --- .../util/noPasswordManager.directive.js | 24 +++++++++++++++++++ .../components/editor/umb-editor-header.html | 4 +++- .../views/components/umb-locked-field.html | 1 + 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/Umbraco.Web.UI.Client/src/common/directives/util/noPasswordManager.directive.js diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/util/noPasswordManager.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/util/noPasswordManager.directive.js new file mode 100644 index 0000000000..190c504aa6 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/common/directives/util/noPasswordManager.directive.js @@ -0,0 +1,24 @@ +/** +* @ngdoc directive +* @name umbraco.directives.directive:no-password-manager +* @attribte +* @function +* @description +* Added attributes to block password manager elements should as LastPass + +* @example +* +* +* +* +* +**/ +angular.module("umbraco.directives") + .directive('noPasswordManager', function () { + return { + restrict: 'A', + link: function (scope, element, attrs) { + element.attr("data-lpignore", "true"); + } + } + }); diff --git a/src/Umbraco.Web.UI.Client/src/views/components/editor/umb-editor-header.html b/src/Umbraco.Web.UI.Client/src/views/components/editor/umb-editor-header.html index 3754b66c53..25925f42ed 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/editor/umb-editor-header.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/editor/umb-editor-header.html @@ -23,7 +23,8 @@
- {{ name }}
LanguageLanguage ISODefaultMandatoryDefaultMandatory Fallback
{{ language.name }} @@ -47,17 +45,15 @@ {{ language.culture }} - + - + @@ -65,14 +61,13 @@ (none) - +