From bfca8c555e328bd93ca36f9f77aa37adecaba342 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 19:12:42 +0200 Subject: [PATCH 01/58] Removes Package repository config setting and related unnecessary code --- .../tools/umbracoSettings.config.install.xdt | 2 + .../UmbracoSettings/IRepositoriesSection.cs | 10 - .../UmbracoSettings/IRepository.cs | 14 - .../IUmbracoSettingsSection.cs | 6 +- .../UmbracoSettings/RepositoriesCollection.cs | 36 - .../UmbracoSettings/RepositoriesElement.cs | 23 - .../RepositoryConfigExtensions.cs | 19 - .../UmbracoSettings/RepositoryElement.cs | 53 - .../UmbracoSettings/UmbracoSettingsSection.cs | 50 +- .../Constants-PackageRepository.cs | 15 + src/Umbraco.Core/Services/PackagingService.cs | 6 +- src/Umbraco.Core/Umbraco.Core.csproj | 9 +- .../PackageRepositoriesElementDefaultTests.cs | 23 - .../PackageRepositoriesElementTests.cs | 27 - .../TestHelpers/SettingsForTests.cs | 2 - src/Umbraco.Tests/Umbraco.Tests.csproj | 2 - src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 4 +- .../config/umbracoSettings.config | 8 +- .../umbraco/developer/Packages/installer.aspx | 346 --- .../Editors/BackOfficeServerVariables.cs | 3 +- .../Editors/PackageInstallController.cs | 2 - src/Umbraco.Web/Umbraco.Web.csproj | 4 - .../umbraco/Trees/loadPackager.cs | 87 +- .../umbraco/Trees/loadPackages.cs | 139 -- .../umbraco/create/CreatedPackageTasks.cs | 2 +- .../developer/Packages/installer.aspx.cs | 835 ------- .../Packager/Repositories/Repository.cs | 299 --- .../Repositories/RepositoryWebservice.cs | 2002 ----------------- src/umbraco.cms/umbraco.cms.csproj | 2 - 29 files changed, 48 insertions(+), 3982 deletions(-) delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/IRepositoriesSection.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/IRepository.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesCollection.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesElement.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryConfigExtensions.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryElement.cs create mode 100644 src/Umbraco.Core/Constants-PackageRepository.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementDefaultTests.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementTests.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Packages/installer.aspx delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackages.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installer.aspx.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs delete mode 100644 src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs diff --git a/build/NuSpecs/tools/umbracoSettings.config.install.xdt b/build/NuSpecs/tools/umbracoSettings.config.install.xdt index a4725b835f..295fc0ba57 100644 --- a/build/NuSpecs/tools/umbracoSettings.config.install.xdt +++ b/build/NuSpecs/tools/umbracoSettings.config.install.xdt @@ -5,4 +5,6 @@ + + \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IRepositoriesSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IRepositoriesSection.cs deleted file mode 100644 index 063acbe1cf..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IRepositoriesSection.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - - public interface IRepositoriesSection : IUmbracoConfigurationSection - { - IEnumerable Repositories { get; } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IRepository.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IRepository.cs deleted file mode 100644 index 7559f090c0..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IRepository.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IRepository - { - string Name { get; } - Guid Id { get; } - string RepositoryUrl { get; } - string WebServiceUrl { get; } - bool HasCustomWebServiceUrl { get; } - string RestApiUrl { get; } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs index 7174f7762f..ee6d172b08 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs @@ -24,9 +24,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings IScheduledTasksSection ScheduledTasks { get; } IDistributedCallSection DistributedCall { get; } - - IRepositoriesSection PackageRepositories { get; } - + IProvidersSection Providers { get; } [EditorBrowsable(EditorBrowsableState.Never)] @@ -37,4 +35,4 @@ namespace Umbraco.Core.Configuration.UmbracoSettings IScriptingSection Scripting { get; } } -} \ No newline at end of file +} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesCollection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesCollection.cs deleted file mode 100644 index 994c808703..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesCollection.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class RepositoriesCollection : ConfigurationElementCollection, IEnumerable - { - internal void Add(RepositoryElement item) - { - BaseAdd(item); - } - - protected override ConfigurationElement CreateNewElement() - { - return new RepositoryElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((RepositoryElement)element).Id; - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as IRepository; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesElement.cs deleted file mode 100644 index e2c3ba3036..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoriesElement.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class RepositoriesElement : ConfigurationElement, IRepositoriesSection - { - - [ConfigurationCollection(typeof(RepositoriesCollection), AddItemName = "repository")] - [ConfigurationProperty("", IsDefaultCollection = true)] - internal RepositoriesCollection Repositories - { - get { return (RepositoriesCollection) base[""]; } - set { base[""] = value; } - } - - IEnumerable IRepositoriesSection.Repositories - { - get { return Repositories; } - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryConfigExtensions.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryConfigExtensions.cs deleted file mode 100644 index e2c4283dc6..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryConfigExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Linq; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public static class RepositoryConfigExtensions - { - //Our package repo - private static readonly Guid RepoGuid = new Guid("65194810-1f85-11dd-bd0b-0800200c9a66"); - - public static IRepository GetDefault(this IRepositoriesSection repos) - { - var found = repos.Repositories.FirstOrDefault(x => x.Id == RepoGuid); - if (found == null) - throw new InvalidOperationException("No default package repository found with id " + RepoGuid); - return found; - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryElement.cs deleted file mode 100644 index a249be2ee3..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/RepositoryElement.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class RepositoryElement : ConfigurationElement, IRepository - { - [ConfigurationProperty("name", IsRequired = true)] - public string Name - { - get { return (string)base["name"]; } - set { base["name"] = value; } - } - - [ConfigurationProperty("guid", IsRequired = true)] - public Guid Id - { - get { return (Guid)base["guid"]; } - set { base["guid"] = value; } - } - - [ConfigurationProperty("repositoryurl", DefaultValue = "http://packages.umbraco.org")] - public string RepositoryUrl - { - get { return (string)base["repositoryurl"]; } - set { base["repositoryurl"] = value; } - } - - [ConfigurationProperty("webserviceurl", DefaultValue = "/umbraco/webservices/api/repository.asmx")] - public string WebServiceUrl - { - get { return (string)base["webserviceurl"]; } - set { base["webserviceurl"] = value; } - } - - public bool HasCustomWebServiceUrl - { - get - { - var prop = Properties["webserviceurl"]; - return (string) prop.DefaultValue != (string) this[prop]; - } - } - - [ConfigurationProperty("restapiurl", DefaultValue = "https://our.umbraco.org/webapi/packages/v1")] - public string RestApiUrl - { - get { return (string)base["restapiurl"]; } - set { base["restapiurl"] = value; } - } - - } -} \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs index 9ec1b36053..ef40c3f324 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs @@ -67,50 +67,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings { get { return (DistributedCallElement)this["distributedCall"]; } } - - private RepositoriesElement _defaultRepositories; - - [ConfigurationProperty("repositories")] - internal RepositoriesElement PackageRepositories - { - get - { - - if (_defaultRepositories != null) - { - return _defaultRepositories; - } - - //here we need to check if this element is defined, if it is not then we'll setup the defaults - var prop = Properties["repositories"]; - var repos = this[prop] as ConfigurationElement; - if (repos != null && repos.ElementInformation.IsPresent == false) - { - var collection = new RepositoriesCollection - { - new RepositoryElement() {Name = "Umbraco package Repository", Id = new Guid("65194810-1f85-11dd-bd0b-0800200c9a66")} - }; - - - _defaultRepositories = new RepositoriesElement() - { - Repositories = collection - }; - - return _defaultRepositories; - } - - //now we need to ensure there is *always* our umbraco repo! its hard coded in the codebase! - var reposElement = (RepositoriesElement)base["repositories"]; - if (reposElement.Repositories.All(x => x.Id != new Guid("65194810-1f85-11dd-bd0b-0800200c9a66"))) - { - reposElement.Repositories.Add(new RepositoryElement() { Name = "Umbraco package Repository", Id = new Guid("65194810-1f85-11dd-bd0b-0800200c9a66") }); - } - - return reposElement; - } - } - + [ConfigurationProperty("providers")] internal ProvidersElement Providers { @@ -185,11 +142,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings get { return DistributedCall; } } - IRepositoriesSection IUmbracoSettingsSection.PackageRepositories - { - get { return PackageRepositories; } - } - IProvidersSection IUmbracoSettingsSection.Providers { get { return Providers; } diff --git a/src/Umbraco.Core/Constants-PackageRepository.cs b/src/Umbraco.Core/Constants-PackageRepository.cs new file mode 100644 index 0000000000..bdcb86932b --- /dev/null +++ b/src/Umbraco.Core/Constants-PackageRepository.cs @@ -0,0 +1,15 @@ +namespace Umbraco.Core +{ + public static partial class Constants + { + /// + /// Defines the constants used for the Umbraco package repository + /// + public static class PackageRepository + { + public const string RestApiBaseUrl = "https://our.umbraco.org/webapi/packages/v1"; + public const string DefaultRepositoryName = "Umbraco package Repository"; + public const string DefaultRepositoryId = "65194810-1f85-11dd-bd0b-0800200c9a66"; + } + } +} diff --git a/src/Umbraco.Core/Services/PackagingService.cs b/src/Umbraco.Core/Services/PackagingService.cs index f9b8ab5e9a..dcef982992 100644 --- a/src/Umbraco.Core/Services/PackagingService.cs +++ b/src/Umbraco.Core/Services/PackagingService.cs @@ -89,13 +89,11 @@ namespace Umbraco.Core.Services /// public string FetchPackageFile(Guid packageId, Version umbracoVersion, int userId) { - var packageRepo = UmbracoConfig.For.UmbracoSettings().PackageRepositories.GetDefault(); - using (var httpClient = new HttpClient()) using (var uow = _uowProvider.GetUnitOfWork()) { //includeHidden = true because we don't care if it's hidden we want to get the file regardless - var url = string.Format("{0}/{1}?version={2}&includeHidden=true&asFile=true", packageRepo.RestApiUrl, packageId, umbracoVersion.ToString(3)); + var url = string.Format("{0}/{1}?version={2}&includeHidden=true&asFile=true", Constants.PackageRepository.RestApiBaseUrl, packageId, umbracoVersion.ToString(3)); byte[] bytes; try { @@ -124,7 +122,7 @@ namespace Umbraco.Core.Services } } - Audit(uow, AuditType.PackagerInstall, string.Format("Package {0} fetched from {1}", packageId, packageRepo.Id), userId, -1); + Audit(uow, AuditType.PackagerInstall, string.Format("Package {0} fetched from {1}", packageId, Constants.PackageRepository.DefaultRepositoryId), userId, -1); return null; } } diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index c1a102e954..f12ff4f4f1 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -281,8 +281,6 @@ - - @@ -308,10 +306,6 @@ - - - - @@ -1606,6 +1600,9 @@ Constants.cs + + Constants.cs + Constants.cs diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementDefaultTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementDefaultTests.cs deleted file mode 100644 index b10a35f5f4..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementDefaultTests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Linq; -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class PackageRepositoriesElementDefaultTests : PackageRepositoriesElementTests - { - protected override bool TestingDefaults - { - get { return true; } - } - - [Test] - public override void Repositories() - { - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.Count() == 1); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).Id == Guid.Parse("65194810-1f85-11dd-bd0b-0800200c9a66")); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).Name == "Umbraco package Repository"); - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementTests.cs deleted file mode 100644 index cb82978c72..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/PackageRepositoriesElementTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Linq; -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class PackageRepositoriesElementTests : UmbracoSettingsTests - { - [Test] - public virtual void Repositories() - { - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.Count() == 2); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).Id == Guid.Parse("65194810-1f85-11dd-bd0b-0800200c9a66")); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).Name == "Umbraco package Repository"); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).HasCustomWebServiceUrl == false); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).WebServiceUrl == "/umbraco/webservices/api/repository.asmx"); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).RepositoryUrl == "http://packages.umbraco.org"); - - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(1).Id == Guid.Parse("163245E0-CD22-44B6-841A-1B9B9D2E955F")); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(1).Name == "Test Repo"); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(1).HasCustomWebServiceUrl == false); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).WebServiceUrl == "/umbraco/webservices/api/repository.asmx"); - Assert.IsTrue(SettingsSection.PackageRepositories.Repositories.ElementAt(0).RepositoryUrl == "http://packages.umbraco.org"); - } - } -} \ No newline at end of file diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index d67a44de46..6c54bc335c 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -38,7 +38,6 @@ namespace Umbraco.Tests.TestHelpers var logging = new Mock(); var tasks = new Mock(); var distCall = new Mock(); - var repos = new Mock(); var providers = new Mock(); var routing = new Mock(); @@ -53,7 +52,6 @@ namespace Umbraco.Tests.TestHelpers settings.Setup(x => x.Logging).Returns(logging.Object); settings.Setup(x => x.ScheduledTasks).Returns(tasks.Object); settings.Setup(x => x.DistributedCall).Returns(distCall.Object); - settings.Setup(x => x.PackageRepositories).Returns(repos.Object); settings.Setup(x => x.Providers).Returns(providers.Object); settings.Setup(x => x.WebRouting).Returns(routing.Object); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 0d707bc56b..d2d94bc694 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -361,8 +361,6 @@ - - diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 1577442ede..fa3ff3ca72 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -49,6 +49,7 @@ true true + bin\ @@ -492,7 +493,6 @@ - @@ -1037,7 +1037,7 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" True 7110 / - http://localhost:7110 + http://localhost:3110 False False diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.config b/src/Umbraco.Web.UI/config/umbracoSettings.config index 31c32d4d19..658eb07f0a 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.config @@ -279,12 +279,6 @@ - - - - - - @@ -326,4 +320,4 @@ umbracoApplicationUrl=""> - \ No newline at end of file + diff --git a/src/Umbraco.Web.UI/umbraco/developer/Packages/installer.aspx b/src/Umbraco.Web.UI/umbraco/developer/Packages/installer.aspx deleted file mode 100644 index a7fe23357d..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Packages/installer.aspx +++ /dev/null @@ -1,346 +0,0 @@ -<%@ Page Language="c#" MasterPageFile="../../masterpages/umbracoPage.Master" - AutoEventWireup="True" Inherits="umbraco.presentation.developer.packages.Installer" - Trace="false" ValidateRequest="false" %> -<%@ Import Namespace="umbraco" %> -<%@ Register TagPrefix="cc1" Namespace="umbraco.uicontrols" Assembly="controls" %> - - - - - - - - - - - - - - - -
-

- Only install packages from sources you know and trust!

-

- When installing an Umbraco package you should use the same caution as when you install - an application on your computer.

-

- A malicious package could damage your Umbraco installation just like a malicious - application can damage your computer. -

-

- It is recommended to install from the official Umbraco package - repository or a custom repository whenever it's possible. -

-

- - -

-
-
- - -

- -
- - - <%= umbraco.ui.Text("packager", "chooseLocalPackageText") %> - -

-
- - - - -
- - -
-

- This repository requires authentication before you can download any packages from - it.
- Please enter email and password to login. -

-
-
- - - - - - -
- - - - - -
-

- Please note: Installing a package containing several items and - files can take some time. Do not refresh the page or navigate away before, the installer - notifies you once the install is completed. -

-
- - - - - - - - - - - - - - - - - -
-

Binary files in the package!

- - Read more... -
-

- This package contains .NET code. This is not unusual as .NET code - is used for any advanced functionality on an Umbraco powered website.

-

- However, if you don't know the author of the package or are unsure why this package - contains these files, it is adviced not to continue the installation. -

-

- The Files in question:
-

    - -
-

-
-
- -
- - -
-

- Legacy Property editors detected

- Read more... -
-

- This package contains legacy property editors which are not compatible with Umbraco 7

-

- This package may not function correctly if the package developer has not indicated that - it is compatible with version 7. Any DataTypes this package creates that do not have - a Version 7 compatible property editor will be converted to use a Label/NoEdit property editor. -

-
-
-
- - -
-

- Binary file errors detected

- Read more... -
-

- This package contains .NET binary files that might not be compatible with this version of Umbraco. - If you aren't sure what these errors mean or why they are listed please contact the package creator. -

-

- Error report
-

    - -
-

-
-
-
- -
-

- Macro Conflicts in the package!

- Read more... -
-

- This package contains one or more macros which have the same alias as an existing one on your site, based on the Macro Alias. -

-

- If you choose to continue your existing macros will be replaced with the ones from this package. If you do not want to overwrite your existing macros you will need to change their alias. -

-

- The Macros in question:
-

    - -
-

-
-
-
- - -
-

- Template Conflicts in the package!

- Read more... -
-

- This package contains one or more templates which have the same alias as an existing one on your site, based on the Template Alias. -

-

- If you choose to continue your existing template will be replaced with the ones from this package. If you do not want to overwrite your existing templates you will need to change their alias. -

-

- The Templates in question:
-

    - -
-

-
-
-
- - -
-

- Stylesheet Conflicts in the package!

- Read more... -
-

- This package contains one or more stylesheets which have the same alias as an existing one on your site, based on the Stylesheet Name. -

-

- If you choose to continue your existing stylesheets will be replaced with the ones from this package. If you do not want to overwrite your existing stylesheets you will need to change their name. -

-

- The Stylesheets in question:
-

    - -
-

-
-
-
- - -
- - -
-
- -
- - - - - - - - - - - - -

- All items in the package have been installed

-

- Overview of what was installed can be found under "installed package" in the developer - section.

-

- Uninstall is available at the same location.

-

- - -

- -
-
- - - - -

<%= umbraco.ui.Text("packager", "packageUninstalledText") %>

- -
-
- - - - -
- Please wait while the browser is reloaded... -
- - - -
-
- -
-
diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index 6903d9db23..faecec759b 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -20,6 +20,7 @@ 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 { @@ -113,7 +114,7 @@ namespace Umbraco.Web.Editors {"serverVarsJs", _urlHelper.Action("Application", "BackOffice")}, //API URLs { - "packagesRestApiBaseUrl", UmbracoConfig.For.UmbracoSettings().PackageRepositories.GetDefault().RestApiUrl + "packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl }, { "redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl( diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 6b5f460171..057d97ef33 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -10,9 +10,7 @@ using System.Web.Http; using System.Xml; using umbraco; using umbraco.cms.businesslogic.packager; -using umbraco.cms.businesslogic.packager.repositories; using umbraco.cms.presentation.Trees; -using umbraco.presentation.developer.packages; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Events; diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index b578e20401..6d1140e78f 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -532,9 +532,6 @@ - - ASPXCodeBehind - @@ -1717,7 +1714,6 @@ - diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackager.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackager.cs index 5470d530ad..5146b268cc 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackager.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackager.cs @@ -1,27 +1,7 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Data; -using System.IO; using System.Text; -using System.Web; -using System.Xml; -using System.Configuration; -using umbraco.BasePages; -using umbraco.BusinessLogic; -using umbraco.businesslogic; -using umbraco.cms.businesslogic; -using umbraco.cms.businesslogic.cache; -using umbraco.cms.businesslogic.contentitem; -using umbraco.cms.businesslogic.datatype; -using umbraco.cms.businesslogic.language; -using umbraco.cms.businesslogic.media; -using umbraco.cms.businesslogic.member; -using umbraco.cms.businesslogic.property; -using umbraco.cms.businesslogic.web; using umbraco.interfaces; -using umbraco.DataLayer; -using umbraco.BusinessLogic.Utils; using Umbraco.Core; using umbraco.cms.presentation.Trees; @@ -34,11 +14,9 @@ namespace umbraco [Obsolete("This is no longer used and will be removed from the codebase in the future")] public class loadPackager : BaseTree { - #region TreeI Members public loadPackager(string application) : base(application) { } protected override void CreateRootNode(ref XmlTreeNode rootNode) { - } private int _id; @@ -65,7 +43,7 @@ namespace umbraco protected override void CreateAllowedActions(ref List actions) { actions.Clear(); - actions.Add(umbraco.BusinessLogic.Actions.ActionRefresh.Instance); + actions.Add(BusinessLogic.Actions.ActionRefresh.Instance); } protected override void CreateRootNodeActions(ref List actions) @@ -93,89 +71,61 @@ namespace umbraco /// /// The tree. public override void Render(ref XmlTree tree) - { + { string[,] items = { { "BrowseRepository.aspx", "Install from repository" }, { "CreatePackage.aspx", "Created Packages" }, { "installedPackages.aspx", "Installed packages" }, { "StarterKits.aspx", "Starter kit" }, { "installer.aspx", "Install local package" } }; - - for (int i = 0; i <= items.GetUpperBound(0); i++) + for (var i = 0; i <= items.GetUpperBound(0); i++) { - XmlTreeNode xNode = XmlTreeNode.Create(this); + var xNode = XmlTreeNode.Create(this); xNode.NodeID = (i + 1).ToInvariantString(); xNode.Text = items[i, 1]; xNode.Icon = "icon-folder"; xNode.OpenIcon = "icon-folder"; - - + //Make sure the different sections load the correct childnodes. switch (items[i, 0]) { case "installedPackages.aspx": - if (cms.businesslogic.packager.InstalledPackage.GetAllInstalledPackages().Count > 0) { - xNode.Source = "tree.aspx?app=" + this._app + "&id=" + this._id + "&treeType=packagerPackages&packageType=installed" + "&rnd=" + Guid.NewGuid(); - xNode.NodeType = "installedPackages"; - xNode.Text = ui.Text("treeHeaders", "installedPackages"); + xNode.Source = $"tree.aspx?app={_app}&id={_id}&treeType=packagerPackages&packageType=installed&rnd={Guid.NewGuid()}"; + xNode.NodeType = "installedPackages"; + xNode.Text = ui.Text("treeHeaders", "installedPackages"); xNode.HasChildren = true; } else { xNode.Text = ""; } - xNode.Action = "javascript:void(0);"; - break; case "BrowseRepository.aspx": - - /* - //Gets all the repositories registered in umbracoSettings.config - var repos = cms.businesslogic.packager.repositories.Repository.getAll(); - - - //if more then one repo, then list them as child nodes under the "Install from repository" node. - // the repositories will then be fetched from the loadPackages class. - if (repos.Count > 1) - { - xNode.Source = "tree.aspx?app=" + this._app + "&id=" + this._id + "&treeType=packagerPackages&packageType=repositories" + "&rnd=" + Guid.NewGuid(); - xNode.NodeType = "packagesRepositories"; - xNode.Text = ui.Text("treeHeaders", "repositories"); - xNode.HasChildren = true; - } - */ - //if only one repo, then just list it directly and name it as the repository. - //the packages will be loaded from the loadPackages class with a repoAlias querystring - var repos = cms.businesslogic.packager.repositories.Repository.getAll(); - - xNode.Text = repos[0].Name; - xNode.Source = "tree.aspx?app=" + this._app + "&id=" + this._id + "&treeType=packagerPackages&packageType=repository&repoGuid=" + repos[0].Guid + "&rnd=" + Guid.NewGuid(); + xNode.Text = Constants.PackageRepository.DefaultRepositoryName; + xNode.Source = $"tree.aspx?app={_app}&id={_id}&treeType=packagerPackages&packageType=repository&repoGuid={Constants.PackageRepository.DefaultRepositoryId}&rnd={Guid.NewGuid()}"; xNode.NodeType = "packagesRepository"; - xNode.Action = "javascript:openPackageCategory('BrowseRepository.aspx?repoGuid=" + repos[0].Guid + "');"; + xNode.Action = $"javascript:openPackageCategory(\'BrowseRepository.aspx?repoGuid={Constants.PackageRepository.DefaultRepositoryId}\');"; xNode.Icon = "icon-server-alt"; xNode.HasChildren = true; - break; - case "CreatePackage.aspx": - xNode.Source = "tree.aspx?app=" + this._app + "&id=" + this._id + "&treeType=packagerPackages&packageType=created" + "&rnd=" + Guid.NewGuid(); + xNode.Source = $"tree.aspx?app={_app}&id={_id}&treeType=packagerPackages&packageType=created&rnd={Guid.NewGuid()}"; xNode.NodeType = "createdPackages"; - xNode.Menu.Clear(); - xNode.Menu.Add(umbraco.BusinessLogic.Actions.ActionNew.Instance); - xNode.Menu.Add(umbraco.BusinessLogic.Actions.ActionRefresh.Instance); + xNode.Menu.Clear(); + xNode.Menu.Add(BusinessLogic.Actions.ActionNew.Instance); + xNode.Menu.Add(BusinessLogic.Actions.ActionRefresh.Instance); xNode.Text = ui.Text("treeHeaders", "createdPackages"); xNode.HasChildren = true; xNode.Action = "javascript:void(0);"; - break; case "installer.aspx": xNode.Source = ""; xNode.NodeType = "uploadPackage"; xNode.Icon = "icon-page-up"; - xNode.Action = "javascript:openPackageCategory('" + items[i, 0] + "');"; + xNode.Action = $"javascript:openPackageCategory(\'{items[i, 0]}\');"; xNode.Text = ui.Text("treeHeaders", "localPackage"); xNode.Menu.Clear(); break; @@ -183,7 +133,7 @@ namespace umbraco case "StarterKits.aspx": xNode.Source = ""; xNode.NodeType = "starterKits"; - xNode.Action = "javascript:openPackageCategory('" + items[i, 0] + "');"; + xNode.Action = $"javascript:openPackageCategory(\'{items[i, 0]}\');"; xNode.Icon = "icon-flash"; xNode.Text = ui.Text("treeHeaders", "installStarterKit"); xNode.Menu.Clear(); @@ -199,7 +149,4 @@ namespace umbraco } } - - #endregion - } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackages.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackages.cs deleted file mode 100644 index 154f995618..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadPackages.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Web; -using System.Xml; -using umbraco.businesslogic; -using umbraco.cms.businesslogic.packager; -using umbraco.cms.presentation.Trees; -using Umbraco.Core; -using umbraco.interfaces; - -namespace umbraco -{ - //[Tree(Constants.Applications.Developer, "packagerPackages", "Packager Packages", initialize: false, sortOrder: 1)] - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - public class loadPackages : BaseTree - { - - public const string PACKAGE_TREE_PREFIX = "package_"; - - public loadPackages(string application) : base(application) { } - - protected override void CreateRootNode(ref XmlTreeNode rootNode) - { - - } - - private int _id; - private string _app; - private string _packageType = ""; - private string _repoGuid = ""; - - public override void RenderJS(ref StringBuilder Javascript) - { - Javascript.Append(@" - function openCreatedPackage(id) { - UmbClientMgr.contentFrame('developer/packages/editPackage.aspx?id=' + id); - } - function openInstalledPackage(id) { - UmbClientMgr.contentFrame('developer/packages/installedPackage.aspx?id=' + id); - } - "); - } - - protected override void CreateAllowedActions(ref List actions) - { - actions.Clear(); - } - - public override void Render(ref XmlTree tree) - { - - _packageType = HttpContext.Current.Request.QueryString["packageType"]; - - switch (_packageType) - { - case "installed": - Version v; - // Display the unique packages, ordered by the latest version number. [LK 2013-06-10] - var uniquePackages = InstalledPackage.GetAllInstalledPackages() - .OrderByDescending(x => Version.TryParse(x.Data.Version, out v) ? v : new Version()) - .GroupBy(x => x.Data.Name) - .Select(x => x.First()) - .OrderBy(x => x.Data.Name); - foreach (var p in uniquePackages) - { - var xNode = XmlTreeNode.Create(this); - xNode.NodeID = string.Concat(PACKAGE_TREE_PREFIX, p.Data.Id); - xNode.Text = p.Data.Name; - xNode.Action = string.Format("javascript:openInstalledPackage('{0}');", p.Data.Id); - xNode.Icon = "icon-box"; - xNode.OpenIcon = "icon-box"; - xNode.NodeType = "createdPackageInstance"; - tree.Add(xNode); - } - break; - - case "created": - foreach (CreatedPackage p in CreatedPackage.GetAllCreatedPackages()) - { - - XmlTreeNode xNode = XmlTreeNode.Create(this); - xNode.NodeID = PACKAGE_TREE_PREFIX + p.Data.Id.ToString(); - xNode.Text = p.Data.Name; - xNode.Action = "javascript:openCreatedPackage('" + p.Data.Id.ToString() + "');"; - xNode.Icon = "icon-box"; - xNode.OpenIcon = "icon-box"; - xNode.NodeType = "createdPackageInstance"; - xNode.Menu.Add(umbraco.BusinessLogic.Actions.ActionDelete.Instance); - tree.Add(xNode); - } - break; - - case "repositories": - List repos = cms.businesslogic.packager.repositories.Repository.getAll(); - - foreach (cms.businesslogic.packager.repositories.Repository repo in repos) - { - XmlTreeNode xNode = XmlTreeNode.Create(this); - xNode.Text = repo.Name; - xNode.Action = "javascript:openPackageCategory('BrowseRepository.aspx?repoGuid=" + repo.Guid + "');"; - xNode.Icon = "icon-server-alt"; - xNode.OpenIcon = "icon-server-alt"; - xNode.NodeType = "packagesRepo" + repo.Guid; - xNode.Menu.Add( umbraco.BusinessLogic.Actions.ActionRefresh.Instance ); - xNode.Source = "tree.aspx?app=" + this._app + "&id=" + this._id + "&treeType=packagerPackages&packageType=repository&repoGuid=" + repo.Guid + "&rnd=" + Guid.NewGuid(); - tree.Add(xNode); - - } - - break; - case "repository": - - _repoGuid = HttpContext.Current.Request.QueryString["repoGuid"]; - Umbraco.Web.org.umbraco.our.Repository r = new Umbraco.Web.org.umbraco.our.Repository(); - - foreach (var cat in r.Categories(_repoGuid)) - { - XmlTreeNode xNode = XmlTreeNode.Create(this); - xNode.NodeID = cat.Id.ToInvariantString(); - xNode.Text = cat.Text; - xNode.Action = "javascript:openPackageCategory('BrowseRepository.aspx?category=" + cat.Id + "&repoGuid=" + _repoGuid + "');"; - xNode.Icon = "icon-folder"; - xNode.OpenIcon = "icon-folder"; - xNode.NodeType = "packagesCategory" + cat.Id; - tree.Add(xNode); - - } - - break; - } - - } - - - } - -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs index 8c2f9ca837..de8639f7ac 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs @@ -27,7 +27,7 @@ namespace umbraco // we need to grab the id from the alias as the new tree needs to prefix the NodeID with "package_" if (ParentID == 0) { - ParentID = int.Parse(Alias.Substring(loadPackages.PACKAGE_TREE_PREFIX.Length)); + ParentID = int.Parse(Alias.Substring("package_".Length)); } cms.businesslogic.packager.CreatedPackage.GetById(ParentID).Delete(); return true; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installer.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installer.aspx.cs deleted file mode 100644 index a9bf7b5e43..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/installer.aspx.cs +++ /dev/null @@ -1,835 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Globalization; -using System.Threading; -using System.Web; -using System.Web.SessionState; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.Xml; -using System.Xml.XPath; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Web; -using umbraco.BasePages; -using umbraco.BusinessLogic; -using umbraco.cms.presentation.Trees; -using Umbraco.Core; -using BizLogicAction = umbraco.BusinessLogic.Actions.Action; - -namespace umbraco.presentation.developer.packages -{ - /// - /// Summary description for packager. - /// - [Obsolete("This should not be used and will be removed in v8, this is kept here only for backwards compat reasons, this page should never be rendered/used")] - public class Installer : UmbracoEnsuredPage - { - public Installer() - { - CurrentApp = DefaultApps.developer.ToString(); - _installer = new cms.businesslogic.packager.Installer(UmbracoUser.Id); - } - - private Control _configControl; - private cms.businesslogic.packager.repositories.Repository _repo; - private readonly cms.businesslogic.packager.Installer _installer = null; - private string _tempFileName = ""; - - protected string RefreshQueryString { get; set; } - - protected void Page_Load(object sender, EventArgs e) - { - var ex = new Exception(); - if (!cms.businesslogic.packager.Settings.HasFileAccess(ref ex)) - { - fb.Style.Add("margin-top", "7px"); - fb.type = uicontrols.Feedback.feedbacktype.error; - fb.Text = "" + ui.Text("errors", "filePermissionsError") + ":
" + ex.Message; - } - - if (!IsPostBack) - { - ButtonInstall.Attributes.Add("onClick", "jQuery(this).hide(); jQuery('#installingMessage').show();; return true;"); - ButtonLoadPackage.Attributes.Add("onClick", "jQuery(this).hide(); jQuery('#loadingbar').show();; return true;"); - } - - //if we are actually in the middle of installing something... meaning we keep redirecting back to this page with - // custom query strings - // TODO: SD: This process needs to be fixed/changed/etc... to use the InstallPackageController - // http://issues.umbraco.org/issue/U4-1047 - if (!string.IsNullOrEmpty(Request.GetItemAsString("installing"))) - { - HideAllPanes(); - pane_installing.Visible = true; - ProcessInstall(Request.GetItemAsString("installing")); //process the current step - - } - else if (tempFile.Value.IsNullOrWhiteSpace() //if we haven't downloaded the .umb temp file yet - && (!Request.GetItemAsString("guid").IsNullOrWhiteSpace() && !Request.GetItemAsString("repoGuid").IsNullOrWhiteSpace())) - { - //we'll fetch the local information we have about our repo, to find out what webservice to query. - _repo = cms.businesslogic.packager.repositories.Repository.getByGuid(Request.GetItemAsString("repoGuid")); - - if (_repo != null && _repo.HasConnection()) - { - //from the webservice we'll fetch some info about the package. - cms.businesslogic.packager.repositories.Package pack = _repo.Webservice.PackageByGuid(Request.GetItemAsString("guid")); - - //if the package is protected we will ask for the users credentials. (this happens every time they try to fetch anything) - if (!pack.Protected) - { - //if it isn't then go straigt to the accept licens screen - tempFile.Value = _installer.Import(_repo.fetch(Request.GetItemAsString("guid"), UmbracoUser.Id)); - UpdateSettings(); - - } - else if (!IsPostBack) - { - - //Authenticate against the repo - HideAllPanes(); - pane_authenticate.Visible = true; - - } - } - else - { - fb.Style.Add("margin-top", "7px"); - fb.type = uicontrols.Feedback.feedbacktype.error; - fb.Text = "No connection to repository. Runway could not be installed as there was no connection to: '" + _repo.RepositoryUrl + "'"; - pane_upload.Visible = false; - } - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - acceptCheckbox.Attributes.Add("onmouseup", "document.getElementById('" + ButtonInstall.ClientID + "').disabled = false;"); - } - - protected void uploadFile(object sender, EventArgs e) - { - try - { - _tempFileName = Guid.NewGuid().ToString() + ".umb"; - string fileName = SystemDirectories.Data + System.IO.Path.DirectorySeparatorChar + _tempFileName; - file1.PostedFile.SaveAs(IOHelper.MapPath(fileName)); - tempFile.Value = _installer.Import(_tempFileName); - UpdateSettings(); - } - catch (Exception ex) - { - fb.type = global::umbraco.uicontrols.Feedback.feedbacktype.error; - fb.Text = "Could not upload file
" + ex.ToString(); - } - } - - //this fetches the protected package from the repo. - protected void fetchProtectedPackage(object sender, EventArgs e) - { - //we auth against the webservice. This key will be used to fetch the protected package. - string memberGuid = _repo.Webservice.authenticate(tb_email.Text, library.CreateHash(tb_password.Text)); - - //if we auth correctly and get a valid key back, we will fetch the file from the repo webservice. - if (string.IsNullOrEmpty(memberGuid) == false) - { - tempFile.Value = _installer.Import(_repo.fetch(helper.Request("guid"), memberGuid)); - UpdateSettings(); - } - } - - //this loads the accept license screen - private void UpdateSettings() - { - HideAllPanes(); - - pane_acceptLicense.Visible = true; - pane_acceptLicenseInner.Text = "Installing the package: " + _installer.Name; - Panel1.Text = "Installing the package: " + _installer.Name; - - - if (_installer.ContainsUnsecureFiles) - { - pp_unsecureFiles.Visible = true; - foreach (string str in _installer.UnsecureFiles) - { - lt_files.Text += "
  • " + str + "
  • "; - } - } - - if (_installer.ContainsLegacyPropertyEditors) - { - LegacyPropertyEditorPanel.Visible = true; - } - - if (_installer.ContainsBinaryFileErrors) - { - BinaryFileErrorsPanel.Visible = true; - foreach (var str in _installer.BinaryFileErrors) - { - BinaryFileErrorReport.Text += "
  • " + str + "
  • "; - } - } - - if (_installer.ContainsMacroConflict) - { - pp_macroConflicts.Visible = true; - foreach (var item in _installer.ConflictingMacroAliases) - { - ltrMacroAlias.Text += "
  • " + item.Key + " (Alias: " + item.Value + ")
  • "; - } - } - - if (_installer.ContainsTemplateConflicts) - { - pp_templateConflicts.Visible = true; - foreach (var item in _installer.ConflictingTemplateAliases) - { - ltrTemplateAlias.Text += "
  • " + item.Key + " (Alias: " + item.Value + ")
  • "; - } - } - - if (_installer.ContainsStyleSheeConflicts) - { - pp_stylesheetConflicts.Visible = true; - foreach (var item in _installer.ConflictingStyleSheetNames) - { - ltrStylesheetNames.Text += "
  • " + item.Key + " (Alias: " + item.Value + ")
  • "; - } - } - - LabelName.Text = _installer.Name + " Version: " + _installer.Version; - LabelMore.Text = "" + _installer.Url + ""; - LabelAuthor.Text = "" + _installer.Author + ""; - LabelLicense.Text = "" + _installer.License + ""; - - if (_installer.ReadMe != "") - readme.Text = "
    " + library.ReplaceLineBreaks(library.StripHtml(_installer.ReadMe)) + "
    "; - else - readme.Text = "No information
    "; - } - - - private void ProcessInstall(string currentStep) - { - var dir = Request.GetItemAsString("dir"); - var packageId = 0; - int.TryParse(Request.GetItemAsString("pId"), out packageId); - - switch (currentStep.ToLowerInvariant()) - { - case "businesslogic": - //first load in the config from the temporary directory - //this will ensure that the installer have access to all the new files and the package manifest - _installer.LoadConfig(dir); - _installer.InstallBusinessLogic(packageId, dir); - - - //making sure that publishing actions performed from the cms layer gets pushed to the presentation - library.RefreshContent(); - - if (string.IsNullOrEmpty(_installer.Control) == false) - { - Response.Redirect("installer.aspx?installing=refresh&dir=" + dir + "&pId=" + packageId.ToString() + "&customControl=" + Server.UrlEncode(_installer.Control) + "&customUrl=" + Server.UrlEncode(_installer.Url)); - } - else - { - Response.Redirect("installer.aspx?installing=refresh&dir=" + dir + "&pId=" + packageId.ToString() + "&customUrl=" + Server.UrlEncode(_installer.Url)); - } - break; - case "custominstaller": - var customControl = Request.GetItemAsString("customControl"); - - if (customControl.IsNullOrWhiteSpace() == false) - { - HideAllPanes(); - - _configControl = LoadControl(SystemDirectories.Root + customControl); - _configControl.ID = "packagerConfigControl"; - - pane_optional.Controls.Add(_configControl); - pane_optional.Visible = true; - - if (!IsPostBack) - { - //We still need to clean everything up which is normally done in the Finished Action - PerformPostInstallCleanup(packageId, dir); - } - - } - else - { - //if the custom installer control is empty here (though it should never be because we've already checked for it previously) - //then we should run the normal FinishedAction - PerformFinishedAction(packageId, dir, Request.GetItemAsString("customUrl")); - } - break; - case "refresh": - PerformRefreshAction(packageId, dir, Request.GetItemAsString("customUrl"), Request.GetItemAsString("customControl")); - break; - case "finished": - PerformFinishedAction(packageId, dir, Request.GetItemAsString("customUrl")); - break; - case "uninstalled": - PerformUninstalledAction(); - break; - default: - break; - } - } - - /// - /// Perform the 'Finished' action of the installer - /// - /// - /// - /// - private void PerformFinishedAction(int packageId, string dir, string url) - { - HideAllPanes(); - //string url = _installer.Url; - string packageViewUrl = "installedPackage.aspx?id=" + packageId.ToString(CultureInfo.InvariantCulture); - - bt_viewInstalledPackage.OnClientClick = "document.location = '" + packageViewUrl + "'; return false;"; - - if (!string.IsNullOrEmpty(url)) - lit_authorUrl.Text = " " + ui.Text("or") + " " + ui.Text("viewPackageWebsite") + ""; - - - pane_success.Visible = true; - - PerformPostInstallCleanup(packageId, dir); - } - - private void PerformUninstalledAction() - { - HideAllPanes(); - Panel1.Text = "Package has been uninstalled"; - pane_uninstalled.Visible = true; - } - - /// - /// Perform the 'Refresh' action of the installer - /// - /// - /// - /// - /// - private void PerformRefreshAction(int packageId, string dir, string url, string customControl) - { - HideAllPanes(); - - //create the URL to refresh to - // /umbraco/developer/packages/installer.aspx?installing=finished - // &dir=X:\Projects\Umbraco\Umbraco_7.0\src\Umbraco.Web.UI\App_Data\aef8c41f-63a0-494b-a1e2-10d761647033 - // &pId=3 - // &customUrl=http:%2f%2four.umbraco.org%2fprojects%2fwebsite-utilities%2fmerchello - - if (customControl.IsNullOrWhiteSpace()) - { - RefreshQueryString = Server.UrlEncode(string.Format( - "installing=finished&dir={0}&pId={1}&customUrl={2}", - dir, packageId, url)); - } - else - { - RefreshQueryString = Server.UrlEncode(string.Format( - "installing=customInstaller&dir={0}&pId={1}&customUrl={2}&customControl={3}", - dir, packageId, url, customControl)); - } - - pane_refresh.Visible = true; - - PerformPostInstallCleanup(packageId, dir); - } - - /// - /// Runs Post refresh actions such reloading the correct tree nodes, etc... - /// - private void PerformPostRefreshAction() - { - BasePage.Current.ClientTools.ReloadActionNode(true, true); - } - - /// - /// Runs Post install actions such as clearning any necessary cache, reloading the correct tree nodes, etc... - /// - /// - /// - private void PerformPostInstallCleanup(int packageId, string dir) - { - _installer.InstallCleanUp(packageId, dir); - - // Update ClientDependency version - var clientDependencyConfig = new Umbraco.Core.Configuration.ClientDependencyConfiguration(LoggerResolver.Current.Logger); - var clientDependencyUpdated = clientDependencyConfig.IncreaseVersionNumber(); - - //clear the tree cache - we'll do this here even though the browser will reload, but just in case it doesn't can't hurt. - ClientTools.ClearClientTreeCache().RefreshTree("packager"); - TreeDefinitionCollection.Instance.ReRegisterTrees(); - BizLogicAction.ReRegisterActionsAndHandlers(); - } - - //this accepts the package, creates the manifest and then installs the files. - protected void startInstall(object sender, System.EventArgs e) - { - //we will now create the installer manifest, which means that umbraco can register everything that gets added to the system - //this returns an id of the manifest. - - _installer.LoadConfig(tempFile.Value); - - int pId = _installer.CreateManifest(tempFile.Value, helper.Request("guid"), helper.Request("repoGuid")); - - //and then copy over the files. This will take some time if it contains .dlls that will reboot the system.. - _installer.InstallFiles(pId, tempFile.Value); - - //TODO: This is a total hack, we need to refactor the installer to be just like the package installer during the - // install process and use AJAX to ensure that app pool restarts and restarts PROPERLY before installing the business - // logic. Until then, we are going to put a thread sleep here for 2 seconds in hopes that we always fluke out and the app - // pool will be restarted after redirect. - Thread.Sleep(2000); - - Response.Redirect("installer.aspx?installing=businesslogic&dir=" + tempFile.Value + "&pId=" + pId.ToString()); - } - - private void HideAllPanes() - { - pane_authenticate.Visible = false; - pane_acceptLicense.Visible = false; - pane_installing.Visible = false; - pane_optional.Visible = false; - pane_success.Visible = false; - pane_refresh.Visible = false; - pane_upload.Visible = false; - } - - /// - /// Panel1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.UmbracoPanel Panel1; - - /// - /// fb control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Feedback fb; - - /// - /// pane_upload control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_upload; - - /// - /// PropertyPanel9 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel9; - - /// - /// file1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlInputFile file1; - - /// - /// ButtonLoadPackage control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button ButtonLoadPackage; - - /// - /// progbar1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.ProgressBar progbar1; - - /// - /// pane_authenticate control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_authenticate; - - /// - /// tb_email control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox tb_email; - - /// - /// PropertyPanel1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel1; - - /// - /// tb_password control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox tb_password; - - /// - /// PropertyPanel2 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel2; - - /// - /// Button1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button Button1; - - /// - /// pane_acceptLicense control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Panel pane_acceptLicense; - - /// - /// pane_acceptLicenseInner control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_acceptLicenseInner; - - /// - /// PropertyPanel3 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel3; - - /// - /// LabelName control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label LabelName; - - /// - /// PropertyPanel5 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel5; - - /// - /// LabelAuthor control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label LabelAuthor; - - /// - /// PropertyPanel4 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel4; - - /// - /// LabelMore control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label LabelMore; - - /// - /// PropertyPanel6 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel6; - - /// - /// LabelLicense control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label LabelLicense; - - /// - /// PropertyPanel7 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel7; - - /// - /// acceptCheckbox control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox acceptCheckbox; - - /// - /// PropertyPanel8 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel PropertyPanel8; - - /// - /// readme control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal readme; - - /// - /// pp_unsecureFiles control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel pp_unsecureFiles; - - /// - /// lt_files control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal lt_files; - - /// - /// pp_macroConflicts control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel pp_macroConflicts; - - /// - /// ltrMacroAlias control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal ltrMacroAlias; - - /// - /// pp_templateConflicts control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel pp_templateConflicts; - - protected global::umbraco.uicontrols.PropertyPanel BinaryFileErrorsPanel; - protected global::umbraco.uicontrols.PropertyPanel LegacyPropertyEditorPanel; - protected global::System.Web.UI.WebControls.Literal BinaryFileErrorReport; - - /// - /// ltrTemplateAlias control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal ltrTemplateAlias; - - /// - /// pp_stylesheetConflicts control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.PropertyPanel pp_stylesheetConflicts; - - /// - /// ltrStylesheetNames control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal ltrStylesheetNames; - - /// - /// _progbar1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.ProgressBar _progbar1; - - /// - /// ButtonInstall control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button ButtonInstall; - - /// - /// pane_installing control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_installing; - - protected global::umbraco.uicontrols.Pane pane_uninstalled; - - - /// - /// progBar2 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.ProgressBar progBar2; - - /// - /// lit_installStatus control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal lit_installStatus; - - /// - /// pane_optional control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_optional; - - /// - /// pane_success control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.uicontrols.Pane pane_success; - - protected global::umbraco.uicontrols.Pane pane_refresh; - - /// - /// bt_viewInstalledPackage control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button bt_viewInstalledPackage; - - /// - /// lit_authorUrl control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal lit_authorUrl; - - /// - /// tempFile control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlInputHidden tempFile; - - /// - /// processState control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlInputHidden processState; - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs b/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs deleted file mode 100644 index 8609504313..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Repositories/Repository.cs +++ /dev/null @@ -1,299 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Xml; -using System.IO; -using System.Net; -using Umbraco.Core; -using Umbraco.Core.Auditing; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; -using Umbraco.Core.IO; - -namespace umbraco.cms.businesslogic.packager.repositories -{ - [Obsolete("This should not be used and will be removed in future Umbraco versions")] - public class Repository : DisposableObjectSlim - { - public string Guid { get; private set; } - - public string Name { get; private set; } - - public string RepositoryUrl { get; private set; } - - public string WebserviceUrl { get; private set; } - - - public RepositoryWebservice Webservice - { - get - { - var repo = new RepositoryWebservice(WebserviceUrl); - return repo; - } - } - - public SubmitStatus SubmitPackage(string authorGuid, PackageInstance package, byte[] doc) - { - - string packageName = package.Name; - string packageGuid = package.PackageGuid; - string description = package.Readme; - string packageFile = package.PackagePath; - - - System.IO.FileStream fs1 = null; - - try - { - - byte[] pack = new byte[0]; - fs1 = System.IO.File.Open(IOHelper.MapPath(packageFile), FileMode.Open, FileAccess.Read); - pack = new byte[fs1.Length]; - fs1.Read(pack, 0, (int) fs1.Length); - fs1.Close(); - fs1 = null; - - byte[] thumb = new byte[0]; //todo upload thumbnail... - - return Webservice.SubmitPackage(Guid, authorGuid, packageGuid, pack, doc, thumb, packageName, "", "", description); - } - catch (Exception ex) - { - LogHelper.Error("An error occurred in SubmitPackage", ex); - - return SubmitStatus.Error; - } - } - - public static List getAll() - { - - var repositories = new List(); - - foreach (var r in UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories) - { - var repository = new Repository - { - Guid = r.Id.ToString(), - Name = r.Name - }; - - repository.RepositoryUrl = r.RepositoryUrl; - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + r.WebServiceUrl.Trim('/'); - if (r.HasCustomWebServiceUrl) - { - string wsUrl = r.WebServiceUrl; - - if (wsUrl.Contains("://")) - { - repository.WebserviceUrl = r.WebServiceUrl; - } - else - { - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); - } - } - - repositories.Add(repository); - } - - return repositories; - } - - public static Repository getByGuid(string repositoryGuid) - { - Guid id; - if (System.Guid.TryParse(repositoryGuid, out id) == false) - { - throw new FormatException("The repositoryGuid is not a valid GUID"); - } - - var found = UmbracoConfig.For.UmbracoSettings().PackageRepositories.Repositories.FirstOrDefault(x => x.Id == id); - if (found == null) - { - return null; - } - - var repository = new Repository - { - Guid = found.Id.ToString(), - Name = found.Name - }; - - repository.RepositoryUrl = found.RepositoryUrl; - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + found.WebServiceUrl.Trim('/'); - - if (found.HasCustomWebServiceUrl) - { - string wsUrl = found.WebServiceUrl; - - if (wsUrl.Contains("://")) - { - repository.WebserviceUrl = found.WebServiceUrl; - } - else - { - repository.WebserviceUrl = repository.RepositoryUrl.Trim('/') + "/" + wsUrl.Trim('/'); - } - } - - return repository; - } - - - - //shortcut method to download pack from repo and place it on the server... - public string fetch(string packageGuid) - { - return fetch(packageGuid, string.Empty); - } - - public string fetch(string packageGuid, int userId) - { - // log - Audit.Add(AuditTypes.PackagerInstall, - string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), - userId, -1); - return fetch(packageGuid); - } - - /// - /// Used to get the correct package file from the repo for the current umbraco version - /// - /// - /// - /// - /// - public string GetPackageFile(string packageGuid, int userId, System.Version currentUmbracoVersion) - { - // log - Audit.Add(AuditTypes.PackagerInstall, - string.Format("Package {0} fetched from {1}", packageGuid, this.Guid), - userId, -1); - - var fileByteArray = Webservice.GetPackageFile(packageGuid, currentUmbracoVersion.ToString(3)); - - //successfull - if (fileByteArray.Length > 0) - { - // Check for package directory - if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); - - using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) - { - fs1.Write(fileByteArray, 0, fileByteArray.Length); - fs1.Close(); - return "packages\\" + packageGuid + ".umb"; - } - } - - return ""; - } - - public bool HasConnection() - { - - string strServer = this.RepositoryUrl; - - try - { - - HttpWebRequest reqFP = (HttpWebRequest) HttpWebRequest.Create(strServer); - HttpWebResponse rspFP = (HttpWebResponse) reqFP.GetResponse(); - - if (HttpStatusCode.OK == rspFP.StatusCode) - { - - // HTTP = 200 - Internet connection available, server online - rspFP.Close(); - - return true; - - } - else - { - - // Other status - Server or connection not available - - rspFP.Close(); - - return false; - - } - - } - catch (WebException) - { - - // Exception - connection not available - - return false; - - } - } - - - /// - /// This goes and fetches the Byte array for the package from OUR, but it's pretty strange - /// - /// - /// The package ID for the package file to be returned - /// - /// - /// This is a strange Umbraco version parameter - but it's not really an umbraco version, it's a special/odd version format like Version41 - /// but it's actually not used for the 7.5+ package installs so it's obsolete/unused. - /// - /// - public string fetch(string packageGuid, string key) - { - - byte[] fileByteArray = new byte[0]; - - if (key == string.Empty) - { - //SD: this is odd, not sure why it returns a different package depending on the legacy xml schema but I'll leave it for now - if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) - fileByteArray = Webservice.fetchPackage(packageGuid); - else - { - fileByteArray = Webservice.fetchPackageByVersion(packageGuid, Version.Version41); - } - } - else - { - fileByteArray = Webservice.fetchProtectedPackage(packageGuid, key); - } - - //successfull - if (fileByteArray.Length > 0) - { - - // Check for package directory - if (Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)) == false) - Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); - - using (var fs1 = new FileStream(IOHelper.MapPath(Settings.PackagerRoot + Path.DirectorySeparatorChar + packageGuid + ".umb"), FileMode.Create)) - { - fs1.Write(fileByteArray, 0, fileByteArray.Length); - fs1.Close(); - return "packages\\" + packageGuid + ".umb"; - } - } - - // log - - return ""; - } - - /// - /// Handles the disposal of resources. Derived from abstract class which handles common required locking logic. - /// - protected override void DisposeResources() - { - Webservice.Dispose(); - } - } -} diff --git a/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs b/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs deleted file mode 100644 index a2da17dd76..0000000000 --- a/src/umbraco.cms/businesslogic/Packager/Repositories/RepositoryWebservice.cs +++ /dev/null @@ -1,2002 +0,0 @@ -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Web.Services; -using System.Web.Services.Protocols; -using System.Xml.Serialization; - -namespace umbraco.cms.businesslogic.packager.repositories -{ - - - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Web.Services.WebServiceBindingAttribute(Name = "RepositorySoap", Namespace = "http://packages.umbraco.org/webservices/")] - public partial class RepositoryWebservice : System.Web.Services.Protocols.SoapHttpClientProtocol - { - - private System.Threading.SendOrPostCallback CategoriesOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosCategorizedOperationCompleted; - - private System.Threading.SendOrPostCallback NitrosCategorizedByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitsOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitModulesCategorizedOperationCompleted; - - private System.Threading.SendOrPostCallback StarterKitModulesOperationCompleted; - - private System.Threading.SendOrPostCallback authenticateOperationCompleted; - - private System.Threading.SendOrPostCallback GetPackageFileOperationCompleted; - - private System.Threading.SendOrPostCallback fetchPackageByVersionOperationCompleted; - - private System.Threading.SendOrPostCallback fetchPackageOperationCompleted; - - private System.Threading.SendOrPostCallback fetchProtectedPackageOperationCompleted; - - private System.Threading.SendOrPostCallback SubmitPackageOperationCompleted; - - private System.Threading.SendOrPostCallback PackageByGuidOperationCompleted; - - private System.Threading.SendOrPostCallback SkinByGuidOperationCompleted; - - private System.Threading.SendOrPostCallback SkinsOperationCompleted; - - /// - public RepositoryWebservice(string url) - { - this.Url = url;//"http://our.umbraco.org/umbraco/webservices/api/repository.asmx"; - } - - /// - public event CategoriesCompletedEventHandler CategoriesCompleted; - - /// - public event NitrosCompletedEventHandler NitrosCompleted; - - /// - public event NitrosByVersionCompletedEventHandler NitrosByVersionCompleted; - - /// - public event NitrosCategorizedCompletedEventHandler NitrosCategorizedCompleted; - - /// - public event NitrosCategorizedByVersionCompletedEventHandler NitrosCategorizedByVersionCompleted; - - /// - public event StarterKitsCompletedEventHandler StarterKitsCompleted; - - /// - public event StarterKitModulesCategorizedCompletedEventHandler StarterKitModulesCategorizedCompleted; - - /// - public event StarterKitModulesCompletedEventHandler StarterKitModulesCompleted; - - /// - public event authenticateCompletedEventHandler authenticateCompleted; - - /// - public event GetPackageFileCompletedEventHandler GetPackageFileCompleted; - - /// - public event fetchPackageByVersionCompletedEventHandler fetchPackageByVersionCompleted; - - /// - public event fetchPackageCompletedEventHandler fetchPackageCompleted; - - /// - public event fetchProtectedPackageCompletedEventHandler fetchProtectedPackageCompleted; - - /// - public event SubmitPackageCompletedEventHandler SubmitPackageCompleted; - - /// - public event PackageByGuidCompletedEventHandler PackageByGuidCompleted; - - /// - public event SkinByGuidCompletedEventHandler SkinByGuidCompleted; - - /// - public event SkinsCompletedEventHandler SkinsCompleted; - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Categories", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] Categories(string repositoryGuid) - { - object[] results = this.Invoke("Categories", new object[] { - repositoryGuid}); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginCategories(string repositoryGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Categories", new object[] { - repositoryGuid}, callback, asyncState); - } - - /// - public Category[] EndCategories(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void CategoriesAsync(string repositoryGuid) - { - this.CategoriesAsync(repositoryGuid, null); - } - - /// - public void CategoriesAsync(string repositoryGuid, object userState) - { - if ((this.CategoriesOperationCompleted == null)) - { - this.CategoriesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCategoriesOperationCompleted); - } - this.InvokeAsync("Categories", new object[] { - repositoryGuid}, this.CategoriesOperationCompleted, userState); - } - - private void OnCategoriesOperationCompleted(object arg) - { - if ((this.CategoriesCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.CategoriesCompleted(this, new CategoriesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Nitros", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] Nitros() - { - object[] results = this.Invoke("Nitros", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitros(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Nitros", new object[0], callback, asyncState); - } - - /// - public Package[] EndNitros(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void NitrosAsync() - { - this.NitrosAsync(null); - } - - /// - public void NitrosAsync(object userState) - { - if ((this.NitrosOperationCompleted == null)) - { - this.NitrosOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosOperationCompleted); - } - this.InvokeAsync("Nitros", new object[0], this.NitrosOperationCompleted, userState); - } - - private void OnNitrosOperationCompleted(object arg) - { - if ((this.NitrosCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCompleted(this, new NitrosCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] NitrosByVersion(Version version) - { - object[] results = this.Invoke("NitrosByVersion", new object[] { - version}); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosByVersion(Version version, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosByVersion", new object[] { - version}, callback, asyncState); - } - - /// - public Package[] EndNitrosByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void NitrosByVersionAsync(Version version) - { - this.NitrosByVersionAsync(version, null); - } - - /// - public void NitrosByVersionAsync(Version version, object userState) - { - if ((this.NitrosByVersionOperationCompleted == null)) - { - this.NitrosByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosByVersionOperationCompleted); - } - this.InvokeAsync("NitrosByVersion", new object[] { - version}, this.NitrosByVersionOperationCompleted, userState); - } - - private void OnNitrosByVersionOperationCompleted(object arg) - { - if ((this.NitrosByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosByVersionCompleted(this, new NitrosByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosCategorized", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] NitrosCategorized() - { - object[] results = this.Invoke("NitrosCategorized", new object[0]); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosCategorized(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosCategorized", new object[0], callback, asyncState); - } - - /// - public Category[] EndNitrosCategorized(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void NitrosCategorizedAsync() - { - this.NitrosCategorizedAsync(null); - } - - /// - public void NitrosCategorizedAsync(object userState) - { - if ((this.NitrosCategorizedOperationCompleted == null)) - { - this.NitrosCategorizedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosCategorizedOperationCompleted); - } - this.InvokeAsync("NitrosCategorized", new object[0], this.NitrosCategorizedOperationCompleted, userState); - } - - private void OnNitrosCategorizedOperationCompleted(object arg) - { - if ((this.NitrosCategorizedCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCategorizedCompleted(this, new NitrosCategorizedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/NitrosCategorizedByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] NitrosCategorizedByVersion(Version version) - { - object[] results = this.Invoke("NitrosCategorizedByVersion", new object[] { - version}); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginNitrosCategorizedByVersion(Version version, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("NitrosCategorizedByVersion", new object[] { - version}, callback, asyncState); - } - - /// - public Category[] EndNitrosCategorizedByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void NitrosCategorizedByVersionAsync(Version version) - { - this.NitrosCategorizedByVersionAsync(version, null); - } - - /// - public void NitrosCategorizedByVersionAsync(Version version, object userState) - { - if ((this.NitrosCategorizedByVersionOperationCompleted == null)) - { - this.NitrosCategorizedByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnNitrosCategorizedByVersionOperationCompleted); - } - this.InvokeAsync("NitrosCategorizedByVersion", new object[] { - version}, this.NitrosCategorizedByVersionOperationCompleted, userState); - } - - private void OnNitrosCategorizedByVersionOperationCompleted(object arg) - { - if ((this.NitrosCategorizedByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.NitrosCategorizedByVersionCompleted(this, new NitrosCategorizedByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKits", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] StarterKits() - { - object[] results = this.Invoke("StarterKits", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKits(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKits", new object[0], callback, asyncState); - } - - /// - public Package[] EndStarterKits(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void StarterKitsAsync() - { - this.StarterKitsAsync(null); - } - - /// - public void StarterKitsAsync(object userState) - { - if ((this.StarterKitsOperationCompleted == null)) - { - this.StarterKitsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitsOperationCompleted); - } - this.InvokeAsync("StarterKits", new object[0], this.StarterKitsOperationCompleted, userState); - } - - private void OnStarterKitsOperationCompleted(object arg) - { - if ((this.StarterKitsCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitsCompleted(this, new StarterKitsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKitModulesCategorized", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Category[] StarterKitModulesCategorized() - { - object[] results = this.Invoke("StarterKitModulesCategorized", new object[0]); - return ((Category[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKitModulesCategorized(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKitModulesCategorized", new object[0], callback, asyncState); - } - - /// - public Category[] EndStarterKitModulesCategorized(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Category[])(results[0])); - } - - /// - public void StarterKitModulesCategorizedAsync() - { - this.StarterKitModulesCategorizedAsync(null); - } - - /// - public void StarterKitModulesCategorizedAsync(object userState) - { - if ((this.StarterKitModulesCategorizedOperationCompleted == null)) - { - this.StarterKitModulesCategorizedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitModulesCategorizedOperationCompleted); - } - this.InvokeAsync("StarterKitModulesCategorized", new object[0], this.StarterKitModulesCategorizedOperationCompleted, userState); - } - - private void OnStarterKitModulesCategorizedOperationCompleted(object arg) - { - if ((this.StarterKitModulesCategorizedCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitModulesCategorizedCompleted(this, new StarterKitModulesCategorizedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/StarterKitModules", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package[] StarterKitModules() - { - object[] results = this.Invoke("StarterKitModules", new object[0]); - return ((Package[])(results[0])); - } - - /// - public System.IAsyncResult BeginStarterKitModules(System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("StarterKitModules", new object[0], callback, asyncState); - } - - /// - public Package[] EndStarterKitModules(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package[])(results[0])); - } - - /// - public void StarterKitModulesAsync() - { - this.StarterKitModulesAsync(null); - } - - /// - public void StarterKitModulesAsync(object userState) - { - if ((this.StarterKitModulesOperationCompleted == null)) - { - this.StarterKitModulesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStarterKitModulesOperationCompleted); - } - this.InvokeAsync("StarterKitModules", new object[0], this.StarterKitModulesOperationCompleted, userState); - } - - private void OnStarterKitModulesOperationCompleted(object arg) - { - if ((this.StarterKitModulesCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.StarterKitModulesCompleted(this, new StarterKitModulesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/authenticate", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public string authenticate(string email, string md5Password) - { - object[] results = this.Invoke("authenticate", new object[] { - email, - md5Password}); - return ((string)(results[0])); - } - - /// - public System.IAsyncResult Beginauthenticate(string email, string md5Password, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("authenticate", new object[] { - email, - md5Password}, callback, asyncState); - } - - /// - public string Endauthenticate(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((string)(results[0])); - } - - /// - public void authenticateAsync(string email, string md5Password) - { - this.authenticateAsync(email, md5Password, null); - } - - /// - public void authenticateAsync(string email, string md5Password, object userState) - { - if ((this.authenticateOperationCompleted == null)) - { - this.authenticateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnauthenticateOperationCompleted); - } - this.InvokeAsync("authenticate", new object[] { - email, - md5Password}, this.authenticateOperationCompleted, userState); - } - - private void OnauthenticateOperationCompleted(object arg) - { - if ((this.authenticateCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.authenticateCompleted(this, new authenticateCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - - - - - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/GetPackageFile", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] GetPackageFile(string packageGuid, string umbracoVersion) - { - object[] results = this.Invoke("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackageByVersion(string packageGuid, string umbracoVersion, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}, callback, asyncState); - } - - /// - public byte[] EndGetPackageFile(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void GetPackageFileAsync(string packageGuid, string umbracoVersion) - { - this.GetPackageFileAsync(packageGuid, umbracoVersion, null); - } - - /// - public void GetPackageFileAsync(string packageGuid, string umbracoVersion, object userState) - { - if ((this.GetPackageFileOperationCompleted == null)) - { - this.GetPackageFileOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetPackageFileOperationCompleted); - } - this.InvokeAsync("GetPackageFile", new object[] { - packageGuid, - umbracoVersion}, this.GetPackageFileOperationCompleted, userState); - } - - private void OnGetPackageFileOperationCompleted(object arg) - { - if ((this.GetPackageFileCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.GetPackageFileCompleted(this, new GetPackageFileCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - - - - - - - - - - - - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchPackageByVersion", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchPackageByVersion(string packageGuid, Version schemaVersion) - { - object[] results = this.Invoke("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackageByVersion(string packageGuid, Version schemaVersion, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}, callback, asyncState); - } - - /// - public byte[] EndfetchPackageByVersion(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchPackageByVersionAsync(string packageGuid, Version schemaVersion) - { - this.fetchPackageByVersionAsync(packageGuid, schemaVersion, null); - } - - /// - public void fetchPackageByVersionAsync(string packageGuid, Version schemaVersion, object userState) - { - if ((this.fetchPackageByVersionOperationCompleted == null)) - { - this.fetchPackageByVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchPackageByVersionOperationCompleted); - } - this.InvokeAsync("fetchPackageByVersion", new object[] { - packageGuid, - schemaVersion}, this.fetchPackageByVersionOperationCompleted, userState); - } - - private void OnfetchPackageByVersionOperationCompleted(object arg) - { - if ((this.fetchPackageByVersionCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchPackageByVersionCompleted(this, new fetchPackageByVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchPackage(string packageGuid) - { - object[] results = this.Invoke("fetchPackage", new object[] { - packageGuid}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchPackage(string packageGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchPackage", new object[] { - packageGuid}, callback, asyncState); - } - - /// - public byte[] EndfetchPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchPackageAsync(string packageGuid) - { - this.fetchPackageAsync(packageGuid, null); - } - - /// - public void fetchPackageAsync(string packageGuid, object userState) - { - if ((this.fetchPackageOperationCompleted == null)) - { - this.fetchPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchPackageOperationCompleted); - } - this.InvokeAsync("fetchPackage", new object[] { - packageGuid}, this.fetchPackageOperationCompleted, userState); - } - - private void OnfetchPackageOperationCompleted(object arg) - { - if ((this.fetchPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchPackageCompleted(this, new fetchPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/fetchProtectedPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - [return: System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] - public byte[] fetchProtectedPackage(string packageGuid, string memberKey) - { - object[] results = this.Invoke("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}); - return ((byte[])(results[0])); - } - - /// - public System.IAsyncResult BeginfetchProtectedPackage(string packageGuid, string memberKey, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}, callback, asyncState); - } - - /// - public byte[] EndfetchProtectedPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((byte[])(results[0])); - } - - /// - public void fetchProtectedPackageAsync(string packageGuid, string memberKey) - { - this.fetchProtectedPackageAsync(packageGuid, memberKey, null); - } - - /// - public void fetchProtectedPackageAsync(string packageGuid, string memberKey, object userState) - { - if ((this.fetchProtectedPackageOperationCompleted == null)) - { - this.fetchProtectedPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnfetchProtectedPackageOperationCompleted); - } - this.InvokeAsync("fetchProtectedPackage", new object[] { - packageGuid, - memberKey}, this.fetchProtectedPackageOperationCompleted, userState); - } - - private void OnfetchProtectedPackageOperationCompleted(object arg) - { - if ((this.fetchProtectedPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.fetchProtectedPackageCompleted(this, new fetchProtectedPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/SubmitPackage", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public SubmitStatus SubmitPackage(string repositoryGuid, string authorGuid, string packageGuid, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageFile, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageDoc, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] packageThumbnail, string name, string author, string authorUrl, string description) - { - object[] results = this.Invoke("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}); - return ((SubmitStatus)(results[0])); - } - - /// - public System.IAsyncResult BeginSubmitPackage(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}, callback, asyncState); - } - - /// - public SubmitStatus EndSubmitPackage(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((SubmitStatus)(results[0])); - } - - /// - public void SubmitPackageAsync(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description) - { - this.SubmitPackageAsync(repositoryGuid, authorGuid, packageGuid, packageFile, packageDoc, packageThumbnail, name, author, authorUrl, description, null); - } - - /// - public void SubmitPackageAsync(string repositoryGuid, string authorGuid, string packageGuid, byte[] packageFile, byte[] packageDoc, byte[] packageThumbnail, string name, string author, string authorUrl, string description, object userState) - { - if ((this.SubmitPackageOperationCompleted == null)) - { - this.SubmitPackageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSubmitPackageOperationCompleted); - } - this.InvokeAsync("SubmitPackage", new object[] { - repositoryGuid, - authorGuid, - packageGuid, - packageFile, - packageDoc, - packageThumbnail, - name, - author, - authorUrl, - description}, this.SubmitPackageOperationCompleted, userState); - } - - private void OnSubmitPackageOperationCompleted(object arg) - { - if ((this.SubmitPackageCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SubmitPackageCompleted(this, new SubmitPackageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/PackageByGuid", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Package PackageByGuid(string packageGuid) - { - object[] results = this.Invoke("PackageByGuid", new object[] { - packageGuid}); - return ((Package)(results[0])); - } - - /// - public System.IAsyncResult BeginPackageByGuid(string packageGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("PackageByGuid", new object[] { - packageGuid}, callback, asyncState); - } - - /// - public Package EndPackageByGuid(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Package)(results[0])); - } - - /// - public void PackageByGuidAsync(string packageGuid) - { - this.PackageByGuidAsync(packageGuid, null); - } - - /// - public void PackageByGuidAsync(string packageGuid, object userState) - { - if ((this.PackageByGuidOperationCompleted == null)) - { - this.PackageByGuidOperationCompleted = new System.Threading.SendOrPostCallback(this.OnPackageByGuidOperationCompleted); - } - this.InvokeAsync("PackageByGuid", new object[] { - packageGuid}, this.PackageByGuidOperationCompleted, userState); - } - - private void OnPackageByGuidOperationCompleted(object arg) - { - if ((this.PackageByGuidCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.PackageByGuidCompleted(this, new PackageByGuidCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/SkinByGuid", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Skin SkinByGuid(string skinGuid) - { - object[] results = this.Invoke("SkinByGuid", new object[] { - skinGuid}); - return ((Skin)(results[0])); - } - - /// - public System.IAsyncResult BeginSkinByGuid(string skinGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("SkinByGuid", new object[] { - skinGuid}, callback, asyncState); - } - - /// - public Skin EndSkinByGuid(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Skin)(results[0])); - } - - /// - public void SkinByGuidAsync(string skinGuid) - { - this.SkinByGuidAsync(skinGuid, null); - } - - /// - public void SkinByGuidAsync(string skinGuid, object userState) - { - if ((this.SkinByGuidOperationCompleted == null)) - { - this.SkinByGuidOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSkinByGuidOperationCompleted); - } - this.InvokeAsync("SkinByGuid", new object[] { - skinGuid}, this.SkinByGuidOperationCompleted, userState); - } - - private void OnSkinByGuidOperationCompleted(object arg) - { - if ((this.SkinByGuidCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SkinByGuidCompleted(this, new SkinByGuidCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://packages.umbraco.org/webservices/Skins", RequestNamespace = "http://packages.umbraco.org/webservices/", ResponseNamespace = "http://packages.umbraco.org/webservices/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] - public Skin[] Skins(string starterKitGuid) - { - object[] results = this.Invoke("Skins", new object[] { - starterKitGuid}); - return ((Skin[])(results[0])); - } - - /// - public System.IAsyncResult BeginSkins(string starterKitGuid, System.AsyncCallback callback, object asyncState) - { - return this.BeginInvoke("Skins", new object[] { - starterKitGuid}, callback, asyncState); - } - - /// - public Skin[] EndSkins(System.IAsyncResult asyncResult) - { - object[] results = this.EndInvoke(asyncResult); - return ((Skin[])(results[0])); - } - - /// - public void SkinsAsync(string starterKitGuid) - { - this.SkinsAsync(starterKitGuid, null); - } - - /// - public void SkinsAsync(string starterKitGuid, object userState) - { - if ((this.SkinsOperationCompleted == null)) - { - this.SkinsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSkinsOperationCompleted); - } - this.InvokeAsync("Skins", new object[] { - starterKitGuid}, this.SkinsOperationCompleted, userState); - } - - private void OnSkinsOperationCompleted(object arg) - { - if ((this.SkinsCompleted != null)) - { - System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); - this.SkinsCompleted(this, new SkinsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); - } - } - - /// - public new void CancelAsync(object userState) - { - base.CancelAsync(userState); - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Category - { - - private string textField; - - private string descriptionField; - - private string urlField; - - private int idField; - - private Package[] packagesField; - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Url - { - get - { - return this.urlField; - } - set - { - this.urlField = value; - } - } - - /// - public int Id - { - get - { - return this.idField; - } - set - { - this.idField = value; - } - } - - /// - public Package[] Packages - { - get - { - return this.packagesField; - } - set - { - this.packagesField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Package - { - - private System.Guid repoGuidField; - - private string textField; - - private string descriptionField; - - private string iconField; - - private string thumbnailField; - - private string documentationField; - - private string demoField; - - private bool acceptedField; - - private bool editorsPickField; - - private bool protectedField; - - private bool hasUpgradeField; - - private string upgradeVersionField; - - private string upgradeReadMeField; - - private string urlField; - - /// - public System.Guid RepoGuid - { - get - { - return this.repoGuidField; - } - set - { - this.repoGuidField = value; - } - } - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Icon - { - get - { - return this.iconField; - } - set - { - this.iconField = value; - } - } - - /// - public string Thumbnail - { - get - { - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - /// - public string Documentation - { - get - { - return this.documentationField; - } - set - { - this.documentationField = value; - } - } - - /// - public string Demo - { - get - { - return this.demoField; - } - set - { - this.demoField = value; - } - } - - /// - public bool Accepted - { - get - { - return this.acceptedField; - } - set - { - this.acceptedField = value; - } - } - - /// - public bool EditorsPick - { - get - { - return this.editorsPickField; - } - set - { - this.editorsPickField = value; - } - } - - /// - public bool Protected - { - get - { - return this.protectedField; - } - set - { - this.protectedField = value; - } - } - - /// - public bool HasUpgrade - { - get - { - return this.hasUpgradeField; - } - set - { - this.hasUpgradeField = value; - } - } - - /// - public string UpgradeVersion - { - get - { - return this.upgradeVersionField; - } - set - { - this.upgradeVersionField = value; - } - } - - /// - public string UpgradeReadMe - { - get - { - return this.upgradeReadMeField; - } - set - { - this.upgradeReadMeField = value; - } - } - - /// - public string Url - { - get - { - return this.urlField; - } - set - { - this.urlField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public partial class Skin - { - - private System.Guid repoGuidField; - - private string textField; - - private string thumbnailField; - - private string previewField; - - private string descriptionField; - - private string authorField; - - private string authorUrlField; - - private string licenseField; - - private string licenseUrlField; - - /// - public System.Guid RepoGuid - { - get - { - return this.repoGuidField; - } - set - { - this.repoGuidField = value; - } - } - - /// - public string Text - { - get - { - return this.textField; - } - set - { - this.textField = value; - } - } - - /// - public string Thumbnail - { - get - { - return this.thumbnailField; - } - set - { - this.thumbnailField = value; - } - } - - /// - public string Preview - { - get - { - return this.previewField; - } - set - { - this.previewField = value; - } - } - - /// - public string Description - { - get - { - return this.descriptionField; - } - set - { - this.descriptionField = value; - } - } - - /// - public string Author - { - get - { - return this.authorField; - } - set - { - this.authorField = value; - } - } - - /// - public string AuthorUrl - { - get - { - return this.authorUrlField; - } - set - { - this.authorUrlField = value; - } - } - - /// - public string License - { - get - { - return this.licenseField; - } - set - { - this.licenseField = value; - } - } - - /// - public string LicenseUrl - { - get - { - return this.licenseUrlField; - } - set - { - this.licenseUrlField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public enum Version - { - - /// - Version3, - - /// - Version4, - - /// - /// This is apparently the version number we pass in for all installs - /// - Version41, - - /// - Version41Legacy, - - /// - Version50, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://packages.umbraco.org/webservices/")] - public enum SubmitStatus - { - - /// - Complete, - - /// - Exists, - - /// - NoAccess, - - /// - Error, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void CategoriesCompletedEventHandler(object sender, CategoriesCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class CategoriesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal CategoriesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCompletedEventHandler(object sender, NitrosCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosByVersionCompletedEventHandler(object sender, NitrosByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCategorizedCompletedEventHandler(object sender, NitrosCategorizedCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCategorizedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCategorizedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void NitrosCategorizedByVersionCompletedEventHandler(object sender, NitrosCategorizedByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class NitrosCategorizedByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal NitrosCategorizedByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitsCompletedEventHandler(object sender, StarterKitsCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitModulesCategorizedCompletedEventHandler(object sender, StarterKitModulesCategorizedCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitModulesCategorizedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitModulesCategorizedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Category[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Category[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void StarterKitModulesCompletedEventHandler(object sender, StarterKitModulesCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class StarterKitModulesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal StarterKitModulesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void authenticateCompletedEventHandler(object sender, authenticateCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class authenticateCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal authenticateCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public string Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((string)(this.results[0])); - } - } - } - - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void GetPackageFileCompletedEventHandler(object sender, GetPackageFileCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class GetPackageFileCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal GetPackageFileCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchPackageByVersionCompletedEventHandler(object sender, fetchPackageByVersionCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchPackageByVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchPackageByVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchPackageCompletedEventHandler(object sender, fetchPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void fetchProtectedPackageCompletedEventHandler(object sender, fetchProtectedPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class fetchProtectedPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal fetchProtectedPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public byte[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((byte[])(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SubmitPackageCompletedEventHandler(object sender, SubmitPackageCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SubmitPackageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SubmitPackageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public SubmitStatus Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((SubmitStatus)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void PackageByGuidCompletedEventHandler(object sender, PackageByGuidCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class PackageByGuidCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal PackageByGuidCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Package Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Package)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SkinByGuidCompletedEventHandler(object sender, SkinByGuidCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SkinByGuidCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SkinByGuidCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Skin Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Skin)(this.results[0])); - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - public delegate void SkinsCompletedEventHandler(object sender, SkinsCompletedEventArgs e); - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - public partial class SkinsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs - { - - private object[] results; - - internal SkinsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) - { - this.results = results; - } - - /// - public Skin[] Result - { - get - { - this.RaiseExceptionIfNecessary(); - return ((Skin[])(this.results[0])); - } - } - } -} diff --git a/src/umbraco.cms/umbraco.cms.csproj b/src/umbraco.cms/umbraco.cms.csproj index 42db5b90ee..c38dbb2d2c 100644 --- a/src/umbraco.cms/umbraco.cms.csproj +++ b/src/umbraco.cms/umbraco.cms.csproj @@ -346,8 +346,6 @@ Code - - Code From 6c8e39876fa9cc6d577a711ae31ba930a47b7629 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 19:36:32 +0200 Subject: [PATCH 02/58] These changes shouldn't have been checked in --- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index fa3ff3ca72..3a7cbc4429 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -49,7 +49,6 @@ true true -
    bin\ @@ -1037,7 +1036,7 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" True 7110 / - http://localhost:3110 + http://localhost:7110 False False From 8fc33f6aea7a5a96089af668548c71a5e24a84d6 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 19:36:44 +0200 Subject: [PATCH 03/58] Fix unit tests --- .../UmbracoSettings/umbracoSettings.minimal.config | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config index f74879b193..b6ea54d75e 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config @@ -60,9 +60,6 @@ - - - @@ -72,4 +69,4 @@ - \ No newline at end of file + From 386dc1a14d39dba5e41cdb714be3c47e0ffbf76f Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 19:54:53 +0200 Subject: [PATCH 04/58] U4-11253 New Chrome 66 trimStart function is overriding the Umbraco Core trimStart polyfill --- .../lib/umbraco/Extensions.js | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js index b70a6b12bc..e8c6eda4bc 100644 --- a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js +++ b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js @@ -84,27 +84,21 @@ }; } - if (!String.prototype.trimStart) { - - /** trims the start of the string*/ - String.prototype.trimStart = function (str) { - if (this.startsWith(str)) { - return this.substring(str.length); - } - return this; - }; - } - - if (!String.prototype.trimEnd) { + /** trims the start of the string*/ + String.prototype.trimStart = function (str) { + if (this.startsWith(str)) { + return this.substring(str.length); + } + return this; + }; - /** trims the end of the string*/ - String.prototype.trimEnd = function (str) { - if (this.endsWith(str)) { - return this.substring(0, this.length - str.length); - } - return this; - }; - } + /** trims the end of the string*/ + String.prototype.trimEnd = function (str) { + if (this.endsWith(str)) { + return this.substring(0, this.length - str.length); + } + return this; + }; if (!String.prototype.utf8Encode) { @@ -332,4 +326,4 @@ } -})(); \ No newline at end of file +})(); From fbc9c6aed630758222a1750ca47045af49ef8123 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 20:06:34 +0200 Subject: [PATCH 05/58] Fixes even more (hopefully all) unit tests --- .../UmbracoSettings/umbracoSettings.config | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config index a89a6e4d71..5f5d47e8ba 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config @@ -222,13 +222,6 @@ - - - - - - - @@ -256,4 +249,4 @@ internalRedirectPreservesTemplate="false"> - \ No newline at end of file + From 6d6be4e6a42a34293c67aea3accdf658c99f0a44 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Thu, 19 Apr 2018 20:29:46 +0200 Subject: [PATCH 06/58] Fixes last failing test --- src/Umbraco.Tests/Plugins/PluginManagerTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs index 22d150ac3b..970259618a 100644 --- a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs +++ b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs @@ -300,7 +300,7 @@ AnotherContentFinder public void Resolves_Trees() { var trees = _manager.ResolveTrees(); - Assert.AreEqual(35, trees.Count()); + Assert.AreEqual(34, trees.Count()); } [Test] From 7d349ef51830664e65b70b00ddf4482da14788a4 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 20 Apr 2018 17:40:01 +1000 Subject: [PATCH 07/58] Replaces instances of UmbracoTemplatePage with UmbracoViewPage --- src/Umbraco.Core/IO/ViewHelper.cs | 7 +++---- src/Umbraco.Core/Services/Implement/FileService.cs | 4 ++-- .../Repositories/TemplateRepositoryTest.cs | 4 ++-- .../Services/Importing/PackageImportTests.cs | 2 +- src/Umbraco.Tests/Templates/ViewHelperTests.cs | 14 +++++++------- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 1 + .../umbraco_client/PunyCode/punycode.min.js | 2 ++ src/Umbraco.Web/HtmlHelperRenderExtensions.cs | 2 +- 8 files changed, 19 insertions(+), 17 deletions(-) create mode 100644 src/Umbraco.Web.UI/umbraco_client/PunyCode/punycode.min.js diff --git a/src/Umbraco.Core/IO/ViewHelper.cs b/src/Umbraco.Core/IO/ViewHelper.cs index 1645355b72..63f7504f18 100644 --- a/src/Umbraco.Core/IO/ViewHelper.cs +++ b/src/Umbraco.Core/IO/ViewHelper.cs @@ -67,10 +67,9 @@ namespace Umbraco.Core.IO modelNamespaceAlias = "ContentModels"; // either - // @inherits Umbraco.Web.Mvc.UmbracoTemplatePage - // @inherits Umbraco.Web.Mvc.UmbracoTemplatePage - // @inherits Umbraco.Web.Mvc.UmbracoTemplatePage - content.Append("@inherits Umbraco.Web.Mvc.UmbracoTemplatePage"); + // @inherits Umbraco.Web.Mvc.UmbracoViewPage + // @inherits Umbraco.Web.Mvc.UmbracoViewPage + content.Append("@inherits Umbraco.Web.Mvc.UmbracoViewPage"); if (modelClassName.IsNullOrWhiteSpace() == false) { content.Append("<"); diff --git a/src/Umbraco.Core/Services/Implement/FileService.cs b/src/Umbraco.Core/Services/Implement/FileService.cs index 23a4cddc55..8c1fa53880 100644 --- a/src/Umbraco.Core/Services/Implement/FileService.cs +++ b/src/Umbraco.Core/Services/Implement/FileService.cs @@ -27,7 +27,7 @@ namespace Umbraco.Core.Services.Implement private readonly IXsltFileRepository _xsltRepository; private readonly IAuditRepository _auditRepository; - private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage"; + private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoViewPage"; private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage"; public FileService(IScopeProvider uowProvider, ILogger logger, IEventMessagesFactory eventMessagesFactory, @@ -1182,4 +1182,4 @@ namespace Umbraco.Core.Services.Implement #endregion } -} \ No newline at end of file +} diff --git a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs index e288bc5eaf..39128eb60a 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/TemplateRepositoryTest.cs @@ -178,7 +178,7 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(repository.Get("test"), Is.Not.Null); Assert.That(_viewsFileSystem.FileExists("test.cshtml"), Is.True); Assert.AreEqual( - @"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = null;}".StripWhitespace(), + @"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = null;}".StripWhitespace(), template.Content.StripWhitespace()); } @@ -208,7 +208,7 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(repository.Get("test2"), Is.Not.Null); Assert.That(_viewsFileSystem.FileExists("test2.cshtml"), Is.True); Assert.AreEqual( - "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = \"test.cshtml\";}".StripWhitespace(), + "@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = \"test.cshtml\";}".StripWhitespace(), template2.Content.StripWhitespace()); } } diff --git a/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs b/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs index 1333ca9f57..a810d4c644 100644 --- a/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs +++ b/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs @@ -189,7 +189,7 @@ namespace Umbraco.Tests.Services.Importing Assert.That(templates.Count(), Is.EqualTo(numberOfTemplates)); Assert.AreEqual(init + numberOfTemplates, allTemplates.Count()); - Assert.IsTrue(allTemplates.All(x => x.Content.Contains("UmbracoTemplatePage"))); + Assert.IsTrue(allTemplates.All(x => x.Content.Contains("UmbracoViewPage"))); } [Test] diff --git a/src/Umbraco.Tests/Templates/ViewHelperTests.cs b/src/Umbraco.Tests/Templates/ViewHelperTests.cs index 5bd7733920..ee7264eaec 100644 --- a/src/Umbraco.Tests/Templates/ViewHelperTests.cs +++ b/src/Umbraco.Tests/Templates/ViewHelperTests.cs @@ -10,7 +10,7 @@ namespace Umbraco.Tests.Templates public void NoOptions() { var view = ViewHelper.GetDefaultFileContent(); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = null; }"), FixView(view)); @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Templates public void Layout() { var view = ViewHelper.GetDefaultFileContent(layoutPageAlias: "Dharznoik"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = ""Dharznoik.cshtml""; }"), FixView(view)); @@ -30,7 +30,7 @@ namespace Umbraco.Tests.Templates public void ClassName() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = null; }"), FixView(view)); @@ -40,7 +40,7 @@ namespace Umbraco.Tests.Templates public void Namespace() { var view = ViewHelper.GetDefaultFileContent(modelNamespace: "Models"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @{ Layout = null; }"), FixView(view)); @@ -50,7 +50,7 @@ namespace Umbraco.Tests.Templates public void ClassNameAndNamespace() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName", modelNamespace: "My.Models"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @using ContentModels = My.Models; @{ Layout = null; @@ -61,7 +61,7 @@ namespace Umbraco.Tests.Templates public void ClassNameAndNamespaceAndAlias() { var view = ViewHelper.GetDefaultFileContent(modelClassName: "ClassName", modelNamespace: "My.Models", modelNamespaceAlias: "MyModels"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @using MyModels = My.Models; @{ Layout = null; @@ -72,7 +72,7 @@ namespace Umbraco.Tests.Templates public void Combined() { var view = ViewHelper.GetDefaultFileContent(layoutPageAlias: "Dharznoik", modelClassName: "ClassName", modelNamespace: "My.Models", modelNamespaceAlias: "MyModels"); - Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoTemplatePage + Assert.AreEqual(FixView(@"@inherits Umbraco.Web.Mvc.UmbracoViewPage @using MyModels = My.Models; @{ Layout = ""Dharznoik.cshtml""; diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 0d8d4f48d0..00a698a4d1 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -401,6 +401,7 @@ + diff --git a/src/Umbraco.Web.UI/umbraco_client/PunyCode/punycode.min.js b/src/Umbraco.Web.UI/umbraco_client/PunyCode/punycode.min.js new file mode 100644 index 0000000000..e14359fbaf --- /dev/null +++ b/src/Umbraco.Web.UI/umbraco_client/PunyCode/punycode.min.js @@ -0,0 +1,2 @@ +/*! https://mths.be/punycode v1.3.2 by @mathias */ +!function(a){function b(a){throw RangeError(E[a])}function c(a,b){for(var c=a.length,d=[];c--;)d[c]=b(a[c]);return d}function d(a,b){var d=a.split("@"),e="";d.length>1&&(e=d[0]+"@",a=d[1]),a=a.replace(D,".");var f=a.split("."),g=c(f,b).join(".");return e+g}function e(a){for(var b,c,d=[],e=0,f=a.length;f>e;)b=a.charCodeAt(e++),b>=55296&&56319>=b&&f>e?(c=a.charCodeAt(e++),56320==(64512&c)?d.push(((1023&b)<<10)+(1023&c)+65536):(d.push(b),e--)):d.push(b);return d}function f(a){return c(a,function(a){var b="";return a>65535&&(a-=65536,b+=H(a>>>10&1023|55296),a=56320|1023&a),b+=H(a)}).join("")}function g(a){return 10>a-48?a-22:26>a-65?a-65:26>a-97?a-97:t}function h(a,b){return a+22+75*(26>a)-((0!=b)<<5)}function i(a,b,c){var d=0;for(a=c?G(a/x):a>>1,a+=G(a/b);a>F*v>>1;d+=t)a=G(a/F);return G(d+(F+1)*a/(a+w))}function j(a){var c,d,e,h,j,k,l,m,n,o,p=[],q=a.length,r=0,w=z,x=y;for(d=a.lastIndexOf(A),0>d&&(d=0),e=0;d>e;++e)a.charCodeAt(e)>=128&&b("not-basic"),p.push(a.charCodeAt(e));for(h=d>0?d+1:0;q>h;){for(j=r,k=1,l=t;h>=q&&b("invalid-input"),m=g(a.charCodeAt(h++)),(m>=t||m>G((s-r)/k))&&b("overflow"),r+=m*k,n=x>=l?u:l>=x+v?v:l-x,!(n>m);l+=t)o=t-n,k>G(s/o)&&b("overflow"),k*=o;c=p.length+1,x=i(r-j,c,0==j),G(r/c)>s-w&&b("overflow"),w+=G(r/c),r%=c,p.splice(r++,0,w)}return f(p)}function k(a){var c,d,f,g,j,k,l,m,n,o,p,q,r,w,x,B=[];for(a=e(a),q=a.length,c=z,d=0,j=y,k=0;q>k;++k)p=a[k],128>p&&B.push(H(p));for(f=g=B.length,g&&B.push(A);q>f;){for(l=s,k=0;q>k;++k)p=a[k],p>=c&&l>p&&(l=p);for(r=f+1,l-c>G((s-d)/r)&&b("overflow"),d+=(l-c)*r,c=l,k=0;q>k;++k)if(p=a[k],c>p&&++d>s&&b("overflow"),p==c){for(m=d,n=t;o=j>=n?u:n>=j+v?v:n-j,!(o>m);n+=t)x=m-o,w=t-o,B.push(H(h(o+x%w,0))),m=G(x/w);B.push(H(h(m,0))),j=i(d,r,f==g),d=0,++f}++d,++c}return B.join("")}function l(a){return d(a,function(a){return B.test(a)?j(a.slice(4).toLowerCase()):a})}function m(a){return d(a,function(a){return C.test(a)?"xn--"+k(a):a})}var n="object"==typeof exports&&exports&&!exports.nodeType&&exports,o="object"==typeof module&&module&&!module.nodeType&&module,p="object"==typeof global&&global;(p.global===p||p.window===p||p.self===p)&&(a=p);var q,r,s=2147483647,t=36,u=1,v=26,w=38,x=700,y=72,z=128,A="-",B=/^xn--/,C=/[^\x20-\x7E]/,D=/[\x2E\u3002\uFF0E\uFF61]/g,E={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},F=t-u,G=Math.floor,H=String.fromCharCode;if(q={version:"1.3.2",ucs2:{decode:e,encode:f},decode:j,encode:k,toASCII:m,toUnicode:l},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return q});else if(n&&o)if(module.exports==n)o.exports=q;else for(r in q)q.hasOwnProperty(r)&&(n[r]=q[r]);else a.punycode=q}(this); \ No newline at end of file diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index dd34dea6b5..1615dec94e 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -55,7 +55,7 @@ namespace Umbraco.Web /// /// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are - /// using does not inherit from UmbracoTemplatePage + /// using does not inherit from UmbracoViewPage /// /// /// From 861e5908a736c6dcb5ed6236834f3a0c486cdf46 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Fri, 20 Apr 2018 10:35:21 +0200 Subject: [PATCH 08/58] U4-11253 New Chrome 66 trimStart function is overriding the Umbraco Core trimStart polyfill --- .../lib/umbraco/Extensions.js | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js index b70a6b12bc..e8c6eda4bc 100644 --- a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js +++ b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js @@ -84,27 +84,21 @@ }; } - if (!String.prototype.trimStart) { - - /** trims the start of the string*/ - String.prototype.trimStart = function (str) { - if (this.startsWith(str)) { - return this.substring(str.length); - } - return this; - }; - } - - if (!String.prototype.trimEnd) { + /** trims the start of the string*/ + String.prototype.trimStart = function (str) { + if (this.startsWith(str)) { + return this.substring(str.length); + } + return this; + }; - /** trims the end of the string*/ - String.prototype.trimEnd = function (str) { - if (this.endsWith(str)) { - return this.substring(0, this.length - str.length); - } - return this; - }; - } + /** trims the end of the string*/ + String.prototype.trimEnd = function (str) { + if (this.endsWith(str)) { + return this.substring(0, this.length - str.length); + } + return this; + }; if (!String.prototype.utf8Encode) { @@ -332,4 +326,4 @@ } -})(); \ No newline at end of file +})(); From 4a0cd87a38aa82840dd7cc3260fca8e8c9165a3d Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Fri, 20 Apr 2018 10:51:28 +0200 Subject: [PATCH 09/58] U4-11253 New Chrome 66 trimStart function is overriding the Umbraco Core trimStart polyfill --- .../lib/umbraco/Extensions.js | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js index b70a6b12bc..e8c6eda4bc 100644 --- a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js +++ b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js @@ -84,27 +84,21 @@ }; } - if (!String.prototype.trimStart) { - - /** trims the start of the string*/ - String.prototype.trimStart = function (str) { - if (this.startsWith(str)) { - return this.substring(str.length); - } - return this; - }; - } - - if (!String.prototype.trimEnd) { + /** trims the start of the string*/ + String.prototype.trimStart = function (str) { + if (this.startsWith(str)) { + return this.substring(str.length); + } + return this; + }; - /** trims the end of the string*/ - String.prototype.trimEnd = function (str) { - if (this.endsWith(str)) { - return this.substring(0, this.length - str.length); - } - return this; - }; - } + /** trims the end of the string*/ + String.prototype.trimEnd = function (str) { + if (this.endsWith(str)) { + return this.substring(0, this.length - str.length); + } + return this; + }; if (!String.prototype.utf8Encode) { @@ -332,4 +326,4 @@ } -})(); \ No newline at end of file +})(); From 7a181bd281b4874e6a7f2e31dbbad718efbebf02 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Fri, 20 Apr 2018 10:59:13 +0200 Subject: [PATCH 10/58] Bump version to 7.8.3 --- src/SolutionInfo.cs | 4 ++-- src/Umbraco.Core/Configuration/UmbracoVersion.cs | 2 +- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/SolutionInfo.cs b/src/SolutionInfo.cs index e39fd33eb2..8a8fce9d31 100644 --- a/src/SolutionInfo.cs +++ b/src/SolutionInfo.cs @@ -11,5 +11,5 @@ using System.Resources; [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyFileVersion("7.8.2")] -[assembly: AssemblyInformationalVersion("7.8.2")] \ No newline at end of file +[assembly: AssemblyFileVersion("7.8.3")] +[assembly: AssemblyInformationalVersion("7.8.3")] \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoVersion.cs b/src/Umbraco.Core/Configuration/UmbracoVersion.cs index 1025d97c3d..9f3a8441bd 100644 --- a/src/Umbraco.Core/Configuration/UmbracoVersion.cs +++ b/src/Umbraco.Core/Configuration/UmbracoVersion.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration { public class UmbracoVersion { - private static readonly Version Version = new Version("7.8.2"); + private static readonly Version Version = new Version("7.8.3"); /// /// Gets the current version of Umbraco. diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 6b39c6ca05..d950779916 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -1024,9 +1024,9 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" True True - 7820 + 7830 / - http://localhost:7820 + http://localhost:7830 7800 / http://localhost:7800 From 27f6560a00c53ef389f7d808398298a372954101 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Fri, 20 Apr 2018 11:00:49 +0200 Subject: [PATCH 11/58] U4-11253 New Chrome 66 trimStart function is overriding the Umbraco Core trimStart polyfill --- .../lib/umbraco/Extensions.js | 36 ++++++++----------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js index b70a6b12bc..e8c6eda4bc 100644 --- a/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js +++ b/src/Umbraco.Web.UI.Client/lib/umbraco/Extensions.js @@ -84,27 +84,21 @@ }; } - if (!String.prototype.trimStart) { - - /** trims the start of the string*/ - String.prototype.trimStart = function (str) { - if (this.startsWith(str)) { - return this.substring(str.length); - } - return this; - }; - } - - if (!String.prototype.trimEnd) { + /** trims the start of the string*/ + String.prototype.trimStart = function (str) { + if (this.startsWith(str)) { + return this.substring(str.length); + } + return this; + }; - /** trims the end of the string*/ - String.prototype.trimEnd = function (str) { - if (this.endsWith(str)) { - return this.substring(0, this.length - str.length); - } - return this; - }; - } + /** trims the end of the string*/ + String.prototype.trimEnd = function (str) { + if (this.endsWith(str)) { + return this.substring(0, this.length - str.length); + } + return this; + }; if (!String.prototype.utf8Encode) { @@ -332,4 +326,4 @@ } -})(); \ No newline at end of file +})(); From f1a8da2876efeea2594a32513348c5d294e4d1a5 Mon Sep 17 00:00:00 2001 From: Sebastiaan Janssen Date: Fri, 20 Apr 2018 11:02:29 +0200 Subject: [PATCH 12/58] Bumps version to 7.9.6 --- src/SolutionInfo.cs | 4 ++-- src/Umbraco.Core/Configuration/UmbracoVersion.cs | 2 +- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/SolutionInfo.cs b/src/SolutionInfo.cs index 71cecfdde2..87ea10b16c 100644 --- a/src/SolutionInfo.cs +++ b/src/SolutionInfo.cs @@ -11,5 +11,5 @@ using System.Resources; [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyFileVersion("7.9.5")] -[assembly: AssemblyInformationalVersion("7.9.5")] \ No newline at end of file +[assembly: AssemblyFileVersion("7.9.6")] +[assembly: AssemblyInformationalVersion("7.9.6")] \ No newline at end of file diff --git a/src/Umbraco.Core/Configuration/UmbracoVersion.cs b/src/Umbraco.Core/Configuration/UmbracoVersion.cs index b9b797aebb..87a5643816 100644 --- a/src/Umbraco.Core/Configuration/UmbracoVersion.cs +++ b/src/Umbraco.Core/Configuration/UmbracoVersion.cs @@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration { public class UmbracoVersion { - private static readonly Version Version = new Version("7.9.5"); + private static readonly Version Version = new Version("7.9.6"); /// /// Gets the current version of Umbraco. diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index b680b09c71..73bb070862 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -1023,9 +1023,9 @@ xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" True True - 7950 + 7960 / - http://localhost:7950 + http://localhost:7960 False False From 48641166b944f046f754b03961d7370774b1f1c4 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 01:31:01 +1000 Subject: [PATCH 13/58] WIP - gets 'inbound' routing working to generate culture specific URLs --- .../PublishedContent/IPublishedContent.cs | 10 +-- .../PublishedContentWrapped.cs | 4 +- .../PublishedContent/PublishedCultureName.cs | 19 ++++++ .../Persistence/Dtos/ContentNuDto.cs | 6 ++ src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../Published/NestedContentTests.cs | 1 + .../Published/PublishedSnapshotTestObjects.cs | 1 + .../PublishedContentDataTableTests.cs | 3 +- .../PublishedContentTestElements.cs | 7 +- .../TestControllerActivatorBase.cs | 2 +- .../Testing/TestingTests/MockTests.cs | 2 +- .../Web/TemplateUtilitiesTests.cs | 2 +- .../Models/PublishedContentBase.cs | 4 +- .../ContentPickerValueConverter.cs | 1 + .../MediaPickerValueConverter.cs | 2 + .../MultiNodeTreePickerValueConverter.cs | 2 + .../PublishedCache/IPublishedContentCache.cs | 4 +- .../PublishedCache/NuCache/CacheKeys.cs | 10 ++- .../PublishedCache/NuCache/ContentCache.cs | 34 +++++++--- .../NuCache/DataSource/BTree.cs | 68 ++++++++++++++++++- .../NuCache/DataSource/ContentData.cs | 6 ++ .../DataSource/ContentSerializedData.cs | 17 +++++ .../NuCache/DataSource/CultureVariation.cs | 15 ++++ .../NuCache/DataSource/Database.cs | 19 ++++-- .../NuCache/PublishedContent.cs | 37 +++++++--- .../NuCache/PublishedSnapshotService.cs | 42 +++++++++--- .../PublishedCache/PublishedMember.cs | 2 + .../PublishedContentCache.cs | 6 +- .../XmlPublishedCache/PublishedMediaCache.cs | 2 + .../XmlPublishedCache/XmlPublishedContent.cs | 4 +- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 62 ++++++++++------- .../Routing/CustomRouteUrlProvider.cs | 2 +- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 4 +- src/Umbraco.Web/Routing/IUrlProvider.cs | 2 +- src/Umbraco.Web/Umbraco.Web.csproj | 2 + src/Umbraco.Web/umbraco.presentation/page.cs | 30 +++++++- 36 files changed, 350 insertions(+), 85 deletions(-) create mode 100644 src/Umbraco.Core/Models/PublishedContent/PublishedCultureName.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/CultureVariation.cs diff --git a/src/Umbraco.Core/Models/PublishedContent/IPublishedContent.cs b/src/Umbraco.Core/Models/PublishedContent/IPublishedContent.cs index f114d94116..f75e59bee0 100644 --- a/src/Umbraco.Core/Models/PublishedContent/IPublishedContent.cs +++ b/src/Umbraco.Core/Models/PublishedContent/IPublishedContent.cs @@ -3,17 +3,11 @@ using System.Collections.Generic; namespace Umbraco.Core.Models.PublishedContent { + /// /// /// Represents a cached content. /// - /// - /// SD: A replacement for INode which needs to occur since INode doesn't contain the document type alias - /// and INode is poorly formatted with mutable properties (i.e. Lists instead of IEnumerable). - /// Stephan: initially, that was for cached published content only. Now, we're using it also for - /// cached preview (so, maybe unpublished) content. A better name would therefore be ICachedContent, as - /// has been suggested. However, can't change now. Maybe in v7? - /// public interface IPublishedContent : IPublishedElement { #region Content @@ -38,6 +32,8 @@ namespace Umbraco.Core.Models.PublishedContent int Level { get; } string Url { get; } + IReadOnlyDictionary CultureNames { get; } + /// /// Gets a value indicating whether the content is a content (aka a document) or a media. /// diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedContentWrapped.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedContentWrapped.cs index a30726012e..528a545f8f 100644 --- a/src/Umbraco.Core/Models/PublishedContent/PublishedContentWrapped.cs +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedContentWrapped.cs @@ -54,7 +54,9 @@ namespace Umbraco.Core.Models.PublishedContent public virtual int SortOrder => _content.SortOrder; - public virtual string Name => _content.Name; + public virtual string Name => _content.Name; + + public virtual IReadOnlyDictionary CultureNames => _content.CultureNames; public virtual string UrlName => _content.UrlName; diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedCultureName.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedCultureName.cs new file mode 100644 index 0000000000..59ac875aa4 --- /dev/null +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedCultureName.cs @@ -0,0 +1,19 @@ +using System; + +namespace Umbraco.Core.Models.PublishedContent +{ + /// + /// Contains the culture specific data for a item + /// + public struct PublishedCultureName + { + public PublishedCultureName(string name, string urlName) : this() + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + UrlName = urlName ?? throw new ArgumentNullException(nameof(urlName)); + } + + public string Name { get; } + public string UrlName { get; } + } +} diff --git a/src/Umbraco.Core/Persistence/Dtos/ContentNuDto.cs b/src/Umbraco.Core/Persistence/Dtos/ContentNuDto.cs index f427c5aa4a..eea3d5d537 100644 --- a/src/Umbraco.Core/Persistence/Dtos/ContentNuDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/ContentNuDto.cs @@ -16,6 +16,12 @@ namespace Umbraco.Core.Persistence.Dtos [Column("published")] public bool Published { get; set; } + /// + /// Stores serialized JSON representing the content item's property and culture name values + /// + /// + /// Pretty much anything that would require a 1:M lookup is serialized here + /// [Column("data")] [SpecialDbType(SpecialDbTypes.NTEXT)] public string Data { get; set; } diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 77b78f355d..c8f4ed577d 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -365,6 +365,7 @@ + diff --git a/src/Umbraco.Tests/Published/NestedContentTests.cs b/src/Umbraco.Tests/Published/NestedContentTests.cs index a916a2d51e..b097358fc3 100644 --- a/src/Umbraco.Tests/Published/NestedContentTests.cs +++ b/src/Umbraco.Tests/Published/NestedContentTests.cs @@ -273,6 +273,7 @@ namespace Umbraco.Tests.Published public override int TemplateId { get; } public override int SortOrder { get; } public override string Name { get; } + public override IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public override string UrlName { get; } public override string DocumentTypeAlias { get; } public override int DocumentTypeId { get; } diff --git a/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs b/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs index 48495b2ae7..acfc12d408 100644 --- a/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs +++ b/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs @@ -66,6 +66,7 @@ namespace Umbraco.Tests.Published public int TemplateId { get; set; } public int SortOrder { get; set; } public string Name { get; set; } + public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public string UrlName { get; set; } public string DocumentTypeAlias => ContentType.Alias; public int DocumentTypeId { get; set; } diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs index 6e7bae28a6..4668a86c78 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentDataTableTests.cs @@ -200,7 +200,8 @@ namespace Umbraco.Tests.PublishedContent public Guid Key { get; set; } public int TemplateId { get; set; } public int SortOrder { get; set; } - public string Name { get; set; } + public string Name { get; set; } + public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public string UrlName { get; set; } public string DocumentTypeAlias { get; set; } public int DocumentTypeId { get; set; } diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs index 8f6ee5c2b1..9241686188 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs @@ -68,12 +68,12 @@ namespace Umbraco.Tests.PublishedContent throw new NotImplementedException(); } - public string GetRouteById(bool preview, int contentId) + public string GetRouteById(bool preview, int contentId, string language = null) { throw new NotImplementedException(); } - public string GetRouteById(int contentId) + public string GetRouteById(int contentId, string language = null) { throw new NotImplementedException(); } @@ -176,7 +176,8 @@ namespace Umbraco.Tests.PublishedContent public Guid Key { get; set; } public int TemplateId { get; set; } public int SortOrder { get; set; } - public string Name { get; set; } + public string Name { get; set; } + public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public string UrlName { get; set; } public string DocumentTypeAlias { get; private set; } public int DocumentTypeId { get; private set; } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 0b3e5d6efd..7a8188cd0b 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 true); //replace it var urlHelper = new Mock(); - urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var membershipHelper = new MembershipHelper(umbCtx, Mock.Of(), Mock.Of()); diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index b6a5d982c4..580defd5ab 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -73,7 +73,7 @@ namespace Umbraco.Tests.Testing.TestingTests var umbracoContext = TestObjects.GetUmbracoContextMock(); var urlProviderMock = new Mock(); - urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var urlProvider = urlProviderMock.Object; diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index 8b52ce1893..e6a5dd8438 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -72,7 +72,7 @@ namespace Umbraco.Tests.Web //setup a mock url provider which we'll use fo rtesting var testUrlProvider = new Mock(); - testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode) => { return "/my-test-url"; diff --git a/src/Umbraco.Web/Models/PublishedContentBase.cs b/src/Umbraco.Web/Models/PublishedContentBase.cs index 89a735688c..a89cab2c65 100644 --- a/src/Umbraco.Web/Models/PublishedContentBase.cs +++ b/src/Umbraco.Web/Models/PublishedContentBase.cs @@ -93,7 +93,9 @@ namespace Umbraco.Web.Models public abstract Guid Key { get; } public abstract int TemplateId { get; } public abstract int SortOrder { get; } - public abstract string Name { get; } + public abstract string Name { get; } + //TODO: On the base ContentData instance this dictionary contains a CultureVariation, should we expose that model here or a different model? + public abstract IReadOnlyDictionary CultureNames { get; } public abstract string UrlName { get; } public abstract string DocumentTypeAlias { get; } public abstract int DocumentTypeId { get; } diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/ContentPickerValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/ContentPickerValueConverter.cs index ce3fef228f..b9cac88ecf 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/ContentPickerValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/ContentPickerValueConverter.cs @@ -75,6 +75,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters public override object ConvertIntermediateToXPath(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { + if (inter == null) return null; return inter.ToString(); } } diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs index 9e9e61cb05..f2873e9466 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs @@ -42,6 +42,8 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { + if (source == null) return null; + var nodeIds = source.ToString() .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(Udi.Parse) diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs index 42fc63011b..50ebe35d11 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs @@ -46,6 +46,8 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { + if (source == null) return null; + if (propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.MultiNodeTreePicker)) { var nodeIds = source.ToString() diff --git a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs index e033647fdf..64fa5efde4 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// The value of overrides defaults. - string GetRouteById(bool preview, int contentId); + string GetRouteById(bool preview, int contentId, string language = null); /// /// Gets the route for a content identified by its unique identifier. @@ -47,6 +47,6 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// Considers published or unpublished content depending on defaults. - string GetRouteById(int contentId); + string GetRouteById(int contentId, string language = null); } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs index a3168732e4..6d21fedb6d 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs @@ -11,6 +11,12 @@ namespace Umbraco.Web.PublishedCache.NuCache return previewing ? "D:" : "P:"; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static string LangId(string language) + { + return language != null ? ("-L:" + language) : string.Empty; + } + public static string PublishedContentChildren(Guid contentUid, bool previewing) { return "NuCache.Content.Children[" + DraftOrPub(previewing) + ":" + contentUid + "]"; @@ -50,9 +56,9 @@ namespace Umbraco.Web.PublishedCache.NuCache // a valid ID in the database at that point, whereas content and properties // may be virtual (and not in umbracoNode). - public static string ContentCacheRouteByContent(int id, bool previewing) + public static string ContentCacheRouteByContent(int id, bool previewing, string language) { - return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + "]"; + return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + LangId(language) + "]"; } public static string ContentCacheContentByRoute(string route, bool previewing) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index 3907c4c79c..f27d2c9937 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -25,10 +25,11 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly ICacheProvider _elementsCache; private readonly DomainHelper _domainHelper; private readonly IGlobalSettings _globalSettings; + private readonly ILocalizationService _localizationService; #region Constructor - public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings) + public ContentCache(bool previewDefault, ContentStore.Snapshot snapshot, ICacheProvider snapshotCache, ICacheProvider elementsCache, DomainHelper domainHelper, IGlobalSettings globalSettings, ILocalizationService localizationService) : base(previewDefault) { _snapshot = snapshot; @@ -36,6 +37,7 @@ namespace Umbraco.Web.PublishedCache.NuCache _elementsCache = elementsCache; _domainHelper = domainHelper; _globalSettings = globalSettings; + _localizationService = localizationService; } private bool HideTopLevelNodeFromPath => _globalSettings.HideTopLevelNodeFromPath; @@ -118,19 +120,19 @@ namespace Umbraco.Web.PublishedCache.NuCache return content; } - public string GetRouteById(int contentId) + public string GetRouteById(int contentId, string language = null) { - return GetRouteById(PreviewDefault, contentId); + return GetRouteById(PreviewDefault, contentId, language); } - public string GetRouteById(bool preview, int contentId) + public string GetRouteById(bool preview, int contentId, string language = null) { var cache = (preview == false || PublishedSnapshotService.FullCacheWhenPreviewing) ? _elementsCache : _snapshotCache; - var key = CacheKeys.ContentCacheRouteByContent(contentId, preview); - return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null)); + var key = CacheKeys.ContentCacheRouteByContent(contentId, preview, language); + return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null, language)); } - private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode) + private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, string language) { var node = GetById(preview, contentId); if (node == null) @@ -146,7 +148,23 @@ namespace Umbraco.Web.PublishedCache.NuCache while (hasDomains == false && n != null) // n is null at root { // get the url - var urlName = n.UrlName; + string urlName; + if (n.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) + { + var cultureCode = language != null + ? language + : _localizationService.GetDefaultVariantLanguage()?.IsoCode; + + if (n.CultureNames.TryGetValue(cultureCode, out var cultureName)) + urlName = cultureName.UrlName; + else + urlName = n.UrlName; //couldn't get the value, fallback to invariant ... not sure what else to do + } + else + { + urlName = n.UrlName; + } + pathParts.Add(urlName); // move to parent node diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs index 6fd731cbee..29b252cd92 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs @@ -83,6 +83,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource class ContentDataSerializer : ISerializer { private static readonly DictionaryOfPropertyDataSerializer PropertiesSerializer = new DictionaryOfPropertyDataSerializer(); + private static readonly DictionaryOfCultureVariationSerializer CultureVariationsSerializer = new DictionaryOfCultureVariationSerializer(); public ContentData ReadFrom(Stream stream) { @@ -94,7 +95,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionDate = PrimitiveSerializer.DateTime.ReadFrom(stream), WriterId = PrimitiveSerializer.Int32.ReadFrom(stream), TemplateId = PrimitiveSerializer.Int32.ReadFrom(stream), - Properties = PropertiesSerializer.ReadFrom(stream) + Properties = PropertiesSerializer.ReadFrom(stream), + CultureInfos = CultureVariationsSerializer.ReadFrom(stream) }; } @@ -107,6 +109,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource PrimitiveSerializer.Int32.WriteTo(value.WriterId, stream); PrimitiveSerializer.Int32.WriteTo(value.TemplateId, stream); PropertiesSerializer.WriteTo(value.Properties, stream); + CultureVariationsSerializer.WriteTo(value.CultureInfos, stream); } } @@ -131,6 +134,69 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } */ + private class DictionaryOfCultureVariationSerializer : ISerializer> + { + public IReadOnlyDictionary ReadFrom(Stream stream) + { + var dict = new Dictionary(); + + // read values count + var pcount = PrimitiveSerializer.Int32.ReadFrom(stream); + + // read each property + for (var i = 0; i < pcount; i++) + { + // read lang id + // fixme: This will need to change to string when stephane is done his culture work + var key = PrimitiveSerializer.String.ReadFrom(stream); + + var val = new CultureVariation(); + + // read variation info + //TODO: This is supporting multiple properties but we only have one currently + var type = PrimitiveSerializer.Char.ReadFrom(stream); + switch(type) + { + case 'N': + val.Name = PrimitiveSerializer.String.ReadFrom(stream); + break; + default: + throw new ArgumentOutOfRangeException(); + } + + dict[key] = val; + } + return dict; + } + + private static readonly IReadOnlyDictionary Empty = new Dictionary(); + + public void WriteTo(IReadOnlyDictionary value, Stream stream) + { + var valToSerialize = value; + if (valToSerialize == null) + { + valToSerialize = Empty; + } + + // write values count + PrimitiveSerializer.Int32.WriteTo(valToSerialize.Count, stream); + + // write each name + foreach (var kvp in valToSerialize) + { + // write alias + PrimitiveSerializer.String.WriteTo(kvp.Key, stream); + + // write name + PrimitiveSerializer.Char.WriteTo('N', stream); + PrimitiveSerializer.String.WriteTo(kvp.Value.Name, stream); + //TODO: This is supporting multiple properties but we only have one currently + } + } + + } + private class DictionaryOfPropertyDataSerializer : ISerializer> { public IDictionary ReadFrom(Stream stream) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentData.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentData.cs index 2b8fd108b2..6841937c14 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentData.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentData.cs @@ -8,8 +8,14 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource { public bool Published { get; set; } + /// + /// The collection of language Id to name for the content item + /// + public IReadOnlyDictionary CultureInfos { get; set; } + public string Name { get; set; } public int VersionId { get; set; } + //TODO: This will not make a lot of sense since we'll have dates for each variant publishing, need to wait on Stephane public DateTime VersionDate { get; set; } public int WriterId { get; set; } public int TemplateId { get; set; } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs new file mode 100644 index 0000000000..b2cb22a74b --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs @@ -0,0 +1,17 @@ +using Newtonsoft.Json; +using System.Collections.Generic; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + /// + /// The content item 1:M data that is serialized to JSON + /// + internal class ContentSerializedData + { + [JsonProperty("properties")] + public Dictionary PropertyData { get; set; } + + [JsonProperty("cultureData")] + public Dictionary CultureData { get; set; } + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/CultureVariation.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/CultureVariation.cs new file mode 100644 index 0000000000..aad416a925 --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/CultureVariation.cs @@ -0,0 +1,15 @@ +using Newtonsoft.Json; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + /// + /// Represents the culture variation information on a content item + /// + internal class CultureVariation + { + [JsonProperty("name")] + public string Name { get; set; } + + //TODO: We may want some date stamps here + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs index b4b93e799a..2c4249cd08 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs @@ -190,6 +190,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } else { + var deserialized = DeserializeData(dto.EditData); + d = new ContentData { Name = dto.EditName, @@ -198,7 +200,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.EditVersionDate, WriterId = dto.EditWriterId, - Properties = DeserializeData(dto.EditData) + Properties = deserialized.PropertyData, + CultureInfos = deserialized.CultureData }; } @@ -212,6 +215,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } else { + var deserialized = DeserializeData(dto.PubData); + p = new ContentData { Name = dto.PubName, @@ -220,7 +225,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.PubVersionDate, WriterId = dto.PubWriterId, - Properties = DeserializeData(dto.PubData) + Properties = deserialized.PropertyData, + CultureInfos = deserialized.CultureData }; } } @@ -244,6 +250,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource if (dto.EditData == null) throw new Exception("No data for media " + dto.Id); + var deserialized = DeserializeData(dto.EditData); + var p = new ContentData { Name = dto.EditName, @@ -252,7 +260,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.EditVersionDate, WriterId = dto.CreatorId, // what-else? - Properties = DeserializeData(dto.EditData) + Properties = deserialized.PropertyData, + CultureInfos = deserialized.CultureData }; var n = new ContentNode(dto.Id, dto.Uid, @@ -268,7 +277,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource return s; } - private static Dictionary DeserializeData(string data) + private static ContentSerializedData DeserializeData(string data) { // by default JsonConvert will deserialize our numeric values as Int64 // which is bad, because they were Int32 in the database - take care @@ -278,7 +287,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource Converters = new List { new ForceInt32Converter() } }; - return JsonConvert.DeserializeObject>(data, settings); + return JsonConvert.DeserializeObject(data, settings); } } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 558580d7c0..acfc5bdd31 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web.Composing; using Umbraco.Web.Models; @@ -18,6 +19,7 @@ namespace Umbraco.Web.PublishedCache.NuCache internal readonly ContentData _contentData; // internal for ContentNode cloning private readonly string _urlName; + private IReadOnlyDictionary _cultureNames; #region Constructors @@ -44,7 +46,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var cache = GetCurrentSnapshotCache(); return cache == null ? GetProfileNameByIdNoCache(id) - : (string) cache.GetCacheItem(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); + : (string)cache.GetCacheItem(CacheKeys.ProfileName(id), () => GetProfileNameByIdNoCache(id)); } private static string GetProfileNameByIdNoCache(int id) @@ -88,7 +90,7 @@ namespace Umbraco.Web.PublishedCache.NuCache IsPreviewing = true; // clone properties so _isPreviewing is true - PropertiesArray = origin.PropertiesArray.Select(x => (IPublishedProperty) new Property((Property) x, this)).ToArray(); + PropertiesArray = origin.PropertiesArray.Select(x => (IPublishedProperty)new Property((Property)x, this)).ToArray(); } #endregion @@ -157,6 +159,25 @@ namespace Umbraco.Web.PublishedCache.NuCache public override PublishedItemType ItemType => _contentNode.ContentType.ItemType; public override string Name => _contentData.Name; + public override IReadOnlyDictionary CultureNames + { + get + { + if (!ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) + return null; + + if (_cultureNames == null) + { + var d = new Dictionary(); + foreach(var c in _contentData.CultureInfos) + { + d[c.Key] = new PublishedCultureName(c.Value.Name, c.Value.Name.ToUrlSegment()); + } + _cultureNames = d; + } + return _cultureNames; + } + } public override int Level => _contentNode.Level; public override string Path => _contentNode.Path; public override int SortOrder => _contentNode.SortOrder; @@ -205,7 +226,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.GetCacheItem(ChildrenCacheKey, () => GetChildren().ToArray()); } } @@ -250,8 +271,8 @@ namespace Umbraco.Web.PublishedCache.NuCache if (cache == null) return base.GetProperty(alias, true); - var key = ((Property) property).RecurseCacheKey; - return (Property) cache.GetCacheItem(key, () => base.GetProperty(alias, true)); + var key = ((Property)property).RecurseCacheKey; + return (Property)cache.GetCacheItem(key, () => base.GetProperty(alias, true)); } public override PublishedContentType ContentType => _contentNode.ContentType; @@ -263,7 +284,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // beware what you use that one for - you don't want to cache its result private ICacheProvider GetAppropriateCache() { - var publishedSnapshot = (PublishedShapshot) _publishedSnapshotAccessor.PublishedSnapshot; + var publishedSnapshot = (PublishedShapshot)_publishedSnapshotAccessor.PublishedSnapshot; var cache = publishedSnapshot == null ? null : ((IsPreviewing == false || PublishedSnapshotService.FullCacheWhenPreviewing) && (ItemType != PublishedItemType.Member) @@ -274,7 +295,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private ICacheProvider GetCurrentSnapshotCache() { - var publishedSnapshot = (PublishedShapshot) _publishedSnapshotAccessor.PublishedSnapshot; + var publishedSnapshot = (PublishedShapshot)_publishedSnapshotAccessor.PublishedSnapshot; return publishedSnapshot?.SnapshotCache; } @@ -311,7 +332,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.GetCacheItem(AsPreviewingCacheKey, () => new PublishedContent(this).CreateModel()); } // used by Navigable.Source,... diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 992ac62733..a02405c804 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -207,7 +207,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // plug ContentTypeService.UowRefreshedEntity += OnContentTypeRefreshedEntity; - MediaTypeService.UowRefreshedEntity+= OnMediaTypeRefreshedEntity; + MediaTypeService.UowRefreshedEntity += OnMediaTypeRefreshedEntity; MemberTypeService.UowRefreshedEntity += OnMemberTypeRefreshedEntity; } @@ -721,7 +721,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private void Notify(ContentStore store, ContentTypeCacheRefresher.JsonPayload[] payloads, Action, IEnumerable, IEnumerable, IEnumerable> action) { - var nameOfT = typeof (T).Name; + var nameOfT = typeof(T).Name; var removedIds = new List(); var refreshedIds = new List(); @@ -793,7 +793,7 @@ namespace Umbraco.Web.PublishedCache.NuCache } } - ((PublishedShapshot) CurrentPublishedShapshot).Resync(); + ((PublishedShapshot)CurrentPublishedShapshot).Resync(); } public override void Notify(DomainCacheRefresher.JsonPayload[] payloads) @@ -993,7 +993,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // a MaxValue to make sure this one runs last, and it should be ok scopeContext.Enlist("Umbraco.Web.PublishedCache.NuCache.PublishedSnapshotService.Resync", () => this, (completed, svc) => { - ((PublishedShapshot) svc.CurrentPublishedShapshot).Resync(); + ((PublishedShapshot)svc.CurrentPublishedShapshot).Resync(); }, int.MaxValue); } @@ -1015,7 +1015,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return new PublishedShapshot.PublishedSnapshotElements { - ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, new DomainHelper(domainCache), _globalSettings), + ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, new DomainHelper(domainCache), _globalSettings, _serviceContext.LocalizationService), MediaCache = new MediaCache(previewDefault, mediaSnap, snapshotCache, elementsCache), MemberCache = new MemberCache(previewDefault, snapshotCache, _serviceContext.MemberService, _serviceContext.DataTypeService, _serviceContext.LocalizationService, memberTypeCache, PublishedSnapshotAccessor), DomainCache = domainCache, @@ -1079,7 +1079,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private static bool HasChangesImpactingAllVersions(IContent icontent) { - var content = (Content) icontent; + var content = (Content)icontent; // UpdateDate will be dirty // Published may be dirty if saving a Published entity @@ -1093,7 +1093,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private void OnContentRefreshedEntity(DocumentRepository sender, DocumentRepository.ScopedEntityEventArgs args) { var db = args.Scope.Database; - var content = (Content) args.Entity; + var content = (Content)args.Entity; // always refresh the edited data OnRepositoryRefreshed(db, content, false); @@ -1168,14 +1168,17 @@ namespace Umbraco.Web.PublishedCache.NuCache RebuildMemberDbCache(contentTypeIds: memberTypeIds); } - private static ContentNuDto GetDto(IContentBase content, bool published) + private ContentNuDto GetDto(IContentBase content, bool published) { // should inject these in ctor // BUT for the time being we decide not to support ConvertDbToXml/String //var propertyEditorResolver = PropertyEditorResolver.Current; //var dataTypeService = ApplicationContext.Current.Services.DataTypeService; - var data = new Dictionary(); + //the dictionary that will be serialized + var data = new ContentSerializedData(); + + var propertyData = new Dictionary(); foreach (var prop in content.Properties) { var pdatas = new List(); @@ -1206,9 +1209,28 @@ namespace Umbraco.Web.PublishedCache.NuCache // value = e.ValueEditor.ConvertDbToString(prop, prop.PropertyType, dataTypeService); //} } - data[prop.Alias] = pdatas.ToArray(); + propertyData[prop.Alias] = pdatas.ToArray(); } + data.PropertyData = propertyData; + + var cultureData = new Dictionary(); + if (content.Names != null) + { + //fixme - when this stores a culture name reference we don't need this lookup anymore + var keys = content.Names.Keys; + var langs = _serviceContext.LocalizationService.GetAllLanguages().ToDictionary(x => x.Id, x => x.IsoCode); + foreach (var name in content.Names) + { + if (langs.TryGetValue(name.Key, out var found)) + { + cultureData[found] = new CultureVariation { Name = name.Value }; + } + } + } + + data.CultureData = cultureData; + var dto = new ContentNuDto { NodeId = content.Id, diff --git a/src/Umbraco.Web/PublishedCache/PublishedMember.cs b/src/Umbraco.Web/PublishedCache/PublishedMember.cs index 0d5e61a683..bf764b0ff0 100644 --- a/src/Umbraco.Web/PublishedCache/PublishedMember.cs +++ b/src/Umbraco.Web/PublishedCache/PublishedMember.cs @@ -144,6 +144,8 @@ namespace Umbraco.Web.PublishedCache public override string Name => _member.Name; + public override IReadOnlyDictionary CultureNames => throw new NotSupportedException(); + public override string UrlName => throw new NotSupportedException(); public override string DocumentTypeAlias => _member.ContentTypeAlias; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index e44f6864a0..010a220cb2 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -112,7 +112,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache return GetByRoute(PreviewDefault, route, hideTopLevelNode); } - public virtual string GetRouteById(bool preview, int contentId) + public virtual string GetRouteById(bool preview, int contentId, string language = null) { // try to get from cache if not previewing var route = preview || _routesCache == null ? null : _routesCache.GetRoute(contentId); @@ -137,9 +137,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache return route; } - public string GetRouteById(int contentId) + public string GetRouteById(int contentId, string language = null) { - return GetRouteById(PreviewDefault, contentId); + return GetRouteById(PreviewDefault, contentId, language); } IPublishedContent DetermineIdByRoute(bool preview, string route, bool hideTopLevelNode) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs index fc8afe4939..48a63aa8d3 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedMediaCache.cs @@ -747,6 +747,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache public override int SortOrder => _sortOrder; public override string Name => _name; + + public override IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public override string UrlName => _urlName; diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs index 0ab219d368..6f9746c57d 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlPublishedContent.cs @@ -148,7 +148,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache if (_nodeInitialized == false) InitializeNode(); return _name; } - } + } + + public override IReadOnlyDictionary CultureNames => throw new NotSupportedException(); public override string DocumentTypeAlias { diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 3c72a55ede..7113ac498c 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -4,6 +4,7 @@ using System.Linq; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Services; using Umbraco.Web.Composing; using Umbraco.Web.PublishedCache; @@ -15,12 +16,14 @@ namespace Umbraco.Web.Routing public class AliasUrlProvider : IUrlProvider { private readonly IGlobalSettings _globalSettings; - private readonly IRequestHandlerSection _requestConfig; - - public AliasUrlProvider(IGlobalSettings globalSettings, IRequestHandlerSection requestConfig) + private readonly IRequestHandlerSection _requestConfig; + private readonly ILocalizationService _localizationService; + + public AliasUrlProvider(IGlobalSettings globalSettings, IRequestHandlerSection requestConfig, ILocalizationService localizationService) { _globalSettings = globalSettings; - _requestConfig = requestConfig; + _requestConfig = requestConfig; + _localizationService = localizationService; } // note - at the moment we seem to accept pretty much anything as an alias @@ -42,7 +45,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it should return null. /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) { return null; // we have nothing to say } @@ -67,13 +70,13 @@ namespace Umbraco.Web.Routing if (!FindByUrlAliasEnabled) return Enumerable.Empty(); // we have nothing to say - var node = umbracoContext.ContentCache.GetById(id); - string umbracoUrlName = null; - if (node.HasProperty(Constants.Conventions.Content.UrlAlias)) - umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias); - if (string.IsNullOrWhiteSpace(umbracoUrlName)) - return Enumerable.Empty(); - + var node = umbracoContext.ContentCache.GetById(id); + if (node == null) + return Enumerable.Empty(); + + if (!node.HasProperty(Constants.Conventions.Content.UrlAlias)) + return Enumerable.Empty(); + var domainHelper = new DomainHelper(umbracoContext.PublishedShapshot.Domains); var n = node; @@ -84,18 +87,31 @@ namespace Umbraco.Web.Routing n = n.Parent; domainUris = n == null ? null : domainHelper.DomainsForNode(n.Id, current, false); } - - var path = "/" + umbracoUrlName; - - if (domainUris == null) - { + + if (domainUris == null) + { + var path = "/" + node.Value(Constants.Conventions.Content.UrlAlias); var uri = new Uri(path, UriKind.Relative); - return new[] { UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString() }; - } - - return domainUris - .Select(domainUri => new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path))) - .Select(uri => UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString()); + return new[] { UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString() }; + } + else + { + var result = new List(); + var languageIds = new List(domainUris.Select(x => _localizationService.GetLanguageByCultureCode(x.Culture.Name)?.Id).Where(x => x.HasValue)); + foreach (var langId in languageIds) + { + var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias, languageId: langId); + if (!string.IsNullOrWhiteSpace(umbracoUrlName)) + { + var path = "/" + umbracoUrlName; + + result.AddRange(domainUris + .Select(domainUri => new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path))) + .Select(uri => UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString())); + } + } + return result; + } } #endregion diff --git a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs index 251ddf9cdd..ea7983d77c 100644 --- a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs +++ b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.Routing /// /// /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) { if (umbracoContext == null) return null; if (umbracoContext.PublishedRequest == null) return null; diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 93fde8f0b9..13b75ee623 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -37,13 +37,13 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode) + public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) { if (!current.IsAbsoluteUri) throw new ArgumentException("Current url must be absolute.", "current"); // will not use cache if previewing - var route = umbracoContext.ContentCache.GetRouteById(id); + var route = umbracoContext.ContentCache.GetRouteById(id, language); return GetUrlFromRoute(route, umbracoContext, id, current, mode); } diff --git a/src/Umbraco.Web/Routing/IUrlProvider.cs b/src/Umbraco.Web/Routing/IUrlProvider.cs index ae38f6d422..3f6ee4dcc0 100644 --- a/src/Umbraco.Web/Routing/IUrlProvider.cs +++ b/src/Umbraco.Web/Routing/IUrlProvider.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode); + string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null); /// /// Gets the other urls of a published content. diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 56c04deca1..907eac0bde 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -341,6 +341,8 @@ + + diff --git a/src/Umbraco.Web/umbraco.presentation/page.cs b/src/Umbraco.Web/umbraco.presentation/page.cs index ad1ac877be..bc650b5a78 100644 --- a/src/Umbraco.Web/umbraco.presentation/page.cs +++ b/src/Umbraco.Web/umbraco.presentation/page.cs @@ -201,7 +201,7 @@ namespace umbraco /// void PopulateElementData(IPublishedContent node) { - foreach(var p in node.Properties) + foreach (var p in node.Properties) { if (_elements.ContainsKey(p.Alias) == false) { @@ -407,7 +407,8 @@ namespace umbraco private readonly string _writerName; private readonly PublishedContentType _contentType; private readonly IPublishedProperty[] _properties; - private readonly IPublishedContent _parent; + private readonly IPublishedContent _parent; + private IReadOnlyDictionary _cultureNames; private PagePublishedContent(int id) { @@ -469,6 +470,31 @@ namespace umbraco public string Name { get { return _inner.Name; } + } + + public IReadOnlyDictionary CultureNames + { + get + { + if (!_inner.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) + return null; + + if (_cultureNames == null) + { + var d = new Dictionary(); + //fixme this will not be necessary when the IContentBase.Names is a string based dictionary + var langs = Current.Services.LocalizationService.GetAllLanguages().ToDictionary(x => x.Id, x => x.IsoCode); + foreach (var c in _inner.Names) + { + if (langs.TryGetValue(c.Key, out var lang)) + { + d[lang] = new PublishedCultureName(c.Value, c.Value.ToUrlSegment()); + } + } + _cultureNames = d; + } + return _cultureNames; + } } public string UrlName From 9044c9328d362e7f2f41cc7c4d92761799fc97e7 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 13:07:18 +1000 Subject: [PATCH 14/58] Gets inbound routing working, reduces the amount of non injected dependencies, reduces the amount of DomainHelper instances --- src/Umbraco.Core/Models/DomainExtensions.cs | 19 +++ src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../PublishedContentCacheTests.cs | 7 +- .../Integration/GetCultureTests.cs | 5 + .../PublishedContentMoreTests.cs | 3 +- .../PublishedContentTestElements.cs | 9 +- .../Routing/ContentFinderByIdTests.cs | 4 +- .../ContentFinderByNiceUrlAndTemplateTests.cs | 8 +- .../Routing/ContentFinderByNiceUrlTests.cs | 14 +- .../ContentFinderByNiceUrlWithDomainsTests.cs | 4 +- .../Routing/DomainsAndCulturesTests.cs | 6 +- .../Routing/NiceUrlProviderTests.cs | 10 +- .../NiceUrlsProviderWithDomainsTests.cs | 14 +- .../Routing/SiteDomainHelperTests.cs | 72 ++++----- .../Routing/UrlsWithNestedDomains.cs | 4 +- .../Scoping/ScopedNuCacheTests.cs | 8 +- .../Security/BackOfficeCookieManagerTests.cs | 13 +- .../TestControllerActivatorBase.cs | 4 +- .../TestHelpers/TestObjects-Mocks.cs | 2 +- .../TestHelpers/TestWithDatabaseBase.cs | 5 +- .../Testing/TestingTests/MockTests.cs | 3 +- ...RenderIndexActionSelectorAttributeTests.cs | 12 +- .../Web/Mvc/SurfaceControllerTests.cs | 5 + .../Web/Mvc/UmbracoViewPageTests.cs | 9 +- .../Web/TemplateUtilitiesTests.cs | 4 +- .../Web/WebExtensionMethodTests.cs | 10 +- .../Cache/CacheRefresherComponent.cs | 1 + src/Umbraco.Web/Composing/Current.cs | 5 +- src/Umbraco.Web/Models/ContentExtensions.cs | 45 +++--- .../Models/Mapping/ContentMapperProfile.cs | 5 +- .../Models/Mapping/ContentUrlResolver.cs | 15 +- .../PublishedCache/IPublishedContentCache.cs | 11 +- .../PublishedCache/NuCache/CacheKeys.cs | 9 +- .../PublishedCache/NuCache/ContentCache.cs | 54 +++---- .../NuCache/PublishedSnapshotService.cs | 12 +- .../XmlPublishedCache/DomainCache.cs | 11 +- .../PublishedContentCache.cs | 15 +- .../PublishedSnapshotService.cs | 16 +- .../XmlPublishedCache/XmlCacheComponent.cs | 2 + src/Umbraco.Web/PublishedContentExtensions.cs | 77 ++++++---- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 9 +- .../Routing/ContentFinderByIdPath.cs | 13 +- .../Routing/ContentFinderByLegacy404.cs | 2 +- ...nderByNiceUrl.cs => ContentFinderByUrl.cs} | 126 ++++++++-------- ...te.cs => ContentFinderByUrlAndTemplate.cs} | 139 +++++++++--------- .../Routing/CustomRouteUrlProvider.cs | 3 +- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 19 ++- src/Umbraco.Web/Routing/Domain.cs | 9 +- src/Umbraco.Web/Routing/DomainHelper.cs | 23 +-- src/Umbraco.Web/Routing/IUrlProvider.cs | 3 +- src/Umbraco.Web/Routing/SiteDomainHelper.cs | 9 +- src/Umbraco.Web/Routing/UrlProvider.cs | 22 +-- .../Routing/UrlProviderExtensions.cs | 33 ++--- .../Runtime/WebRuntimeComponent.cs | 8 +- src/Umbraco.Web/Umbraco.Web.csproj | 4 +- src/Umbraco.Web/UmbracoContext.cs | 42 ++++-- src/Umbraco.Web/UmbracoModule.cs | 8 +- 57 files changed, 582 insertions(+), 423 deletions(-) create mode 100644 src/Umbraco.Core/Models/DomainExtensions.cs rename src/Umbraco.Web/Routing/{ContentFinderByNiceUrl.cs => ContentFinderByUrl.cs} (82%) rename src/Umbraco.Web/Routing/{ContentFinderByNiceUrlAndTemplate.cs => ContentFinderByUrlAndTemplate.cs} (76%) diff --git a/src/Umbraco.Core/Models/DomainExtensions.cs b/src/Umbraco.Core/Models/DomainExtensions.cs new file mode 100644 index 0000000000..47cd34105b --- /dev/null +++ b/src/Umbraco.Core/Models/DomainExtensions.cs @@ -0,0 +1,19 @@ +using Umbraco.Core.Services; + +namespace Umbraco.Core.Models +{ + public static class DomainExtensions + { + /// + /// Returns ture if the has a culture code equal to the default language specified + /// + /// + /// + /// + public static bool IsDefaultDomain(this IDomain domain, ILocalizationService localizationService) + { + var defaultLang = localizationService.GetDefaultVariantLanguage(); + return domain.LanguageIsoCode == defaultLang.CultureName; + } + } +} diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index c8f4ed577d..a8640d4c84 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -348,6 +348,7 @@ + diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index f330c126d0..304c20c78f 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -62,9 +62,9 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); var cacheProvider = new StaticCacheProvider(); - var domainCache = new DomainCache(ServiceContext.DomainService); + var domainCache = new DomainCache(ServiceContext.DomainService, ServiceContext.LocalizationService); var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedShapshot( - new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, ContentTypesCache, null, null), + new PublishedContentCache(xmlStore, domainCache, cacheProvider, globalSettings, new SiteDomainHelper(), ContentTypesCache, null, null), new PublishedMediaCache(xmlStore, ServiceContext.MediaService, ServiceContext.UserService, cacheProvider, ContentTypesCache), new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache), domainCache); @@ -77,7 +77,8 @@ namespace Umbraco.Tests.Cache.PublishedCache new WebSecurity(_httpContextFactory.HttpContext, Current.Services.UserService, globalSettings), umbracoSettings, Enumerable.Empty(), - globalSettings); + globalSettings, + ServiceContext.EntityService); _cache = _umbracoContext.ContentCache; } diff --git a/src/Umbraco.Tests/Integration/GetCultureTests.cs b/src/Umbraco.Tests/Integration/GetCultureTests.cs index 5441024570..ec3a73b37e 100644 --- a/src/Umbraco.Tests/Integration/GetCultureTests.cs +++ b/src/Umbraco.Tests/Integration/GetCultureTests.cs @@ -54,18 +54,21 @@ namespace Umbraco.Tests.Integration var content = c2; var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, + new SiteDomainHelper(), content.Id, content.Path, new Uri("http://domain1.com/")); Assert.AreEqual("en-US", culture.Name); content = c2; culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, + new SiteDomainHelper(), content.Id, content.Path, new Uri("http://domain1.fr/")); Assert.AreEqual("fr-FR", culture.Name); content = c4; culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, + new SiteDomainHelper(), content.Id, content.Path, new Uri("http://domain1.fr/")); Assert.AreEqual("de-DE", culture.Name); } @@ -102,12 +105,14 @@ namespace Umbraco.Tests.Integration var content = c2; var culture = Umbraco.Web.Models.ContentExtensions.GetCulture(null, ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, + new SiteDomainHelper(), content.Id, content.Path, new Uri("http://domain1.com/")); Assert.AreEqual("de-DE", culture.Name); content = c4; culture = Umbraco.Web.Models.ContentExtensions.GetCulture(null, ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, + new SiteDomainHelper(), content.Id, content.Path, new Uri("http://domain1.fr/")); Assert.AreEqual("fr-FR", culture.Name); } diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs index 2713229a5e..3e715792cb 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs @@ -74,7 +74,8 @@ namespace Umbraco.Tests.PublishedContent new WebSecurity(httpContext, Current.Services.UserService, globalSettings), TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - globalSettings); + globalSettings, + ServiceContext.EntityService); return umbracoContext; } diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs index 9241686188..aa6f62cf46 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Moq; using Umbraco.Core; @@ -58,22 +59,22 @@ namespace Umbraco.Tests.PublishedContent _content.Clear(); } - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null) + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { throw new NotImplementedException(); } - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { throw new NotImplementedException(); } - public string GetRouteById(bool preview, int contentId, string language = null) + public string GetRouteById(bool preview, int contentId, CultureInfo culture = null) { throw new NotImplementedException(); } - public string GetRouteById(int contentId, string language = null) + public string GetRouteById(int contentId, CultureInfo culture = null) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs index 61c5b4aae9..2f2edf3964 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByIdTests.cs @@ -1,6 +1,8 @@ using NUnit.Framework; +using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; +using LightInject; namespace Umbraco.Tests.Routing { @@ -15,7 +17,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlAsString); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByIdPath(Logger); + var lookup = new ContentFinderByIdPath(Container.GetInstance().WebRouting, Logger); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs index c58899d4d1..7a4be24fbf 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs @@ -1,11 +1,13 @@ using Moq; -using NUnit.Framework; +using NUnit.Framework; +using LightInject; using Umbraco.Tests.TestHelpers; using Umbraco.Web.Routing; using Umbraco.Core.Models; using Umbraco.Tests.Testing; using Current = Umbraco.Web.Composing.Current; - +using Umbraco.Core.Configuration.UmbracoSettings; + namespace Umbraco.Tests.Routing { [TestFixture] @@ -37,7 +39,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByNiceUrlAndTemplate(Logger); + var lookup = new ContentFinderByUrlAndTemplate(Logger, ServiceContext.FileService); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs index 66f5cc722a..3e8101a212 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs @@ -34,7 +34,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); @@ -70,7 +70,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); @@ -96,7 +96,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); @@ -124,8 +124,8 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/")); - var lookup = new ContentFinderByNiceUrl(Logger); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/")); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); @@ -154,8 +154,8 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå")); - var lookup = new ContentFinderByNiceUrl(Logger); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/æøå")); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs index 396697001d..2e9bccf398 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs @@ -135,7 +135,7 @@ namespace Umbraco.Tests.Routing // must lookup domain else lookup by url fails publishedRouter.FindDomain(frequest); - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); Assert.AreEqual(expectedId, frequest.PublishedContent.Id); @@ -179,7 +179,7 @@ namespace Umbraco.Tests.Routing publishedRouter.FindDomain(frequest); Assert.AreEqual(expectedCulture, frequest.Culture.Name); - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); Assert.AreEqual(expectedId, frequest.PublishedContent.Id); diff --git a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs index b1d024cc8f..1740f1288c 100644 --- a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs +++ b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs @@ -277,7 +277,7 @@ namespace Umbraco.Tests.Routing Assert.AreEqual(expectedCulture, frequest.Culture.Name); - var finder = new ContentFinderByNiceUrl(Logger); + var finder = new ContentFinderByUrl(Logger); var result = finder.TryFindContent(frequest); Assert.IsTrue(result); @@ -326,7 +326,7 @@ namespace Umbraco.Tests.Routing publishedRouter.FindDomain(frequest); // find document - var finder = new ContentFinderByNiceUrl(Logger); + var finder = new ContentFinderByUrl(Logger); var result = finder.TryFindContent(frequest); // apply wildcard domain @@ -378,7 +378,7 @@ namespace Umbraco.Tests.Routing var content = umbracoContext.ContentCache.GetById(nodeId); Assert.IsNotNull(content); - var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(umbracoContext, domainService, ServiceContext.LocalizationService, null, content.Id, content.Path, new Uri(currentUrl)); + var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(umbracoContext, domainService, ServiceContext.LocalizationService, null, new SiteDomainHelper(), content.Id, content.Path, new Uri(currentUrl)); Assert.AreEqual(expectedCulture, culture.Name); } } diff --git a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs b/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs index 246a9beb8a..a4b51bad85 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs @@ -45,7 +45,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler); @@ -108,7 +108,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); var requestMock = Mock.Get(_umbracoSettings.RequestHandler); @@ -138,7 +138,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); var requestMock = Mock.Get(_umbracoSettings.RequestHandler); @@ -162,7 +162,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); @@ -185,7 +185,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); //mock the Umbraco settings that we need diff --git a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs b/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs index fa223420f2..938f0cbec6 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs @@ -184,7 +184,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains1(); @@ -220,7 +220,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains2(); @@ -248,7 +248,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains3(); @@ -282,7 +282,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains4(); @@ -306,7 +306,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains4(); @@ -373,7 +373,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains4(); @@ -405,7 +405,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); SetDomains5(); diff --git a/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs b/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs index 3b149280bd..fea8948b8e 100644 --- a/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs +++ b/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs @@ -188,8 +188,8 @@ namespace Umbraco.Tests.Routing var current = new Uri("https://www.domain1.com/foo/bar"); var domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), - new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false), + new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, true), + new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, false), }); var output = helper.MapDomain(current, domainAndUris).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); @@ -198,8 +198,8 @@ namespace Umbraco.Tests.Routing current = new Uri("https://domain1.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false), - new Domain(1, "https://domain2.com", -1, CultureInfo.CurrentCulture, false) + new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), + new Domain(1, "https://domain2.com", -1, CultureInfo.CurrentCulture, false, false) }); output = helper.MapDomain(current, domainAndUris).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); @@ -207,8 +207,8 @@ namespace Umbraco.Tests.Routing current = new Uri("https://domain1.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false), - new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false) + new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), + new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false, false) }); output = helper.MapDomain(current, domainAndUris).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); @@ -216,8 +216,8 @@ namespace Umbraco.Tests.Routing current = new Uri("https://domain4.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false), - new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false) + new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), + new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false, false) }); output = helper.MapDomain(current, domainAndUris).Uri.ToString(); Assert.AreEqual("https://domain4.com/", output); @@ -243,8 +243,8 @@ namespace Umbraco.Tests.Routing var current = new Uri("http://domain1.com/foo/bar"); var output = helper.MapDomain(current, new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false), current), - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), current), + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), }).Uri.ToString(); Assert.AreEqual("http://domain1.com/", output); @@ -254,8 +254,8 @@ namespace Umbraco.Tests.Routing current = new Uri("http://domain1.com/foo/bar"); output = helper.MapDomain(current, new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false), current), - new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false), current) + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), + new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false, false), current) }).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); @@ -266,8 +266,8 @@ namespace Umbraco.Tests.Routing current = new Uri("http://domain1.com/foo/bar"); output = helper.MapDomain(current, new[] { - new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false), current), - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false), current) + new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false, true), current), + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, false), current) }).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); } @@ -293,11 +293,11 @@ namespace Umbraco.Tests.Routing var current = new Uri("http://domain1.com/foo/bar"); var output = helper.MapDomains(current, new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false), current), // yes: same site (though bogus setup) + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) }, true).ToArray(); Assert.AreEqual(1, output.Count()); @@ -308,11 +308,11 @@ namespace Umbraco.Tests.Routing current = new Uri("http://domain1.com/foo/bar"); output = helper.MapDomains(current, new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false), current), // yes: same site (though bogus setup) + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) }, true).ToArray(); Assert.AreEqual(1, output.Count()); @@ -326,12 +326,12 @@ namespace Umbraco.Tests.Routing current = new Uri("http://domain1.com/foo/bar"); output = helper.MapDomains(current, new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false), current), // yes: same site (though bogus setup) + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) }, true).ToArray(); Assert.AreEqual(3, output.Count()); @@ -344,12 +344,12 @@ namespace Umbraco.Tests.Routing current = new Uri("http://domain1.com/foo/bar"); output = helper.MapDomains(current, new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false), current), // yes: same site (though bogus setup) + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) }, true).ToArray(); Assert.AreEqual(3, output.Count()); diff --git a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs index 41a7bf730d..0996aaab03 100644 --- a/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs +++ b/src/Umbraco.Tests/Routing/UrlsWithNestedDomains.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.Routing // get the nice url for 100111 var umbracoContext = GetUmbracoContext(url, 9999, umbracoSettings: settings, urlProviders: new [] { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object) + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) }, globalSettings:globalSettings.Object); Assert.AreEqual("http://domain2.com/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111, true)); @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Routing Assert.IsTrue(frequest.HasDomain); // check that it's been routed - var lookup = new ContentFinderByNiceUrl(Logger); + var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); Assert.AreEqual(100111, frequest.PublishedContent.Id); diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 585a943416..bb3b41d128 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Scoping publishedSnapshotAccessor, Logger, ScopeProvider, - documentRepository, mediaRepository, memberRepository, Container.GetInstance()); + documentRepository, mediaRepository, memberRepository, Container.GetInstance(), new SiteDomainHelper()); } protected UmbracoContext GetUmbracoContextNu(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null) @@ -100,13 +100,15 @@ namespace Umbraco.Tests.Scoping var httpContext = GetHttpContextFactory(url, routeData).HttpContext; + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = new UmbracoContext( httpContext, service, - new WebSecurity(httpContext, Current.Services.UserService, TestObjects.GetGlobalSettings()), + new WebSecurity(httpContext, Current.Services.UserService, globalSettings), umbracoSettings ?? SettingsForTests.GetDefaultUmbracoSettings(), urlProviders ?? Enumerable.Empty(), - TestObjects.GetGlobalSettings()); + globalSettings, + Mock.Of()); if (setSingleton) Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; diff --git a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs index 1b182024c3..51d6a7fa7d 100644 --- a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs +++ b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs @@ -7,6 +7,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Services; using Umbraco.Tests.Testing; using Umbraco.Web; using Umbraco.Web.PublishedCache; @@ -26,11 +27,13 @@ namespace Umbraco.Tests.Security //should force app ctx to show not-configured ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", ""); + var globalSettings = TestObjects.GetGlobalSettings(); var umbracoContext = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), - TestObjects.GetUmbracoSettings(), new List(),TestObjects.GetGlobalSettings()); + new WebSecurity(Mock.Of(), Current.Services.UserService, globalSettings), + TestObjects.GetUmbracoSettings(), new List(),globalSettings, + Mock.Of()); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); var mgr = new BackOfficeCookieManager( @@ -44,11 +47,13 @@ namespace Umbraco.Tests.Security [Test] public void ShouldAuthenticateRequest_When_Configured() { + var globalSettings = TestObjects.GetGlobalSettings(); var umbCtx = new UmbracoContext( Mock.Of(), Mock.Of(), - new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), - TestObjects.GetUmbracoSettings(), new List(), TestObjects.GetGlobalSettings()); + new WebSecurity(Mock.Of(), Current.Services.UserService, globalSettings), + TestObjects.GetUmbracoSettings(), new List(), globalSettings, + Mock.Of()); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbCtx), runtime, TestObjects.GetGlobalSettings()); diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 7a8188cd0b..05e9a39551 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -28,6 +28,7 @@ using Umbraco.Web.Routing; using Umbraco.Web.Security; using Umbraco.Web.WebApi; using LightInject; +using System.Globalization; namespace Umbraco.Tests.TestHelpers.ControllerTesting { @@ -148,10 +149,11 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting Mock.Of(section => section.WebRouting == Mock.Of(routingSection => routingSection.UrlProviderMode == UrlProviderMode.Auto.ToString())), Enumerable.Empty(), globalSettings, + mockedEntityService, true); //replace it var urlHelper = new Mock(); - urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var membershipHelper = new MembershipHelper(umbCtx, Mock.Of(), Mock.Of()); diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 50cb115eae..050c10757a 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -119,7 +119,7 @@ namespace Umbraco.Tests.TestHelpers var urlProviders = Enumerable.Empty(); if (accessor == null) accessor = new TestUmbracoContextAccessor(); - return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, true); + return UmbracoContext.EnsureContext(accessor, httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, Mock.Of(), true); } public IUmbracoSettingsSection GetUmbracoSettings() diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 9a2828fd9f..2b6dcffeab 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -265,7 +265,7 @@ namespace Umbraco.Tests.TestHelpers cache, publishedSnapshotAccessor, Container.GetInstance(), Container.GetInstance(), Container.GetInstance(), Logger, - Container.GetInstance(), + Container.GetInstance(), new SiteDomainHelper(), ContentTypesCache, null, true, Options.PublishedRepositoryEvents); @@ -366,7 +366,8 @@ namespace Umbraco.Tests.TestHelpers new WebSecurity(httpContext, Container.GetInstance(), Container.GetInstance()), umbracoSettings ?? Container.GetInstance(), urlProviders ?? Enumerable.Empty(), - globalSettings ?? Container.GetInstance()); + globalSettings ?? Container.GetInstance(), + ServiceContext.EntityService); if (setSingleton) Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index 580defd5ab..7575bb3d1f 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Web.Security; using Moq; using NUnit.Framework; @@ -73,7 +74,7 @@ namespace Umbraco.Tests.Testing.TestingTests var umbracoContext = TestObjects.GetUmbracoContextMock(); var urlProviderMock = new Mock(); - urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var urlProvider = urlProviderMock.Object; diff --git a/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs b/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs index 1a61882949..1f5fe1a6e3 100644 --- a/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/RenderIndexActionSelectorAttributeTests.cs @@ -71,7 +71,8 @@ namespace Umbraco.Tests.Web.Mvc new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - globalSettings, + globalSettings, + Mock.Of(), true); var ctrl = new MatchesDefaultIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -94,7 +95,8 @@ namespace Umbraco.Tests.Web.Mvc new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - globalSettings, + globalSettings, + Mock.Of(), true); var ctrl = new MatchesOverriddenIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -117,7 +119,8 @@ namespace Umbraco.Tests.Web.Mvc new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - globalSettings, + globalSettings, + Mock.Of(), true); var ctrl = new MatchesCustomIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); @@ -140,7 +143,8 @@ namespace Umbraco.Tests.Web.Mvc new Mock(null, null, globalSettings).Object, TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - globalSettings, + globalSettings, + Mock.Of(), true); var ctrl = new MatchesAsyncIndexController { UmbracoContext = umbCtx }; var controllerCtx = new ControllerContext(req, ctrl); diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index d9a12751c0..927b5557bd 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -45,6 +45,7 @@ namespace Umbraco.Tests.Web.Mvc TestObjects.GetUmbracoSettings(), Enumerable.Empty(), globalSettings, + Mock.Of(), true); var ctrl = new TestSurfaceController { UmbracoContext = umbracoContext }; @@ -66,6 +67,7 @@ namespace Umbraco.Tests.Web.Mvc TestObjects.GetUmbracoSettings(), Enumerable.Empty(), globalSettings, + Mock.Of(), true); var ctrl = new TestSurfaceController { UmbracoContext = umbCtx }; @@ -85,6 +87,7 @@ namespace Umbraco.Tests.Web.Mvc TestObjects.GetUmbracoSettings(), Enumerable.Empty(), globalSettings, + Mock.Of(), true); var controller = new TestSurfaceController { UmbracoContext = umbracoContext }; @@ -111,6 +114,7 @@ namespace Umbraco.Tests.Web.Mvc Mock.Of(section => section.WebRouting == Mock.Of(routingSection => routingSection.UrlProviderMode == "AutoLegacy")), Enumerable.Empty(), globalSettings, + Mock.Of(), true); var helper = new UmbracoHelper( @@ -148,6 +152,7 @@ namespace Umbraco.Tests.Web.Mvc Mock.Of(section => section.WebRouting == webRoutingSettings), Enumerable.Empty(), globalSettings, + Mock.Of(), true); var content = Mock.Of(publishedContent => publishedContent.Id == 12345); diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index 053a1f7c5d..9fe3b44264 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -425,17 +425,20 @@ namespace Umbraco.Tests.Web.Mvc var factory = Mock.Of(); _service = new PublishedSnapshotService(svcCtx, factory, scopeProvider, cache, Enumerable.Empty(), null, null, null, null, - Current.Logger, TestObjects.GetGlobalSettings(), null, true, false); // no events + Current.Logger, TestObjects.GetGlobalSettings(), new SiteDomainHelper(), null, true, false); // no events var http = GetHttpContextFactory(url, routeData).HttpContext; + + var globalSettings = TestObjects.GetGlobalSettings(); var ctx = new UmbracoContext( GetHttpContextFactory(url, routeData).HttpContext, _service, - new WebSecurity(http, Current.Services.UserService, TestObjects.GetGlobalSettings()), + new WebSecurity(http, Current.Services.UserService, globalSettings), TestObjects.GetUmbracoSettings(), Enumerable.Empty(), - TestObjects.GetGlobalSettings()); + globalSettings, + Mock.Of()); //if (setSingleton) //{ diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index e6a5dd8438..ed06948e3f 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Web; using LightInject; using Moq; @@ -72,7 +73,7 @@ namespace Umbraco.Tests.Web //setup a mock url provider which we'll use fo rtesting var testUrlProvider = new Mock(); - testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode) => { return "/my-test-url"; @@ -90,6 +91,7 @@ namespace Umbraco.Tests.Web //pass in the custom url provider new[]{ testUrlProvider.Object }, globalSettings, + entityService.Object, true)) { var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider); diff --git a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs index 86339c309f..cc97633cde 100644 --- a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs +++ b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs @@ -5,6 +5,7 @@ using System.Web.Mvc; using System.Web.Routing; using Moq; using NUnit.Framework; +using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Tests.Testing; using Umbraco.Web; @@ -29,7 +30,8 @@ namespace Umbraco.Tests.Web new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), new List(), - TestObjects.GetGlobalSettings()); + TestObjects.GetGlobalSettings(), + Mock.Of()); var r1 = new RouteData(); r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx); @@ -46,7 +48,8 @@ namespace Umbraco.Tests.Web new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), new List(), - TestObjects.GetGlobalSettings()); + TestObjects.GetGlobalSettings(), + Mock.Of()); var r1 = new RouteData(); r1.DataTokens.Add(Core.Constants.Web.UmbracoContextDataToken, umbCtx); @@ -73,7 +76,8 @@ namespace Umbraco.Tests.Web new WebSecurity(Mock.Of(), Current.Services.UserService, TestObjects.GetGlobalSettings()), TestObjects.GetUmbracoSettings(), new List(), - TestObjects.GetGlobalSettings()); + TestObjects.GetGlobalSettings(), + Mock.Of()); var httpContext = Mock.Of(); diff --git a/src/Umbraco.Web/Cache/CacheRefresherComponent.cs b/src/Umbraco.Web/Cache/CacheRefresherComponent.cs index 15030db207..07dcebd763 100644 --- a/src/Umbraco.Web/Cache/CacheRefresherComponent.cs +++ b/src/Umbraco.Web/Cache/CacheRefresherComponent.cs @@ -237,6 +237,7 @@ namespace Umbraco.Web.Cache UmbracoConfig.For.UmbracoSettings(), Current.UrlProviders, UmbracoConfig.For.GlobalSettings(), + Current.Services.EntityService, true); } diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index b819046a9a..5ca7b60cf0 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -142,10 +142,7 @@ namespace Umbraco.Web.Composing internal static IPublishedSnapshotService PublishedSnapshotService => Container.GetInstance(); - - public static ISiteDomainHelper SiteDomainHelper - => Container.GetInstance(); - + public static ThumbnailProviderCollection ThumbnailProviders => Container.GetInstance(); diff --git a/src/Umbraco.Web/Models/ContentExtensions.cs b/src/Umbraco.Web/Models/ContentExtensions.cs index 4a016a895b..0712e2503d 100644 --- a/src/Umbraco.Web/Models/ContentExtensions.cs +++ b/src/Umbraco.Web/Models/ContentExtensions.cs @@ -11,23 +11,27 @@ namespace Umbraco.Web.Models { public static class ContentExtensions { - /// - /// Gets the culture that would be selected to render a specified content, - /// within the context of a specified current request. - /// - /// The content. - /// The request Uri. - /// The culture that would be selected to render the content. - public static CultureInfo GetCulture(this IContent content, Uri current = null) - { - return GetCulture(UmbracoContext.Current, - Current.Services.DomainService, - Current.Services.LocalizationService, - Current.Services.ContentService, - content.Id, content.Path, - current); - } + //TODO: Not used + ///// + ///// Gets the culture that would be selected to render a specified content, + ///// within the context of a specified current request. + ///// + ///// The content. + ///// The request Uri. + ///// The culture that would be selected to render the content. + //public static CultureInfo GetCulture(this IContent content, Uri current = null) + //{ + // return GetCulture(UmbracoContext.Current, + // Current.Services.DomainService, + // Current.Services.LocalizationService, + // Current.Services.ContentService, + // content.Id, content.Path, + // current); + //} + + + //TODO: Not used - only in tests /// /// Gets the culture that would be selected to render a specified content, /// within the context of a specified current request. @@ -42,6 +46,7 @@ namespace Umbraco.Web.Models /// The culture that would be selected to render the content. internal static CultureInfo GetCulture(UmbracoContext umbracoContext, IDomainService domainService, ILocalizationService localizationService, IContentService contentService, + ISiteDomainHelper siteDomainHelper, int contentId, string contentPath, Uri current) { var route = umbracoContext == null @@ -49,9 +54,9 @@ namespace Umbraco.Web.Models : umbracoContext.ContentCache.GetRouteById(contentId); // may be cached var domainCache = umbracoContext == null - ? new PublishedCache.XmlPublishedCache.DomainCache(domainService) // for tests only + ? new PublishedCache.XmlPublishedCache.DomainCache(domainService, localizationService) // for tests only : umbracoContext.PublishedShapshot.Domains; // default - var domainHelper = new DomainHelper(domainCache); + var domainHelper = umbracoContext.GetDomainHelper(siteDomainHelper); Domain domain; if (route == null) @@ -59,6 +64,8 @@ namespace Umbraco.Web.Models // if content is not published then route is null and we have to work // on non-published content (note: could optimize by checking routes?) + // fixme - even non-published content is stored in the cache or in the cmsContentNu table which would be faster to lookup + var content = contentService.GetById(contentId); if (content == null) return GetDefaultCulture(localizationService); @@ -93,7 +100,7 @@ namespace Umbraco.Web.Models private static CultureInfo GetDefaultCulture(ILocalizationService localizationService) { - var defaultLanguage = localizationService.GetAllLanguages().FirstOrDefault(); + var defaultLanguage = localizationService.GetDefaultVariantLanguage(); return defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); } diff --git a/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs index 627f508906..059dd32499 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs @@ -1,6 +1,7 @@ using System.Linq; using AutoMapper; using Umbraco.Core; +using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; @@ -13,7 +14,7 @@ namespace Umbraco.Web.Models.Mapping /// internal class ContentMapperProfile : Profile { - public ContentMapperProfile(IUserService userService, ILocalizedTextService textService, IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService, ILocalizationService localizationService) + public ContentMapperProfile(IUserService userService, ILocalizedTextService textService, IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService, ILocalizationService localizationService, ILogger logger) { // create, capture, cache var contentOwnerResolver = new OwnerResolver(userService); @@ -24,7 +25,7 @@ namespace Umbraco.Web.Models.Mapping var contentTypeBasicResolver = new ContentTypeBasicResolver(); var contentTreeNodeUrlResolver = new ContentTreeNodeUrlResolver(); var defaultTemplateResolver = new DefaultTemplateResolver(); - var contentUrlResolver = new ContentUrlResolver(); + var contentUrlResolver = new ContentUrlResolver(textService, contentService, logger); var variantResolver = new ContentItemDisplayVariationResolver(localizationService); //FROM IContent TO ContentItemDisplay diff --git a/src/Umbraco.Web/Models/Mapping/ContentUrlResolver.cs b/src/Umbraco.Web/Models/Mapping/ContentUrlResolver.cs index 909ca83985..e311190d67 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentUrlResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentUrlResolver.cs @@ -1,6 +1,8 @@ using System.Linq; using AutoMapper; +using Umbraco.Core.Logging; using Umbraco.Core.Models; +using Umbraco.Core.Services; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Routing; @@ -8,13 +10,24 @@ namespace Umbraco.Web.Models.Mapping { internal class ContentUrlResolver : IValueResolver { + private readonly ILocalizedTextService _textService; + private readonly IContentService _contentService; + private readonly ILogger _logger; + + public ContentUrlResolver(ILocalizedTextService textService, IContentService contentService, ILogger logger) + { + _textService = textService; + _contentService = contentService; + _logger = logger; + } + public string[] Resolve(IContent source, ContentItemDisplay destination, string[] destMember, ResolutionContext context) { var umbracoContext = context.GetUmbracoContext(throwIfMissing: false); var urls = umbracoContext == null ? new[] {"Cannot generate urls without a current Umbraco Context"} - : source.GetContentUrls(umbracoContext).ToArray(); + : source.GetContentUrls(umbracoContext.UrlProvider, _textService, _contentService, _logger).ToArray(); return urls; } diff --git a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs index 64fa5efde4..2d7c93d93e 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs @@ -1,4 +1,5 @@ -using Umbraco.Core.Models; +using System.Globalization; +using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Web.PublishedCache @@ -17,7 +18,7 @@ namespace Umbraco.Web.PublishedCache /// If is null then the settings value is used. /// The value of overrides defaults. /// - IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null); + IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null); /// /// Gets content identified by a route. @@ -30,7 +31,7 @@ namespace Umbraco.Web.PublishedCache /// If is null then the settings value is used. /// Considers published or unpublished content depending on defaults. /// - IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null); + IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null); /// /// Gets the route for a content identified by its unique identifier. @@ -39,7 +40,7 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// The value of overrides defaults. - string GetRouteById(bool preview, int contentId, string language = null); + string GetRouteById(bool preview, int contentId, CultureInfo culture = null); /// /// Gets the route for a content identified by its unique identifier. @@ -47,6 +48,6 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// Considers published or unpublished content depending on defaults. - string GetRouteById(int contentId, string language = null); + string GetRouteById(int contentId, CultureInfo culture = null); } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs index 6d21fedb6d..9d887f4d40 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Runtime.CompilerServices; namespace Umbraco.Web.PublishedCache.NuCache @@ -12,9 +13,9 @@ namespace Umbraco.Web.PublishedCache.NuCache } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static string LangId(string language) + private static string LangId(CultureInfo culture) { - return language != null ? ("-L:" + language) : string.Empty; + return culture != null ? ("-L:" + culture.Name) : string.Empty; } public static string PublishedContentChildren(Guid contentUid, bool previewing) @@ -56,9 +57,9 @@ namespace Umbraco.Web.PublishedCache.NuCache // a valid ID in the database at that point, whereas content and properties // may be virtual (and not in umbracoNode). - public static string ContentCacheRouteByContent(int id, bool previewing, string language) + public static string ContentCacheRouteByContent(int id, bool previewing, CultureInfo culture) { - return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + LangId(language) + "]"; + return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + LangId(culture) + "]"; } public static string ContentCacheContentByRoute(string route, bool previewing) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index f27d2c9937..74598186f6 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -55,21 +55,21 @@ namespace Umbraco.Web.PublishedCache.NuCache // at the moment we try our best to be backward compatible, but really, // should get rid of hideTopLevelNode and other oddities entirely, eventually - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { - return GetByRoute(PreviewDefault, route, hideTopLevelNode); + return GetByRoute(PreviewDefault, route, hideTopLevelNode, culture); } - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null) + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { if (route == null) throw new ArgumentNullException(nameof(route)); var cache = preview == false || PublishedSnapshotService.FullCacheWhenPreviewing ? _elementsCache : _snapshotCache; var key = CacheKeys.ContentCacheContentByRoute(route, preview); - return cache.GetCacheItem(key, () => GetByRouteInternal(preview, route, hideTopLevelNode)); + return cache.GetCacheItem(key, () => GetByRouteInternal(preview, route, hideTopLevelNode, culture)); } - private IPublishedContent GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode) + private IPublishedContent GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode, CultureInfo culture) { hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings @@ -90,7 +90,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // note: if domain has a path (eg example.com/en) which is not recommended anymore // then then /en part of the domain is basically ignored here... content = GetById(preview, startNodeId); - content = FollowRoute(content, parts, 0); + content = FollowRoute(content, parts, 0, culture); } else if (parts.Length == 0) { @@ -106,7 +106,7 @@ namespace Umbraco.Web.PublishedCache.NuCache content = hideTopLevelNode.Value ? GetAtRoot(preview).SelectMany(x => x.Children).FirstOrDefault(x => x.UrlName == parts[0]) : GetAtRoot(preview).FirstOrDefault(x => x.UrlName == parts[0]); - content = FollowRoute(content, parts, 1); + content = FollowRoute(content, parts, 1, culture); } // if hideTopLevelNodePath is true then for url /foo we looked for /*/foo @@ -120,19 +120,19 @@ namespace Umbraco.Web.PublishedCache.NuCache return content; } - public string GetRouteById(int contentId, string language = null) + public string GetRouteById(int contentId, CultureInfo culture = null) { - return GetRouteById(PreviewDefault, contentId, language); + return GetRouteById(PreviewDefault, contentId, culture); } - public string GetRouteById(bool preview, int contentId, string language = null) + public string GetRouteById(bool preview, int contentId, CultureInfo culture = null) { var cache = (preview == false || PublishedSnapshotService.FullCacheWhenPreviewing) ? _elementsCache : _snapshotCache; - var key = CacheKeys.ContentCacheRouteByContent(contentId, preview, language); - return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null, language)); + var key = CacheKeys.ContentCacheRouteByContent(contentId, preview, culture); + return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null, culture)); } - private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, string language) + private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, CultureInfo culture) { var node = GetById(preview, contentId); if (node == null) @@ -147,23 +147,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var hasDomains = _domainHelper.NodeHasDomains(n.Id); while (hasDomains == false && n != null) // n is null at root { - // get the url - string urlName; - if (n.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) - { - var cultureCode = language != null - ? language - : _localizationService.GetDefaultVariantLanguage()?.IsoCode; - - if (n.CultureNames.TryGetValue(cultureCode, out var cultureName)) - urlName = cultureName.UrlName; - else - urlName = n.UrlName; //couldn't get the value, fallback to invariant ... not sure what else to do - } - else - { - urlName = n.UrlName; - } + var urlName = n.GetUrlName(_localizationService, culture); pathParts.Add(urlName); @@ -184,13 +168,17 @@ namespace Umbraco.Web.PublishedCache.NuCache return route; } - private static IPublishedContent FollowRoute(IPublishedContent content, IReadOnlyList parts, int start) + private IPublishedContent FollowRoute(IPublishedContent content, IReadOnlyList parts, int start, CultureInfo culture) { var i = start; while (content != null && i < parts.Count) { var part = parts[i++]; - content = content.Children.FirstOrDefault(x => x.UrlName == part); + content = content.Children.FirstOrDefault(x => + { + var urlName = x.GetUrlName(_localizationService, culture); + return urlName == part; + }); } return content; } @@ -266,7 +254,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.GetCacheItem( CacheKeys.ContentCacheRoots(preview), () => GetAtRootNoCache(preview).ToArray()); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index a02405c804..eae0fd50b5 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -43,6 +43,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IMediaRepository _mediaRepository; private readonly IMemberRepository _memberRepository; private readonly IGlobalSettings _globalSettings; + private readonly ISiteDomainHelper _siteDomainHelper; // volatile because we read it with no lock private volatile bool _isReady; @@ -81,7 +82,8 @@ namespace Umbraco.Web.PublishedCache.NuCache public PublishedSnapshotService(Options options, MainDom mainDom, IRuntimeState runtime, ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IdkMap idkMap, IPublishedSnapshotAccessor publishedSnapshotAccessor, ILogger logger, IScopeProvider scopeProvider, - IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, IGlobalSettings globalSettings) + IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, + IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper) : base(publishedSnapshotAccessor) { //if (Interlocked.Increment(ref _singletonCheck) > 1) @@ -96,6 +98,7 @@ namespace Umbraco.Web.PublishedCache.NuCache _mediaRepository = mediaRepository; _memberRepository = memberRepository; _globalSettings = globalSettings; + _siteDomainHelper = siteDomainHelper; // we always want to handle repository events, configured or not // assuming no repository event will trigger before the whole db is ready @@ -484,7 +487,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var domains = _serviceContext.DomainService.GetAll(true); foreach (var domain in domains .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard))) + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_serviceContext.LocalizationService)))) { _domainStore.Set(domain.Id, domain); } @@ -828,7 +831,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (domain.RootContentId.HasValue == false) continue; // anomaly if (domain.LanguageIsoCode.IsNullOrWhiteSpace()) continue; // anomaly var culture = CultureInfo.GetCultureInfo(domain.LanguageIsoCode); - _domainStore.Set(domain.Id, new Domain(domain.Id, domain.DomainName, domain.RootContentId.Value, culture, domain.IsWildcard)); + _domainStore.Set(domain.Id, new Domain(domain.Id, domain.DomainName, domain.RootContentId.Value, culture, domain.IsWildcard, domain.IsDefaultDomain(_serviceContext.LocalizationService))); break; } } @@ -1012,10 +1015,11 @@ namespace Umbraco.Web.PublishedCache.NuCache var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); var domainCache = new DomainCache(domainSnap); + var domainHelper = new DomainHelper(domainCache, _siteDomainHelper); return new PublishedShapshot.PublishedSnapshotElements { - ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, new DomainHelper(domainCache), _globalSettings, _serviceContext.LocalizationService), + ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, domainHelper, _globalSettings, _serviceContext.LocalizationService), MediaCache = new MediaCache(previewDefault, mediaSnap, snapshotCache, elementsCache), MemberCache = new MemberCache(previewDefault, snapshotCache, _serviceContext.MemberService, _serviceContext.DataTypeService, _serviceContext.LocalizationService, memberTypeCache, PublishedSnapshotAccessor), DomainCache = domainCache, diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs index 83651a9986..051c333762 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs @@ -4,30 +4,33 @@ using System.Linq; using Umbraco.Web.Routing; using Umbraco.Core; using Umbraco.Core.Services; +using Umbraco.Core.Models; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { - class DomainCache : IDomainCache + internal class DomainCache : IDomainCache { private readonly IDomainService _domainService; + private readonly ILocalizationService _localizationService; - public DomainCache(IDomainService domainService) + public DomainCache(IDomainService domainService, ILocalizationService localizationService) { _domainService = domainService; + _localizationService = localizationService; } public IEnumerable GetAll(bool includeWildcards) { return _domainService.GetAll(includeWildcards) .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard)); + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_localizationService))); } public IEnumerable GetAssigned(int contentId, bool includeWildcards) { return _domainService.GetAssignedDomains(contentId, includeWildcards) .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard)); + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_localizationService))); } } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index 010a220cb2..01ab37554e 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -31,7 +31,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache XmlStore xmlStore, // an XmlStore containing the master xml IDomainCache domainCache, // an IDomainCache implementation ICacheProvider cacheProvider, // an ICacheProvider that should be at request-level - IGlobalSettings globalSettings, + IGlobalSettings globalSettings, + ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, // a PublishedContentType cache RoutesCache routesCache, // a RoutesCache string previewToken) // a preview token string (or null if not previewing) @@ -42,7 +43,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _routesCache = routesCache; // may be null for unit-testing _contentTypeCache = contentTypeCache; _domainCache = domainCache; - _domainHelper = new DomainHelper(_domainCache); + _domainHelper = new DomainHelper(_domainCache, siteDomainHelper); _xmlStore = xmlStore; _xml = _xmlStore.Xml; // capture - because the cache has to remain consistent @@ -63,7 +64,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache #region Routes - public virtual IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null) + public virtual IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { if (route == null) throw new ArgumentNullException(nameof(route)); @@ -107,12 +108,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _routesCache.Store(content.Id, route, true); // trusted route } - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) { return GetByRoute(PreviewDefault, route, hideTopLevelNode); } - public virtual string GetRouteById(bool preview, int contentId, string language = null) + public virtual string GetRouteById(bool preview, int contentId, CultureInfo culture = null) { // try to get from cache if not previewing var route = preview || _routesCache == null ? null : _routesCache.GetRoute(contentId); @@ -137,9 +138,9 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache return route; } - public string GetRouteById(int contentId, string language = null) + public string GetRouteById(int contentId, CultureInfo culture = null) { - return GetRouteById(PreviewDefault, contentId, language); + return GetRouteById(PreviewDefault, contentId, culture); } IPublishedContent DetermineIdByRoute(bool preview, string route, bool hideTopLevelNode) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs index fedff54c29..7cde462dbc 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs @@ -13,6 +13,7 @@ using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Web.Cache; +using Umbraco.Web.Routing; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { @@ -31,6 +32,8 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IUserService _userService; private readonly ICacheProvider _requestCache; private readonly IGlobalSettings _globalSettings; + private readonly ILocalizationService _localizationService; + private readonly ISiteDomainHelper _siteDomainHelper; #region Constructors @@ -44,11 +47,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, ILogger logger, IGlobalSettings globalSettings, + ISiteDomainHelper siteDomainHelper, MainDom mainDom, bool testing = false, bool enableRepositoryEvents = true) : this(serviceContext, publishedContentTypeFactory, scopeProvider, requestCache, segmentProviders, publishedSnapshotAccessor, documentRepository, mediaRepository, memberRepository, - logger, globalSettings, null, mainDom, testing, enableRepositoryEvents) + logger, globalSettings, siteDomainHelper, null, mainDom, testing, enableRepositoryEvents) { } // used in some tests @@ -60,12 +64,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, ILogger logger, IGlobalSettings globalSettings, + ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, MainDom mainDom, bool testing, bool enableRepositoryEvents) : this(serviceContext, publishedContentTypeFactory, scopeProvider, requestCache, Enumerable.Empty(), publishedSnapshotAccessor, documentRepository, mediaRepository, memberRepository, - logger, globalSettings, contentTypeCache, mainDom, testing, enableRepositoryEvents) + logger, globalSettings, siteDomainHelper, contentTypeCache, mainDom, testing, enableRepositoryEvents) { } private PublishedSnapshotService(ServiceContext serviceContext, @@ -77,6 +82,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, ILogger logger, IGlobalSettings globalSettings, + ISiteDomainHelper siteDomainHelper, PublishedContentTypeCache contentTypeCache, MainDom mainDom, bool testing, bool enableRepositoryEvents) @@ -95,9 +101,11 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _memberService = serviceContext.MemberService; _mediaService = serviceContext.MediaService; _userService = serviceContext.UserService; + _localizationService = serviceContext.LocalizationService; _requestCache = requestCache; _globalSettings = globalSettings; + _siteDomainHelper = siteDomainHelper; } public override void Dispose() @@ -138,10 +146,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // the current caches, but that would mean creating an extra cache (StaticCache // probably) so better use RequestCache. - var domainCache = new DomainCache(_domainService); + var domainCache = new DomainCache(_domainService, _localizationService); return new PublishedShapshot( - new PublishedContentCache(_xmlStore, domainCache, _requestCache, _globalSettings, _contentTypeCache, _routesCache, previewToken), + new PublishedContentCache(_xmlStore, domainCache, _requestCache, _globalSettings, _siteDomainHelper, _contentTypeCache, _routesCache, previewToken), new PublishedMediaCache(_xmlStore, _mediaService, _userService, _requestCache, _contentTypeCache), new PublishedMemberCache(_xmlStore, _requestCache, _memberService, _contentTypeCache), domainCache); diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs index 00bb705c1d..37f29cc1d6 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs @@ -10,6 +10,7 @@ using LightInject; using Umbraco.Core.Configuration; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Persistence.Repositories; +using Umbraco.Web.Routing; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { @@ -33,6 +34,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), factory.GetInstance())); // add the Xml cache health check (hidden from type finder) diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 7bdd196f20..e68365416d 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -272,8 +272,8 @@ namespace Umbraco.Web { //TODO: we should pass in the IExamineManager? - var s = searchProvider ?? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer); - + var s = searchProvider ?? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer); + var results = s.Search(criteria); return results.ToPublishedSearchResults(UmbracoContext.Current.ContentCache); } @@ -1066,7 +1066,7 @@ namespace Umbraco.Web /// The first child of content, of the given content type. public static IPublishedContent FirstChild(this IPublishedContent content, string alias) { - return content.Children( alias ).FirstOrDefault(); + return content.Children(alias).FirstOrDefault(); } public static IPublishedContent FirstChild(this IPublishedContent content, Func predicate) @@ -1116,12 +1116,12 @@ namespace Umbraco.Web return new DataTable(); //no children found //use new utility class to create table so that we don't have to maintain code in many places, just one - var dt = Core.DataTableExtensions.GenerateDataTable( - //pass in the alias of the first child node since this is the node type we're rendering headers for - firstNode.DocumentTypeAlias, - //pass in the callback to extract the Dictionary of all defined aliases to their names - alias => GetPropertyAliasesAndNames(services, alias), - //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. + var dt = Core.DataTableExtensions.GenerateDataTable( + //pass in the alias of the first child node since this is the node type we're rendering headers for + firstNode.DocumentTypeAlias, + //pass in the callback to extract the Dictionary of all defined aliases to their names + alias => GetPropertyAliasesAndNames(services, alias), + //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. () => { //create all row data @@ -1222,28 +1222,51 @@ namespace Umbraco.Web private static Dictionary GetAliasesAndNames(IContentTypeBase contentType) { return contentType.PropertyTypes.ToDictionary(x => x.Alias, x => x.Name); - } - + } + #endregion - + #region Culture - + + //TODO: Not used + ///// + ///// Gets the culture that would be selected to render a specified content, + ///// within the context of a specified current request. + ///// + ///// The content. + ///// The request Uri. + ///// The culture that would be selected to render the content. + //public static CultureInfo GetCulture(this IPublishedContent content, Uri current = null) + //{ + // return Models.ContentExtensions.GetCulture(UmbracoContext.Current, + // Current.Services.DomainService, + // Current.Services.LocalizationService, + // Current.Services.ContentService, + // content.Id, content.Path, + // current); + //} + /// - /// Gets the culture that would be selected to render a specified content, - /// within the context of a specified current request. + /// Return the URL name for the based on the culture specified or default culture defined /// - /// The content. - /// The request Uri. - /// The culture that would be selected to render the content. - public static CultureInfo GetCulture(this IPublishedContent content, Uri current = null) - { - return Models.ContentExtensions.GetCulture(UmbracoContext.Current, - Current.Services.DomainService, - Current.Services.LocalizationService, - Current.Services.ContentService, - content.Id, content.Path, - current); - } + /// + /// + /// + /// + public static string GetUrlName(this IPublishedContent content, ILocalizationService localizationService, CultureInfo culture = null) + { + if (content.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) + { + var cultureCode = culture != null ? culture.Name : localizationService.GetDefaultVariantLanguage()?.IsoCode; + if (cultureCode != null && content.CultureNames.TryGetValue(cultureCode, out var cultureName)) + { + return cultureName.UrlName; + } + } + + //if we get here, the content type is invariant or we don't have access to a usable culture code + return content.UrlName; + } #endregion } diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 7113ac498c..7c926f04f3 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Umbraco.Core; using Umbraco.Core.Configuration; @@ -18,12 +19,14 @@ namespace Umbraco.Web.Routing private readonly IGlobalSettings _globalSettings; private readonly IRequestHandlerSection _requestConfig; private readonly ILocalizationService _localizationService; + private readonly ISiteDomainHelper _siteDomainHelper; - public AliasUrlProvider(IGlobalSettings globalSettings, IRequestHandlerSection requestConfig, ILocalizationService localizationService) + public AliasUrlProvider(IGlobalSettings globalSettings, IRequestHandlerSection requestConfig, ILocalizationService localizationService, ISiteDomainHelper siteDomainHelper) { _globalSettings = globalSettings; _requestConfig = requestConfig; _localizationService = localizationService; + _siteDomainHelper = siteDomainHelper; } // note - at the moment we seem to accept pretty much anything as an alias @@ -45,7 +48,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it should return null. /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) { return null; // we have nothing to say } @@ -77,7 +80,7 @@ namespace Umbraco.Web.Routing if (!node.HasProperty(Constants.Conventions.Content.UrlAlias)) return Enumerable.Empty(); - var domainHelper = new DomainHelper(umbracoContext.PublishedShapshot.Domains); + var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); var n = node; var domainUris = domainHelper.DomainsForNode(n.Id, current, false); diff --git a/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs b/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs index eb3e481a7b..2052a198bf 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByIdPath.cs @@ -16,16 +16,11 @@ namespace Umbraco.Web.Routing { private readonly ILogger _logger; private readonly IWebRoutingSection _webRoutingSection; - - public ContentFinderByIdPath(ILogger logger) - : this(UmbracoConfig.For.UmbracoSettings().WebRouting) + + public ContentFinderByIdPath(IWebRoutingSection webRoutingSection, ILogger logger) { - _logger = logger; - } - - public ContentFinderByIdPath(IWebRoutingSection webRoutingSection) - { - _webRoutingSection = webRoutingSection; + _webRoutingSection = webRoutingSection ?? throw new System.ArgumentNullException(nameof(webRoutingSection)); + _logger = logger ?? throw new System.ArgumentNullException(nameof(logger)); } /// diff --git a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs index a687d43dbe..090b7d421d 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.Routing while (pos > 1) { route = route.Substring(0, pos); - node = frequest.UmbracoContext.ContentCache.GetByRoute(route); + node = frequest.UmbracoContext.ContentCache.GetByRoute(route, culture: frequest.Culture); if (node != null) break; pos = route.LastIndexOf('/'); } diff --git a/src/Umbraco.Web/Routing/ContentFinderByNiceUrl.cs b/src/Umbraco.Web/Routing/ContentFinderByUrl.cs similarity index 82% rename from src/Umbraco.Web/Routing/ContentFinderByNiceUrl.cs rename to src/Umbraco.Web/Routing/ContentFinderByUrl.cs index 094c0addaf..66b8024c6b 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByNiceUrl.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByUrl.cs @@ -1,63 +1,63 @@ -using Umbraco.Core.Logging; -using Umbraco.Core; -using Umbraco.Core.Models.PublishedContent; - -namespace Umbraco.Web.Routing -{ - /// - /// Provides an implementation of that handles page nice urls. - /// - /// - /// Handles /foo/bar where /foo/bar is the nice url of a document. - /// - public class ContentFinderByNiceUrl : IContentFinder - { - protected ILogger Logger { get; } - - public ContentFinderByNiceUrl(ILogger logger) - { - Logger = logger; - } - - /// - /// Tries to find and assign an Umbraco document to a PublishedContentRequest. - /// - /// The PublishedContentRequest. - /// A value indicating whether an Umbraco document was found and assigned. - public virtual bool TryFindContent(PublishedRequest frequest) - { - string route; - if (frequest.HasDomain) - route = frequest.Domain.ContentId + DomainHelper.PathRelativeToDomain(frequest.Domain.Uri, frequest.Uri.GetAbsolutePathDecoded()); - else - route = frequest.Uri.GetAbsolutePathDecoded(); - - var node = FindContent(frequest, route); - return node != null; - } - - /// - /// Tries to find an Umbraco document for a PublishedContentRequest and a route. - /// - /// The document request. - /// The route. - /// The document node, or null. - protected IPublishedContent FindContent(PublishedRequest docreq, string route) - { - Logger.Debug(() => $"Test route \"{route}\""); - - var node = docreq.UmbracoContext.ContentCache.GetByRoute(route); - if (node != null) - { - docreq.PublishedContent = node; - Logger.Debug(() => $"Got content, id={node.Id}"); - } - else - { - Logger.Debug("No match."); - } - - return node; - } - } -} +using Umbraco.Core.Logging; +using Umbraco.Core; +using Umbraco.Core.Models.PublishedContent; + +namespace Umbraco.Web.Routing +{ + /// + /// Provides an implementation of that handles page nice urls. + /// + /// + /// Handles /foo/bar where /foo/bar is the nice url of a document. + /// + public class ContentFinderByUrl : IContentFinder + { + protected ILogger Logger { get; } + + public ContentFinderByUrl(ILogger logger) + { + Logger = logger; + } + + /// + /// Tries to find and assign an Umbraco document to a PublishedContentRequest. + /// + /// The PublishedContentRequest. + /// A value indicating whether an Umbraco document was found and assigned. + public virtual bool TryFindContent(PublishedRequest frequest) + { + string route; + if (frequest.HasDomain) + route = frequest.Domain.ContentId + DomainHelper.PathRelativeToDomain(frequest.Domain.Uri, frequest.Uri.GetAbsolutePathDecoded()); + else + route = frequest.Uri.GetAbsolutePathDecoded(); + + var node = FindContent(frequest, route); + return node != null; + } + + /// + /// Tries to find an Umbraco document for a PublishedContentRequest and a route. + /// + /// The document request. + /// The route. + /// The document node, or null. + protected IPublishedContent FindContent(PublishedRequest docreq, string route) + { + Logger.Debug(() => $"Test route \"{route}\""); + + var node = docreq.UmbracoContext.ContentCache.GetByRoute(route, culture: docreq.Culture); + if (node != null) + { + docreq.PublishedContent = node; + Logger.Debug(() => $"Got content, id={node.Id}"); + } + else + { + Logger.Debug("No match."); + } + + return node; + } + } +} diff --git a/src/Umbraco.Web/Routing/ContentFinderByNiceUrlAndTemplate.cs b/src/Umbraco.Web/Routing/ContentFinderByUrlAndTemplate.cs similarity index 76% rename from src/Umbraco.Web/Routing/ContentFinderByNiceUrlAndTemplate.cs rename to src/Umbraco.Web/Routing/ContentFinderByUrlAndTemplate.cs index d0eaa55b79..8f507078b3 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByNiceUrlAndTemplate.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByUrlAndTemplate.cs @@ -1,67 +1,72 @@ -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core; -using Umbraco.Core.Configuration; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Web.Composing; - -namespace Umbraco.Web.Routing -{ - /// - /// Provides an implementation of that handles page nice urls and a template. - /// - /// - /// Handles /foo/bar/template where /foo/bar is the nice url of a document, and template a template alias. - /// If successful, then the template of the document request is also assigned. - /// - public class ContentFinderByNiceUrlAndTemplate : ContentFinderByNiceUrl - { - public ContentFinderByNiceUrlAndTemplate(ILogger logger) - : base(logger) - { } - - /// - /// Tries to find and assign an Umbraco document to a PublishedContentRequest. - /// - /// The PublishedContentRequest. - /// A value indicating whether an Umbraco document was found and assigned. - /// If successful, also assigns the template. - public override bool TryFindContent(PublishedRequest frequest) - { - IPublishedContent node = null; - var path = frequest.Uri.GetAbsolutePathDecoded(); - - if (frequest.HasDomain) - path = DomainHelper.PathRelativeToDomain(frequest.Domain.Uri, path); - - if (path != "/") // no template if "/" - { - var pos = path.LastIndexOf('/'); - var templateAlias = path.Substring(pos + 1); - path = pos == 0 ? "/" : path.Substring(0, pos); - - var template = Current.Services.FileService.GetTemplate(templateAlias); - if (template != null) - { - Logger.Debug(() => $"Valid template: \"{templateAlias}\""); - - var route = frequest.HasDomain ? (frequest.Domain.ContentId.ToString() + path) : path; - node = FindContent(frequest, route); - - if (UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates == false && node != null) - frequest.TemplateModel = template; - } - else - { - Logger.Debug(() => $"Not a valid template: \"{templateAlias}\""); - } - } - else - { - Logger.Debug("No template in path \"/\""); - } - - return node != null; - } - } -} +using Umbraco.Core.Logging; +using Umbraco.Core.Models; +using Umbraco.Core; +using Umbraco.Core.Configuration; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Web.Composing; +using Umbraco.Core.Services; + +namespace Umbraco.Web.Routing +{ + /// + /// Provides an implementation of that handles page nice urls and a template. + /// + /// + /// Handles /foo/bar/template where /foo/bar is the nice url of a document, and template a template alias. + /// If successful, then the template of the document request is also assigned. + /// + public class ContentFinderByUrlAndTemplate : ContentFinderByUrl + { + private readonly IFileService _fileService; + + public ContentFinderByUrlAndTemplate(ILogger logger, IFileService fileService) + : base(logger) + { + _fileService = fileService; + } + + /// + /// Tries to find and assign an Umbraco document to a PublishedContentRequest. + /// + /// The PublishedContentRequest. + /// A value indicating whether an Umbraco document was found and assigned. + /// If successful, also assigns the template. + public override bool TryFindContent(PublishedRequest frequest) + { + IPublishedContent node = null; + var path = frequest.Uri.GetAbsolutePathDecoded(); + + if (frequest.HasDomain) + path = DomainHelper.PathRelativeToDomain(frequest.Domain.Uri, path); + + if (path != "/") // no template if "/" + { + var pos = path.LastIndexOf('/'); + var templateAlias = path.Substring(pos + 1); + path = pos == 0 ? "/" : path.Substring(0, pos); + + var template = _fileService.GetTemplate(templateAlias); + if (template != null) + { + Logger.Debug(() => $"Valid template: \"{templateAlias}\""); + + var route = frequest.HasDomain ? (frequest.Domain.ContentId.ToString() + path) : path; + node = FindContent(frequest, route); + + if (UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates == false && node != null) + frequest.TemplateModel = template; + } + else + { + Logger.Debug(() => $"Not a valid template: \"{templateAlias}\""); + } + } + else + { + Logger.Debug("No template in path \"/\""); + } + + return node != null; + } + } +} diff --git a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs index ea7983d77c..7a3d8fffed 100644 --- a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs +++ b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; namespace Umbraco.Web.Routing { @@ -18,7 +19,7 @@ namespace Umbraco.Web.Routing /// /// /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) { if (umbracoContext == null) return null; if (umbracoContext.PublishedRequest == null) return null; diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 13b75ee623..d2f0c2662b 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; @@ -14,13 +15,15 @@ namespace Umbraco.Web.Routing { private readonly IRequestHandlerSection _requestSettings; private readonly ILogger _logger; - private readonly IGlobalSettings _globalSettings; - - public DefaultUrlProvider(IRequestHandlerSection requestSettings, ILogger logger, IGlobalSettings globalSettings) + private readonly IGlobalSettings _globalSettings; + private readonly ISiteDomainHelper _siteDomainHelper; + + public DefaultUrlProvider(IRequestHandlerSection requestSettings, ILogger logger, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper) { _requestSettings = requestSettings; _logger = logger; - _globalSettings = globalSettings; + _globalSettings = globalSettings; + _siteDomainHelper = siteDomainHelper; } #region GetUrl @@ -37,13 +40,13 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null) + public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) { if (!current.IsAbsoluteUri) throw new ArgumentException("Current url must be absolute.", "current"); // will not use cache if previewing - var route = umbracoContext.ContentCache.GetRouteById(id, language); + var route = umbracoContext.ContentCache.GetRouteById(id, culture); return GetUrlFromRoute(route, umbracoContext, id, current, mode); } @@ -57,7 +60,7 @@ namespace Umbraco.Web.Routing return null; } - var domainHelper = new DomainHelper(umbracoContext.PublishedShapshot.Domains); + var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); // extract domainUri and path // route is / or / @@ -98,7 +101,7 @@ namespace Umbraco.Web.Routing return null; } - var domainHelper = new DomainHelper(umbracoContext.PublishedShapshot.Domains); + var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); // extract domainUri and path // route is / or / diff --git a/src/Umbraco.Web/Routing/Domain.cs b/src/Umbraco.Web/Routing/Domain.cs index b9116c6b51..03048f0dd5 100644 --- a/src/Umbraco.Web/Routing/Domain.cs +++ b/src/Umbraco.Web/Routing/Domain.cs @@ -15,13 +15,14 @@ namespace Umbraco.Web.Routing /// The identifier of the content which supports the domain. /// The culture of the domain. /// A value indicating whether the domain is a wildcard domain. - public Domain(int id, string name, int contentId, CultureInfo culture, bool isWildcard) + public Domain(int id, string name, int contentId, CultureInfo culture, bool isWildcard, bool isDefault) { Id = id; Name = name; ContentId = contentId; Culture = culture; IsWildcard = isWildcard; + IsDefault = isDefault; } /// @@ -35,6 +36,7 @@ namespace Umbraco.Web.Routing ContentId = domain.ContentId; Culture = domain.Culture; IsWildcard = domain.IsWildcard; + IsDefault = domain.IsDefault; } /// @@ -61,5 +63,10 @@ namespace Umbraco.Web.Routing /// Gets a value indicating whether the domain is a wildcard domain. /// public bool IsWildcard { get; } + + /// + /// Gets a value indicating if this is the default domain for the website. + /// + public bool IsDefault { get; } } } diff --git a/src/Umbraco.Web/Routing/DomainHelper.cs b/src/Umbraco.Web/Routing/DomainHelper.cs index 79ccb9fbd4..d56473f530 100644 --- a/src/Umbraco.Web/Routing/DomainHelper.cs +++ b/src/Umbraco.Web/Routing/DomainHelper.cs @@ -12,11 +12,13 @@ namespace Umbraco.Web.Routing /// public class DomainHelper { - private readonly IDomainCache _domainCache; - - public DomainHelper(IDomainCache domainCache) + private readonly IDomainCache _domainCache; + private readonly ISiteDomainHelper _siteDomainHelper; + + public DomainHelper(IDomainCache domainCache, ISiteDomainHelper siteDomainHelper) { - _domainCache = domainCache; + _domainCache = domainCache; + _siteDomainHelper = siteDomainHelper; } #region Domain for Node @@ -43,8 +45,7 @@ namespace Umbraco.Web.Routing return null; // else filter - var helper = Current.SiteDomainHelper; - var domainAndUri = DomainForUri(domains, current, domainAndUris => helper.MapDomain(current, domainAndUris)); + var domainAndUri = DomainForUri(domains, current, domainAndUris => _siteDomainHelper.MapDomain(current, domainAndUris)); if (domainAndUri == null) throw new Exception("DomainForUri returned null."); @@ -88,8 +89,7 @@ namespace Umbraco.Web.Routing var domainAndUris = DomainsForUri(domains, current).ToArray(); // filter - var helper = Current.SiteDomainHelper; - return helper.MapDomains(current, domainAndUris, excludeDefault).ToArray(); + return _siteDomainHelper.MapDomains(current, domainAndUris, excludeDefault).ToArray(); } #endregion @@ -125,9 +125,10 @@ namespace Umbraco.Web.Routing DomainAndUri domainAndUri; if (current == null) - { - // take the first one by default (what else can we do?) - domainAndUri = domainsAndUris.First(); // .First() protected by .Any() above + { + //get the default domain (there should be one) + domainAndUri = domainsAndUris.FirstOrDefault(x => x.IsDefault); + if (domainAndUri == null) domainsAndUris.First(); // take the first one by default (what else can we do?) } else { diff --git a/src/Umbraco.Web/Routing/IUrlProvider.cs b/src/Umbraco.Web/Routing/IUrlProvider.cs index 3f6ee4dcc0..086f9c4767 100644 --- a/src/Umbraco.Web/Routing/IUrlProvider.cs +++ b/src/Umbraco.Web/Routing/IUrlProvider.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using Umbraco.Web.PublishedCache; namespace Umbraco.Web.Routing @@ -21,7 +22,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string language = null); + string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null); /// /// Gets the other urls of a published content. diff --git a/src/Umbraco.Web/Routing/SiteDomainHelper.cs b/src/Umbraco.Web/Routing/SiteDomainHelper.cs index 1ceab6293a..deaa84b0e1 100644 --- a/src/Umbraco.Web/Routing/SiteDomainHelper.cs +++ b/src/Umbraco.Web/Routing/SiteDomainHelper.cs @@ -302,8 +302,13 @@ namespace Umbraco.Web.Routing throw new ArgumentException("Cannot be empty.", "domainAndUris"); // we do our best, but can't do the impossible - if (qualifiedSites == null) - return domainAndUris.First(); + if (qualifiedSites == null) + { + //fixme take the default + var defaultDomain = domainAndUris.FirstOrDefault(x => x.IsDefault); + if (defaultDomain == null) defaultDomain = domainAndUris.First(); //this shouldn't occur but just in case + return defaultDomain; + } // find a site that contains the current authority var currentSite = qualifiedSites.FirstOrDefault(site => site.Value.Contains(currentAuthority)); diff --git a/src/Umbraco.Web/Routing/UrlProvider.cs b/src/Umbraco.Web/Routing/UrlProvider.cs index 3375ac1be2..58f1689cb0 100644 --- a/src/Umbraco.Web/Routing/UrlProvider.cs +++ b/src/Umbraco.Web/Routing/UrlProvider.cs @@ -7,7 +7,8 @@ using Umbraco.Web.PublishedCache; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Composing; - +using Umbraco.Core.Services; + namespace Umbraco.Web.Routing { /// @@ -23,13 +24,13 @@ namespace Umbraco.Web.Routing /// The Umbraco context. /// /// The list of url providers. - public UrlProvider(UmbracoContext umbracoContext, IWebRoutingSection routingSettings, IEnumerable urlProviders) + public UrlProvider(UmbracoContext umbracoContext, IWebRoutingSection routingSettings, IEnumerable urlProviders, IEntityService entityService) { if (routingSettings == null) throw new ArgumentNullException(nameof(routingSettings)); _umbracoContext = umbracoContext ?? throw new ArgumentNullException(nameof(umbracoContext)); - _urlProviders = urlProviders; - + _urlProviders = urlProviders; + _entityService = entityService ?? throw new ArgumentNullException(nameof(entityService)); var provider = UrlProviderMode.Auto; Mode = provider; @@ -54,8 +55,9 @@ namespace Umbraco.Web.Routing } private readonly UmbracoContext _umbracoContext; - private readonly IEnumerable _urlProviders; - + private readonly IEnumerable _urlProviders; + private readonly IEntityService _entityService; + /// /// Gets or sets the provider url mode. /// @@ -76,7 +78,7 @@ namespace Umbraco.Web.Routing /// public string GetUrl(Guid id) { - var intId = Current.Services.EntityService.GetId(id, UmbracoObjectTypes.Document); + var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1); } @@ -93,7 +95,7 @@ namespace Umbraco.Web.Routing /// public string GetUrl(Guid id, bool absolute) { - var intId = Current.Services.EntityService.GetId(id, UmbracoObjectTypes.Document); + var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, absolute); } @@ -111,7 +113,7 @@ namespace Umbraco.Web.Routing /// public string GetUrl(Guid id, Uri current, bool absolute) { - var intId = Current.Services.EntityService.GetId(id, UmbracoObjectTypes.Document); + var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, current, absolute); } @@ -127,7 +129,7 @@ namespace Umbraco.Web.Routing /// public string GetUrl(Guid id, UrlProviderMode mode) { - var intId = Current.Services.EntityService.GetId(id, UmbracoObjectTypes.Document); + var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, mode); } diff --git a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs index 1d9a4a4236..a71bb51ddc 100644 --- a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs +++ b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs @@ -11,11 +11,6 @@ namespace Umbraco.Web.Routing { internal static class UrlProviderExtensions { - // fixme inject - private static ILocalizedTextService TextService => Current.Services.TextService; - private static IContentService ContentService => Current.Services.ContentService; - private static ILogger Logger => Current.Logger; - /// /// Gets the URLs for the content item /// @@ -26,28 +21,30 @@ namespace Umbraco.Web.Routing /// Use this when displaying URLs, if there are errors genertaing the urls the urls themselves will /// contain the errors. /// - public static IEnumerable GetContentUrls(this IContent content, UmbracoContext umbracoContext) + public static IEnumerable GetContentUrls(this IContent content, UrlProvider urlProvider, ILocalizedTextService textService, IContentService contentService, ILogger logger) { - if (content == null) throw new ArgumentNullException(nameof(content)); - if (umbracoContext == null) throw new ArgumentNullException(nameof(umbracoContext)); - + if (content == null) throw new ArgumentNullException(nameof(content)); + if (urlProvider == null) throw new ArgumentNullException(nameof(urlProvider)); + if (textService == null) throw new ArgumentNullException(nameof(textService)); + if (contentService == null) throw new ArgumentNullException(nameof(contentService)); + if (logger == null) throw new ArgumentNullException(nameof(logger)); + var urls = new List(); if (content.Published == false) { - urls.Add(TextService.Localize("content/itemNotPublished")); + urls.Add(textService.Localize("content/itemNotPublished")); return urls; } string url; - var urlProvider = umbracoContext.UrlProvider; try { url = urlProvider.GetUrl(content.Id); } catch (Exception e) { - Logger.Error("GetUrl exception.", e); + logger.Error("GetUrl exception.", e); url = "#ex"; } if (url == "#") @@ -57,17 +54,17 @@ namespace Umbraco.Web.Routing var parent = content; do { - parent = parent.ParentId > 0 ? parent.Parent(ContentService) : null; + parent = parent.ParentId > 0 ? parent.Parent(contentService) : null; } while (parent != null && parent.Published); urls.Add(parent == null - ? TextService.Localize("content/parentNotPublishedAnomaly") // oops - internal error - : TextService.Localize("content/parentNotPublished", new[] { parent.Name })); + ? textService.Localize("content/parentNotPublishedAnomaly") // oops - internal error + : textService.Localize("content/parentNotPublished", new[] { parent.Name })); } else if (url == "#ex") { - urls.Add(TextService.Localize("content/getUrlException")); + urls.Add(textService.Localize("content/getUrlException")); } else { @@ -81,7 +78,7 @@ namespace Umbraco.Web.Routing if (pcr.HasPublishedContent == false) { - urls.Add(TextService.Localize("content/routeError", new[] { "(error)" })); + urls.Add(textService.Localize("content/routeError", new[] { "(error)" })); } else if (pcr.PublishedContent.Id != content.Id) { @@ -103,7 +100,7 @@ namespace Umbraco.Web.Routing s = "/" + string.Join("/", l) + " (id=" + pcr.PublishedContent.Id + ")"; } - urls.Add(TextService.Localize("content/routeError", s)); + urls.Add(textService.Localize("content/routeError", s)); } else { diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index d67bf50797..820d846d9f 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -169,9 +169,9 @@ namespace Umbraco.Web.Runtime // all built-in finders in the correct order, // devs can then modify this list on application startup .Append() - .Append() + .Append() .Append() - .Append() + .Append() .Append() .Append(); @@ -212,6 +212,7 @@ namespace Umbraco.Web.Runtime IUserService userService, IUmbracoSettingsSection umbracoSettings, IGlobalSettings globalSettings, + IEntityService entityService, UrlProviderCollection urlProviders) { // setup mvc and webapi services @@ -248,7 +249,8 @@ namespace Umbraco.Web.Runtime new WebSecurity(httpContext, userService, globalSettings), umbracoSettings, urlProviders, - globalSettings); + globalSettings, + entityService); // ensure WebAPI is initialized, after everything GlobalConfiguration.Configuration.EnsureInitialized(); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 907eac0bde..67ce954045 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -394,6 +394,8 @@ + + @@ -1231,8 +1233,6 @@ - - diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index cb7a29f608..ef684a21ba 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -4,6 +4,7 @@ using System.Web; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Services; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; using Umbraco.Web.Runtime; @@ -17,7 +18,8 @@ namespace Umbraco.Web public class UmbracoContext : DisposableObject, IDisposeOnRequestEnd { private readonly IGlobalSettings _globalSettings; - private readonly Lazy _publishedSnapshot; + private readonly Lazy _publishedSnapshot; + private DomainHelper _domainHelper; private string _previewToken; private bool? _previewing; @@ -28,10 +30,10 @@ namespace Umbraco.Web /// /// /// An http context. - /// A published snapshot service. - /// A security helper. - /// The umbraco settings. - /// Some url providers. + /// A published snapshot service. + /// A security helper. + /// The umbraco settings. + /// Some url providers. /// /// A value indicating whether to replace the existing context. /// The "current" UmbracoContext. @@ -66,7 +68,8 @@ namespace Umbraco.Web WebSecurity webSecurity, IUmbracoSettingsSection umbracoSettings, IEnumerable urlProviders, - IGlobalSettings globalSettings, + IGlobalSettings globalSettings, + IEntityService entityService, bool replace = false) { if (umbracoContextAccessor == null) throw new ArgumentNullException(nameof(umbracoContextAccessor)); @@ -84,7 +87,7 @@ namespace Umbraco.Web // create & assign to accessor, dispose existing if any umbracoContextAccessor.UmbracoContext?.Dispose(); - return umbracoContextAccessor.UmbracoContext = new UmbracoContext(httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings); + return umbracoContextAccessor.UmbracoContext = new UmbracoContext(httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, entityService); } // initializes a new instance of the UmbracoContext class @@ -96,7 +99,8 @@ namespace Umbraco.Web WebSecurity webSecurity, IUmbracoSettingsSection umbracoSettings, IEnumerable urlProviders, - IGlobalSettings globalSettings) + IGlobalSettings globalSettings, + IEntityService entityService) { if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); if (publishedSnapshotService == null) throw new ArgumentNullException(nameof(publishedSnapshotService)); @@ -132,7 +136,7 @@ namespace Umbraco.Web // OriginalRequestUrl = GetRequestFromContext()?.Url ?? new Uri("http://localhost"); CleanedUmbracoUrl = UriUtility.UriToUmbraco(OriginalRequestUrl); - UrlProvider = new UrlProvider(this, umbracoSettings.WebRouting, urlProviders); + UrlProvider = new UrlProvider(this, umbracoSettings.WebRouting, urlProviders, entityService); } #endregion @@ -207,7 +211,25 @@ namespace Umbraco.Web /// /// Exposes the HttpContext for the current request /// - public HttpContextBase HttpContext { get; } + public HttpContextBase HttpContext { get; } + + /// + /// Creates and caches an instance of a DomainHelper + /// + /// + /// We keep creating new instances of DomainHelper, it would be better if we didn't have to do that so instead we can + /// have one attached to the UmbracoContext. This method accepts an external ISiteDomainHelper otherwise the UmbracoContext + /// ctor will have to have another parameter added only for this one method which is annoying and doesn't make a ton of sense + /// since the UmbracoContext itself doesn't use this. + /// + /// TODO The alternative is to have a IDomainHelperAccessor singleton which is cached per UmbracoContext + /// + internal DomainHelper GetDomainHelper(ISiteDomainHelper siteDomainHelper) + { + if (_domainHelper == null) + _domainHelper = new DomainHelper(PublishedShapshot.Domains, siteDomainHelper); + return _domainHelper; + } /// /// Gets a value indicating whether the request has debugging enabled diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index 746c23a325..1578f5dc53 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -53,7 +53,10 @@ namespace Umbraco.Web public IPublishedSnapshotService PublishedSnapshotService { get; set; } [Inject] - public IUserService UserService { get; set; } + public IUserService UserService { get; set; } + + [Inject] + public IEntityService EntityService { get; set; } [Inject] public UrlProviderCollection UrlProviders { get; set; } @@ -111,7 +114,8 @@ namespace Umbraco.Web new WebSecurity(httpContext, UserService, GlobalSettings), UmbracoConfig.For.UmbracoSettings(), UrlProviders, - GlobalSettings, + GlobalSettings, + EntityService, true); } From 7c05f2e86cabecc10b3f8c009b716293bdb1bcb3 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 14:39:52 +1000 Subject: [PATCH 15/58] fixes routing cache key --- src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs | 4 ++-- src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs index 9d887f4d40..e1b86b9ad6 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs @@ -62,9 +62,9 @@ namespace Umbraco.Web.PublishedCache.NuCache return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + LangId(culture) + "]"; } - public static string ContentCacheContentByRoute(string route, bool previewing) + public static string ContentCacheContentByRoute(string route, bool previewing, CultureInfo culture) { - return "NuCache.ContentCache.ContentByRoute[" + DraftOrPub(previewing) + route + "]"; + return "NuCache.ContentCache.ContentByRoute[" + DraftOrPub(previewing) + route + LangId(culture) + "]"; } //public static string ContentCacheRouteByContentStartsWith() diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index 74598186f6..c6d380ca55 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -65,7 +65,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (route == null) throw new ArgumentNullException(nameof(route)); var cache = preview == false || PublishedSnapshotService.FullCacheWhenPreviewing ? _elementsCache : _snapshotCache; - var key = CacheKeys.ContentCacheContentByRoute(route, preview); + var key = CacheKeys.ContentCacheContentByRoute(route, preview, culture); return cache.GetCacheItem(key, () => GetByRouteInternal(preview, route, hideTopLevelNode, culture)); } From de2784c28141222a2463c062b8c79e6c22212a5a Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 14:51:27 +1000 Subject: [PATCH 16/58] Adds culture optional parameters to all GetUrl methods on UrlProvider --- src/Umbraco.Web/Routing/UrlProvider.cs | 37 +++++++++++++------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/src/Umbraco.Web/Routing/UrlProvider.cs b/src/Umbraco.Web/Routing/UrlProvider.cs index 58f1689cb0..3fb0d6fd1d 100644 --- a/src/Umbraco.Web/Routing/UrlProvider.cs +++ b/src/Umbraco.Web/Routing/UrlProvider.cs @@ -8,6 +8,7 @@ using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Composing; using Umbraco.Core.Services; +using System.Globalization; namespace Umbraco.Web.Routing { @@ -76,10 +77,10 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on Mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id) + public string GetUrl(Guid id, CultureInfo culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); - return GetUrl(intId.Success ? intId.Result : -1); + return GetUrl(intId.Success ? intId.Result : -1, culture); } /// @@ -93,10 +94,10 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, bool absolute) + public string GetUrl(Guid id, bool absolute, CultureInfo culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); - return GetUrl(intId.Success ? intId.Result : -1, absolute); + return GetUrl(intId.Success ? intId.Result : -1, absolute, culture); } /// @@ -111,10 +112,10 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, Uri current, bool absolute) + public string GetUrl(Guid id, Uri current, bool absolute, CultureInfo culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); - return GetUrl(intId.Success ? intId.Result : -1, current, absolute); + return GetUrl(intId.Success ? intId.Result : -1, current, absolute, culture); } /// @@ -127,10 +128,10 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, UrlProviderMode mode) + public string GetUrl(Guid id, UrlProviderMode mode, CultureInfo culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); - return GetUrl(intId.Success ? intId.Result : -1, mode); + return GetUrl(intId.Success ? intId.Result : -1, mode, culture); } /// @@ -142,9 +143,9 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on Mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id) + public string GetUrl(int id, CultureInfo culture = null) { - return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, Mode); + return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, Mode, culture); } /// @@ -158,10 +159,10 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, bool absolute) + public string GetUrl(int id, bool absolute, CultureInfo culture = null) { var mode = absolute ? UrlProviderMode.Absolute : Mode; - return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode); + return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode, culture); } /// @@ -176,10 +177,10 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, Uri current, bool absolute) + public string GetUrl(int id, Uri current, bool absolute, CultureInfo culture = null) { var mode = absolute ? UrlProviderMode.Absolute : Mode; - return GetUrl(id, current, mode); + return GetUrl(id, current, mode, culture); } /// @@ -192,9 +193,9 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, UrlProviderMode mode) + public string GetUrl(int id, UrlProviderMode mode, CultureInfo culture = null) { - return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode); + return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode, culture); } /// @@ -208,9 +209,9 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, Uri current, UrlProviderMode mode) + public string GetUrl(int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) { - var url = _urlProviders.Select(provider => provider.GetUrl(_umbracoContext, id, current, mode)) + var url = _urlProviders.Select(provider => provider.GetUrl(_umbracoContext, id, current, mode, culture)) .FirstOrDefault(u => u != null); return url ?? "#"; // legacy wants this } From d552d5dadbb00c2432a48cfa83c9993a73006849 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 15:27:33 +1000 Subject: [PATCH 17/58] Updates UI and mapping to update a property type to allow being culture variant --- .../services/umbdataformatter.service.js | 2 +- .../propertysettings/propertysettings.html | 208 +++++++++--------- .../Editors/ContentTypeController.cs | 13 +- .../ContentEditing/PropertyTypeBasic.cs | 3 + .../Mapping/ContentTypeMapperProfile.cs | 2 +- .../Mapping/PropertyTypeGroupResolver.cs | 3 +- .../Mapping/PropertyTypeVariationsResolver.cs | 23 ++ .../NuCache/DataSource/BTree.cs | 1 - src/Umbraco.Web/Umbraco.Web.csproj | 1 + 9 files changed, 150 insertions(+), 106 deletions(-) create mode 100644 src/Umbraco.Web/Models/Mapping/PropertyTypeVariationsResolver.cs diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js index dab6cb8eda..9608fe20fb 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js @@ -56,7 +56,7 @@ }); var saveProperties = _.map(realProperties, function (p) { - var saveProperty = _.pick(p, 'id', 'alias', 'description', 'validation', 'label', 'sortOrder', 'dataTypeId', 'groupId', 'memberCanEdit', 'showOnMemberProfile', 'isSensitiveData'); + var saveProperty = _.pick(p, 'id', 'alias', 'description', 'validation', 'label', 'sortOrder', 'dataTypeId', 'groupId', 'memberCanEdit', 'showOnMemberProfile', 'isSensitiveData', 'allowCultureVariant'); return saveProperty; }); diff --git a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html index 9df9c801b4..76be18a58f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html +++ b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html @@ -1,131 +1,137 @@
    -
    -
    -
    Required label
    -
    -
    - -
    -
    +
    +
    + +
    + -
    - -
    + - -
    +
    -
    +
    - + - + - -
    +
    +
    -
    +
    Property Type Variation
    -
    - - + - +
    - +
    -
    +
    - - + - - + + + + +
    + + + + + + diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index 0aa43c8cfb..5ffe68afaa 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -169,7 +169,18 @@ namespace Umbraco.Web.Editors } public DocumentTypeDisplay PostSave(DocumentTypeSave contentTypeSave) - { + { + //Before we send this model into this saving/mapping pipeline, we need to do some cleanup on variations. + //If the doc type does not allow content variations, we need to update all of it's property types to not allow this either + //else we may end up with ysods. I'm unsure if the service level handles this but we'll make sure it is updated here + if (!contentTypeSave.AllowCultureVariant) + { + foreach(var prop in contentTypeSave.Groups.SelectMany(x => x.Properties)) + { + prop.AllowCultureVariant = false; + } + } + var savedCt = PerformPostSave( contentTypeSave: contentTypeSave, getContentType: i => Services.ContentTypeService.Get(i), diff --git a/src/Umbraco.Web/Models/ContentEditing/PropertyTypeBasic.cs b/src/Umbraco.Web/Models/ContentEditing/PropertyTypeBasic.cs index b6f678068e..cde9d0dabc 100644 --- a/src/Umbraco.Web/Models/ContentEditing/PropertyTypeBasic.cs +++ b/src/Umbraco.Web/Models/ContentEditing/PropertyTypeBasic.cs @@ -46,5 +46,8 @@ namespace Umbraco.Web.Models.ContentEditing //SD: Is this really needed ? [DataMember(Name = "groupId")] public int GroupId { get; set; } + + [DataMember(Name = "allowCultureVariant")] + public bool AllowCultureVariant { get; set; } } } diff --git a/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs index bba27ce3f1..2ee9e38ff5 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs @@ -163,7 +163,7 @@ namespace Umbraco.Web.Models.Mapping .ForMember(dest => dest.PropertyEditorAlias, opt => opt.Ignore()) .ForMember(dest => dest.DeleteDate, opt => opt.Ignore()) - .ForMember(dto => dto.Variations, opt => opt.Ignore()) // fixme - change when UI supports it! + .ForMember(dto => dto.Variations, opt => opt.ResolveUsing()) //only map if it is actually set .ForMember(dest => dest.Id, opt => opt.Condition(source => source.Id > 0)) diff --git a/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs b/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs index 9a1aeda845..b9aa482b6a 100644 --- a/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs @@ -220,7 +220,8 @@ namespace Umbraco.Web.Models.Mapping DataTypeId = p.DataTypeId, SortOrder = p.SortOrder, ContentTypeId = contentType.Id, - ContentTypeName = contentType.Name + ContentTypeName = contentType.Name, + AllowCultureVariant = p.Variations.HasFlag(Core.Models.ContentVariation.CultureNeutral) }); } diff --git a/src/Umbraco.Web/Models/Mapping/PropertyTypeVariationsResolver.cs b/src/Umbraco.Web/Models/Mapping/PropertyTypeVariationsResolver.cs new file mode 100644 index 0000000000..772caed964 --- /dev/null +++ b/src/Umbraco.Web/Models/Mapping/PropertyTypeVariationsResolver.cs @@ -0,0 +1,23 @@ +using AutoMapper; +using Umbraco.Core.Models; +using Umbraco.Web.Models.ContentEditing; +using ContentVariation = Umbraco.Core.Models.ContentVariation; + +namespace Umbraco.Web.Models.Mapping +{ + internal class PropertyTypeVariationsResolver: IValueResolver + { + public ContentVariation Resolve(PropertyTypeBasic source, PropertyType destination, ContentVariation destMember, ResolutionContext context) + { + //this will always be the case, a content type will always be allowed to be invariant + var result = ContentVariation.InvariantNeutral; + + if (source.AllowCultureVariant) + { + result |= ContentVariation.CultureNeutral; + } + + return result; + } + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs index 29b252cd92..7329033405 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs @@ -147,7 +147,6 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource for (var i = 0; i < pcount; i++) { // read lang id - // fixme: This will need to change to string when stephane is done his culture work var key = PrimitiveSerializer.String.ReadFrom(stream); var val = new CultureVariation(); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 67ce954045..65ca4c44b4 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -262,6 +262,7 @@ + From f49fa7b567348fc59029a0d2a2047064efe79035 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 15:41:50 +1000 Subject: [PATCH 18/58] don't show the variation toggle on a property type if the content type doesn't have it enabled, ensure the default variation is set on a new property type based on the content type setting --- .../directives/components/umbgroupsbuilder.directive.js | 1 + .../propertysettings/propertysettings.controller.js | 6 +++++- .../propertysettings/propertysettings.html | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js index c0be05addf..9ed180c23e 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js @@ -496,6 +496,7 @@ scope.propertySettingsDialogModel.property = property; scope.propertySettingsDialogModel.contentType = scope.contentType; scope.propertySettingsDialogModel.contentTypeName = scope.model.name; + scope.propertySettingsDialogModel.contentTypeAllowCultureVariant = scope.model.allowCultureVariant; scope.propertySettingsDialogModel.view = "views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html"; scope.propertySettingsDialogModel.show = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.controller.js index 5cb2a218d5..18575985e1 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.controller.js @@ -56,8 +56,12 @@ function activate() { - matchValidationType(); + //make the default the same as the content type + if (!$scope.model.property.id) { + $scope.model.property.allowCultureVariant = $scope.model.contentTypeAllowCultureVariant; + } + matchValidationType(); } function changeValidationPattern() { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html index 76be18a58f..ae47204f48 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html +++ b/src/Umbraco.Web.UI.Client/src/views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html @@ -85,7 +85,7 @@ -
    +
    Property Type Variation
    From a1cd80a0f66ff600c90b8ef9af5d3e6d6d9210c8 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 15:59:16 +1000 Subject: [PATCH 19/58] Removes GetLanguageByCultureCode since it is kind of useless and the name is also very misleading --- .../Repositories/ILanguageRepository.cs | 1 - .../Implement/LanguageRepository.cs | 9 +------ .../Services/ILocalizationService.cs | 9 +------ .../Services/Implement/LocalizationService.cs | 13 ---------- .../Repositories/DictionaryRepositoryTest.cs | 8 +++--- .../Repositories/LanguageRepositoryTest.cs | 25 ------------------- .../Services/LocalizationServiceTests.cs | 11 +------- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 2 +- 8 files changed, 8 insertions(+), 70 deletions(-) diff --git a/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs index 36dd10c3fb..a71128c44b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs @@ -4,7 +4,6 @@ namespace Umbraco.Core.Persistence.Repositories { public interface ILanguageRepository : IReadWriteQueryRepository { - ILanguage GetByCultureName(string cultureName); ILanguage GetByIsoCode(string isoCode); int GetIdByIsoCode(string isoCode); diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs index ae9336593d..e69b8f8f62 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs @@ -199,14 +199,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var entity = factory.BuildEntity(dto); return entity; } - - public ILanguage GetByCultureName(string cultureName) - { - // use the underlying GetMany which will force cache all languages - // TODO we are cloning ALL in GetMany just to retrieve ONE, this is surely not optimized - return GetMany().FirstOrDefault(x => x.CultureName.InvariantEquals(cultureName)); - } - + public ILanguage GetByIsoCode(string isoCode) { TypedCachePolicy.GetAllCached(PerformGetAll); // ensure cache is populated, in a non-expensive way diff --git a/src/Umbraco.Core/Services/ILocalizationService.cs b/src/Umbraco.Core/Services/ILocalizationService.cs index d61ee5e310..4f8406ebe4 100644 --- a/src/Umbraco.Core/Services/ILocalizationService.cs +++ b/src/Umbraco.Core/Services/ILocalizationService.cs @@ -102,14 +102,7 @@ namespace Umbraco.Core.Services /// Id of the /// ILanguage GetLanguageById(int id); - - /// - /// Gets a by its culture code - /// - /// Culture Code - also refered to as the Friendly name - /// - ILanguage GetLanguageByCultureCode(string cultureName); - + /// /// Gets a by its iso code /// diff --git a/src/Umbraco.Core/Services/Implement/LocalizationService.cs b/src/Umbraco.Core/Services/Implement/LocalizationService.cs index bf01605416..040996ca53 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizationService.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizationService.cs @@ -290,19 +290,6 @@ namespace Umbraco.Core.Services.Implement } } - /// - /// Gets a by its culture code - /// - /// Culture Name - also refered to as the Friendly name - /// - public ILanguage GetLanguageByCultureCode(string cultureName) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _languageRepository.GetByCultureName(cultureName); - } - } - /// /// Gets a by its iso code /// diff --git a/src/Umbraco.Tests/Persistence/Repositories/DictionaryRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DictionaryRepositoryTest.cs index 357015a9e5..3a7840dbf5 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DictionaryRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DictionaryRepositoryTest.cs @@ -39,7 +39,7 @@ namespace Umbraco.Tests.Persistence.Repositories { Translations = new List { - new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByCultureCode("en-US"), "Hello world") + new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"), "Hello world") } }; @@ -70,7 +70,7 @@ namespace Umbraco.Tests.Persistence.Repositories { Translations = new List { - new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByCultureCode("en-US"), "Hello world") + new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"), "Hello world") } }; @@ -100,7 +100,7 @@ namespace Umbraco.Tests.Persistence.Repositories { Translations = new List { - new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByCultureCode("en-US"), "Hello world") + new DictionaryTranslation(ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"), "Hello world") } }; @@ -371,7 +371,7 @@ namespace Umbraco.Tests.Persistence.Repositories public void CreateTestData() { - var language = ServiceContext.LocalizationService.GetLanguageByCultureCode("en-US"); + var language = ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"); var languageDK = new Language("da-DK") { CultureName = "da-DK" }; ServiceContext.LocalizationService.Save(languageDK);//Id 2 diff --git a/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs index fbf43a1889..8ef6416185 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/LanguageRepositoryTest.cs @@ -76,31 +76,6 @@ namespace Umbraco.Tests.Persistence.Repositories } } - [Test] - public void Can_Perform_Get_By_Culture_Name_On_LanguageRepository() - { - var provider = TestObjects.GetScopeProvider(Logger); - using (var scope = provider.CreateScope()) - { - var repository = CreateRepository(provider); - - var au = CultureInfo.GetCultureInfo("en-AU"); - var language = (ILanguage)new Language(au.Name) - { - CultureName = au.DisplayName - }; - repository.Save(language); - - //re-get - language = repository.GetByCultureName(au.DisplayName); - - // Assert - Assert.That(language, Is.Not.Null); - Assert.That(language.HasIdentity, Is.True); - Assert.That(language.CultureName, Is.EqualTo(au.DisplayName)); - Assert.That(language.IsoCode, Is.EqualTo(au.Name)); - } - } [Test] public void Get_When_Id_Doesnt_Exist_Returns_Null() diff --git a/src/Umbraco.Tests/Services/LocalizationServiceTests.cs b/src/Umbraco.Tests/Services/LocalizationServiceTests.cs index b2394200a1..c62f14a4b0 100644 --- a/src/Umbraco.Tests/Services/LocalizationServiceTests.cs +++ b/src/Umbraco.Tests/Services/LocalizationServiceTests.cs @@ -144,16 +144,7 @@ namespace Umbraco.Tests.Services //there's a call or two to get languages, so apart from that there should only be one call per level Assert.Less(scope.Database.AsUmbracoDatabase().SqlCount, 30); } - } - - [Test] - public void Can_Get_Language_By_Culture_Code() - { - var danish = ServiceContext.LocalizationService.GetLanguageByCultureCode("Danish"); - var english = ServiceContext.LocalizationService.GetLanguageByCultureCode("English"); - Assert.NotNull(danish); - Assert.NotNull(english); - } + } [Test] public void Can_GetLanguageById() diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 7c926f04f3..6fc04b6bcb 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -100,7 +100,7 @@ namespace Umbraco.Web.Routing else { var result = new List(); - var languageIds = new List(domainUris.Select(x => _localizationService.GetLanguageByCultureCode(x.Culture.Name)?.Id).Where(x => x.HasValue)); + var languageIds = new List(domainUris.Select(x => _localizationService.GetLanguageByIsoCode(x.Culture.Name)?.Id).Where(x => x.HasValue)); foreach (var langId in languageIds) { var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias, languageId: langId); From 43ca9593d4e610a02cf03aaf15a61c14caf5e347 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 16:29:55 +1000 Subject: [PATCH 20/58] fixes AliasUrlProvider --- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 39 ++++++------------- .../Runtime/WebRuntimeComponent.cs | 2 +- 2 files changed, 12 insertions(+), 29 deletions(-) diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 6fc04b6bcb..900af87931 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -70,9 +70,6 @@ namespace Umbraco.Web.Routing /// public IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, Uri current) { - if (!FindByUrlAliasEnabled) - return Enumerable.Empty(); // we have nothing to say - var node = umbracoContext.ContentCache.GetById(id); if (node == null) return Enumerable.Empty(); @@ -100,19 +97,21 @@ namespace Umbraco.Web.Routing else { var result = new List(); - var languageIds = new List(domainUris.Select(x => _localizationService.GetLanguageByIsoCode(x.Culture.Name)?.Id).Where(x => x.HasValue)); - foreach (var langId in languageIds) + var languageIsoCodesToIds = _localizationService.GetAllLanguages().ToDictionary(x => x.IsoCode, x => x.Id); + foreach(var domainUri in domainUris) { - var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias, languageId: langId); - if (!string.IsNullOrWhiteSpace(umbracoUrlName)) + if (languageIsoCodesToIds.TryGetValue(domainUri.Culture.Name, out var langId)) { - var path = "/" + umbracoUrlName; - - result.AddRange(domainUris - .Select(domainUri => new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path))) - .Select(uri => UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString())); + var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias, languageId: langId); + if (!string.IsNullOrWhiteSpace(umbracoUrlName)) + { + var path = "/" + umbracoUrlName; + var uri = new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path)); + result.Add(UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString()); + } } } + return result; } } @@ -121,22 +120,6 @@ namespace Umbraco.Web.Routing #region Utilities - private static bool FindByUrlAliasEnabled - { - get - { - //TODO: The ContentFinderResolver instance should be injected in ctor with DI instead of using singleton! - - // finder - if (Current.ContentFinders.Any(x => x is ContentFinderByUrlAlias)) - return true; - - - // anything else, we can't detect - return false; - } - } - string CombinePaths(string path1, string path2) { string path = path1.TrimEnd('/') + path2; diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index 820d846d9f..a0c482075a 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -159,7 +159,7 @@ namespace Umbraco.Web.Runtime .Append(); composition.Container.RegisterCollectionBuilder() - //.Append() // not enabled by default + .Append() .Append() .Append(); From 6db75d4226283e3925f06e30d9ad4f6ac2435139 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 17:11:09 +1000 Subject: [PATCH 21/58] Fixes PublishedContent.cs when the property index doesn't contain the alias index (due to adding a new property type and the json not matchin) --- src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index acfc5bdd31..b451b45a00 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -258,7 +258,12 @@ namespace Umbraco.Web.PublishedCache.NuCache public override IPublishedProperty GetProperty(string alias) { var index = _contentNode.ContentType.GetPropertyIndex(alias); - var property = index < 0 ? null : PropertiesArray[index]; + if (index < 0) return null; + //TODO: Should we log here? I think this can happen when property types are added/removed from the doc type and the json serialized properties + // no longer match the list of property types since that is how the PropertiesArray is populated. + //TODO: Does the PropertiesArray get repopulated on content save? + if (index > PropertiesArray.Length) return null; + var property = PropertiesArray[index]; return property; } From c5ca61f2490fd96b90f53c9073de8562ba193b21 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 17:15:35 +1000 Subject: [PATCH 22/58] Fixes PublishedContent.cs when the property index doesn't contain the alias index (due to adding a new property type and the json not matchin) --- src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index b451b45a00..a3120ecb68 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -261,8 +261,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (index < 0) return null; //TODO: Should we log here? I think this can happen when property types are added/removed from the doc type and the json serialized properties // no longer match the list of property types since that is how the PropertiesArray is populated. - //TODO: Does the PropertiesArray get repopulated on content save? - if (index > PropertiesArray.Length) return null; + if (index >= PropertiesArray.Length) return null; var property = PropertiesArray[index]; return property; } From 2e38f7b27b19490a94da745e81ad7cb21f633043 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 24 Apr 2018 17:28:57 +1000 Subject: [PATCH 23/58] Fixes PublishedContent.cs when the property index doesn't contain the alias index (due to adding a new property type and the json not matchin) --- .../PublishedCache/NuCache/PublishedContent.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index a3120ecb68..4502245c5a 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -36,7 +36,14 @@ namespace Umbraco.Web.PublishedCache.NuCache foreach (var propertyType in _contentNode.ContentType.PropertyTypes) { if (contentData.Properties.TryGetValue(propertyType.Alias, out var pdatas)) + { properties.Add(new Property(propertyType, this, pdatas, _publishedSnapshotAccessor)); + } + else + { + //it doesn't exist in our serialized json but we should add it as an empty property so they are in sync + properties.Add(new Property(propertyType, this, null, _publishedSnapshotAccessor)); + } } PropertiesArray = properties.ToArray(); } @@ -259,8 +266,7 @@ namespace Umbraco.Web.PublishedCache.NuCache { var index = _contentNode.ContentType.GetPropertyIndex(alias); if (index < 0) return null; - //TODO: Should we log here? I think this can happen when property types are added/removed from the doc type and the json serialized properties - // no longer match the list of property types since that is how the PropertiesArray is populated. + //fixme: This should not happen since we align the PropertiesArray with the property types in the ctor, if this does happen maybe we should throw a descriptive exception if (index >= PropertiesArray.Length) return null; var property = PropertiesArray[index]; return property; From f3bf5d86d2d29921f52afcced83d4bd0d43ea376 Mon Sep 17 00:00:00 2001 From: Stephan Date: Wed, 25 Apr 2018 15:25:47 +0200 Subject: [PATCH 24/58] Cleanup BTree --- .../DataSource/BTree.ContentDataSerializer.cs | 38 +++ .../BTree.ContentNodeKitSerializer.cs | 57 ++++ ....DictionaryOfCultureVariationSerializer.cs | 46 +++ ...Tree.DictionaryOfPropertyDataSerializer.cs | 71 +++++ .../NuCache/DataSource/BTree.cs | 280 +----------------- .../NuCache/DataSource/SerializerBase.cs | 107 +++++++ src/Umbraco.Web/Umbraco.Web.csproj | 5 + 7 files changed, 325 insertions(+), 279 deletions(-) create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentDataSerializer.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentNodeKitSerializer.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfCultureVariationSerializer.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs create mode 100644 src/Umbraco.Web/PublishedCache/NuCache/DataSource/SerializerBase.cs diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentDataSerializer.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentDataSerializer.cs new file mode 100644 index 0000000000..7c793b69bd --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentDataSerializer.cs @@ -0,0 +1,38 @@ +using System.IO; +using CSharpTest.Net.Serialization; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + class ContentDataSerializer : ISerializer + { + private static readonly DictionaryOfPropertyDataSerializer PropertiesSerializer = new DictionaryOfPropertyDataSerializer(); + private static readonly DictionaryOfCultureVariationSerializer CultureVariationsSerializer = new DictionaryOfCultureVariationSerializer(); + + public ContentData ReadFrom(Stream stream) + { + return new ContentData + { + Published = PrimitiveSerializer.Boolean.ReadFrom(stream), + Name = PrimitiveSerializer.String.ReadFrom(stream), + VersionId = PrimitiveSerializer.Int32.ReadFrom(stream), + VersionDate = PrimitiveSerializer.DateTime.ReadFrom(stream), + WriterId = PrimitiveSerializer.Int32.ReadFrom(stream), + TemplateId = PrimitiveSerializer.Int32.ReadFrom(stream), + Properties = PropertiesSerializer.ReadFrom(stream), + CultureInfos = CultureVariationsSerializer.ReadFrom(stream) + }; + } + + public void WriteTo(ContentData value, Stream stream) + { + PrimitiveSerializer.Boolean.WriteTo(value.Published, stream); + PrimitiveSerializer.String.WriteTo(value.Name, stream); + PrimitiveSerializer.Int32.WriteTo(value.VersionId, stream); + PrimitiveSerializer.DateTime.WriteTo(value.VersionDate, stream); + PrimitiveSerializer.Int32.WriteTo(value.WriterId, stream); + PrimitiveSerializer.Int32.WriteTo(value.TemplateId, stream); + PropertiesSerializer.WriteTo(value.Properties, stream); + CultureVariationsSerializer.WriteTo(value.CultureInfos, stream); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentNodeKitSerializer.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentNodeKitSerializer.cs new file mode 100644 index 0000000000..4303f97d3c --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.ContentNodeKitSerializer.cs @@ -0,0 +1,57 @@ +using System.IO; +using CSharpTest.Net.Serialization; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + internal class ContentNodeKitSerializer : ISerializer + { + static readonly ContentDataSerializer DataSerializer = new ContentDataSerializer(); + //static readonly ListOfIntSerializer ChildContentIdsSerializer = new ListOfIntSerializer(); + + public ContentNodeKit ReadFrom(Stream stream) + { + var kit = new ContentNodeKit + { + Node = new ContentNode( + PrimitiveSerializer.Int32.ReadFrom(stream), // id + PrimitiveSerializer.Guid.ReadFrom(stream), // uid + PrimitiveSerializer.Int32.ReadFrom(stream), // level + PrimitiveSerializer.String.ReadFrom(stream), // path + PrimitiveSerializer.Int32.ReadFrom(stream), // sort order + PrimitiveSerializer.Int32.ReadFrom(stream), // parent id + PrimitiveSerializer.DateTime.ReadFrom(stream), // date created + PrimitiveSerializer.Int32.ReadFrom(stream) // creator id + ), + ContentTypeId = PrimitiveSerializer.Int32.ReadFrom(stream) + }; + var hasDraft = PrimitiveSerializer.Boolean.ReadFrom(stream); + if (hasDraft) + kit.DraftData = DataSerializer.ReadFrom(stream); + var hasPublished = PrimitiveSerializer.Boolean.ReadFrom(stream); + if (hasPublished) + kit.PublishedData = DataSerializer.ReadFrom(stream); + return kit; + } + + public void WriteTo(ContentNodeKit value, Stream stream) + { + PrimitiveSerializer.Int32.WriteTo(value.Node.Id, stream); + PrimitiveSerializer.Guid.WriteTo(value.Node.Uid, stream); + PrimitiveSerializer.Int32.WriteTo(value.Node.Level, stream); + PrimitiveSerializer.String.WriteTo(value.Node.Path, stream); + PrimitiveSerializer.Int32.WriteTo(value.Node.SortOrder, stream); + PrimitiveSerializer.Int32.WriteTo(value.Node.ParentContentId, stream); + PrimitiveSerializer.DateTime.WriteTo(value.Node.CreateDate, stream); + PrimitiveSerializer.Int32.WriteTo(value.Node.CreatorId, stream); + PrimitiveSerializer.Int32.WriteTo(value.ContentTypeId, stream); + + PrimitiveSerializer.Boolean.WriteTo(value.DraftData != null, stream); + if (value.DraftData != null) + DataSerializer.WriteTo(value.DraftData, stream); + + PrimitiveSerializer.Boolean.WriteTo(value.PublishedData != null, stream); + if (value.PublishedData != null) + DataSerializer.WriteTo(value.PublishedData, stream); + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfCultureVariationSerializer.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfCultureVariationSerializer.cs new file mode 100644 index 0000000000..a835886254 --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfCultureVariationSerializer.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.IO; +using CSharpTest.Net.Serialization; +using Umbraco.Core; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + internal class DictionaryOfCultureVariationSerializer : SerializerBase, ISerializer> + { + public IReadOnlyDictionary ReadFrom(Stream stream) + { + var dict = new Dictionary(); + + // read variations count + var pcount = PrimitiveSerializer.Int32.ReadFrom(stream); + + // read each variation + for (var i = 0; i < pcount; i++) + { + var languageId = PrimitiveSerializer.String.ReadFrom(stream); + var cultureVariation = new CultureVariation { Name = ReadStringObject(stream) }; + dict[languageId] = cultureVariation; + } + return dict; + } + + private static readonly IReadOnlyDictionary Empty = new Dictionary(); + + public void WriteTo(IReadOnlyDictionary value, Stream stream) + { + var variations = value ?? Empty; + + // write variations count + PrimitiveSerializer.Int32.WriteTo(variations.Count, stream); + + // write each variation + foreach (var (culture, variation) in variations) + { + // fixme - it's weird we're dealing with cultures here, and languageId in properties + + PrimitiveSerializer.String.WriteTo(culture, stream); // should never be null + WriteObject(variation.Name, stream); // write an object in case it's null (though... should not happen) + } + } + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs new file mode 100644 index 0000000000..0b4d391a3a --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.DictionaryOfPropertyDataSerializer.cs @@ -0,0 +1,71 @@ +using System.Collections.Generic; +using System.IO; +using CSharpTest.Net.Serialization; +using Umbraco.Core; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + internal class DictionaryOfPropertyDataSerializer : SerializerBase, ISerializer> + { + public IDictionary ReadFrom(Stream stream) + { + var dict = new Dictionary(); + + // read properties count + var pcount = PrimitiveSerializer.Int32.ReadFrom(stream); + + // read each property + for (var i = 0; i < pcount; i++) + { + // read property alias + var key = PrimitiveSerializer.String.ReadFrom(stream); + + // read values count + var vcount = PrimitiveSerializer.Int32.ReadFrom(stream); + + // create pdata and add to the dictionary + var pdatas = new List(); + + // for each value, read and add to pdata + for (var j = 0; j < vcount; j++) + { + var pdata = new PropertyData(); + pdatas.Add(pdata); + + // everything that can be null is read/written as object + pdata.LanguageId = ReadIntObject(stream); + pdata.Segment = ReadStringObject(stream); + pdata.Value = ReadObject(stream); + } + + dict[key] = pdatas.ToArray(); + } + return dict; + } + + public void WriteTo(IDictionary value, Stream stream) + { + // write properties count + PrimitiveSerializer.Int32.WriteTo(value.Count, stream); + + // write each property + foreach (var (alias, values) in value) + { + // write alias + PrimitiveSerializer.String.WriteTo(alias, stream); + + // write values count + PrimitiveSerializer.Int32.WriteTo(values.Length, stream); + + // write each value + foreach (var pdata in values) + { + // everything that can be null is read/written as object + WriteObject(pdata.LanguageId, stream); + WriteObject(pdata.Segment, stream); + WriteObject(pdata.Value, stream); + } + } + } + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs index 7329033405..1b17e0c124 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/BTree.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using CSharpTest.Net.Collections; +using CSharpTest.Net.Collections; using CSharpTest.Net.Serialization; namespace Umbraco.Web.PublishedCache.NuCache.DataSource @@ -28,91 +25,6 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource return tree; } - private class ContentNodeKitSerializer : ISerializer - { - static readonly ContentDataSerializer DataSerializer = new ContentDataSerializer(); - //static readonly ListOfIntSerializer ChildContentIdsSerializer = new ListOfIntSerializer(); - - public ContentNodeKit ReadFrom(Stream stream) - { - var kit = new ContentNodeKit - { - Node = new ContentNode( - PrimitiveSerializer.Int32.ReadFrom(stream), // id - PrimitiveSerializer.Guid.ReadFrom(stream), // uid - PrimitiveSerializer.Int32.ReadFrom(stream), // level - PrimitiveSerializer.String.ReadFrom(stream), // path - PrimitiveSerializer.Int32.ReadFrom(stream), // sort order - PrimitiveSerializer.Int32.ReadFrom(stream), // parent id - PrimitiveSerializer.DateTime.ReadFrom(stream), // date created - PrimitiveSerializer.Int32.ReadFrom(stream) // creator id - ), - ContentTypeId = PrimitiveSerializer.Int32.ReadFrom(stream) - }; - var hasDraft = PrimitiveSerializer.Boolean.ReadFrom(stream); - if (hasDraft) - kit.DraftData = DataSerializer.ReadFrom(stream); - var hasPublished = PrimitiveSerializer.Boolean.ReadFrom(stream); - if (hasPublished) - kit.PublishedData = DataSerializer.ReadFrom(stream); - return kit; - } - - public void WriteTo(ContentNodeKit value, Stream stream) - { - PrimitiveSerializer.Int32.WriteTo(value.Node.Id, stream); - PrimitiveSerializer.Guid.WriteTo(value.Node.Uid, stream); - PrimitiveSerializer.Int32.WriteTo(value.Node.Level, stream); - PrimitiveSerializer.String.WriteTo(value.Node.Path, stream); - PrimitiveSerializer.Int32.WriteTo(value.Node.SortOrder, stream); - PrimitiveSerializer.Int32.WriteTo(value.Node.ParentContentId, stream); - PrimitiveSerializer.DateTime.WriteTo(value.Node.CreateDate, stream); - PrimitiveSerializer.Int32.WriteTo(value.Node.CreatorId, stream); - PrimitiveSerializer.Int32.WriteTo(value.ContentTypeId, stream); - - PrimitiveSerializer.Boolean.WriteTo(value.DraftData != null, stream); - if (value.DraftData != null) - DataSerializer.WriteTo(value.DraftData, stream); - - PrimitiveSerializer.Boolean.WriteTo(value.PublishedData != null, stream); - if (value.PublishedData != null) - DataSerializer.WriteTo(value.PublishedData, stream); - } - } - - class ContentDataSerializer : ISerializer - { - private static readonly DictionaryOfPropertyDataSerializer PropertiesSerializer = new DictionaryOfPropertyDataSerializer(); - private static readonly DictionaryOfCultureVariationSerializer CultureVariationsSerializer = new DictionaryOfCultureVariationSerializer(); - - public ContentData ReadFrom(Stream stream) - { - return new ContentData - { - Published = PrimitiveSerializer.Boolean.ReadFrom(stream), - Name = PrimitiveSerializer.String.ReadFrom(stream), - VersionId = PrimitiveSerializer.Int32.ReadFrom(stream), - VersionDate = PrimitiveSerializer.DateTime.ReadFrom(stream), - WriterId = PrimitiveSerializer.Int32.ReadFrom(stream), - TemplateId = PrimitiveSerializer.Int32.ReadFrom(stream), - Properties = PropertiesSerializer.ReadFrom(stream), - CultureInfos = CultureVariationsSerializer.ReadFrom(stream) - }; - } - - public void WriteTo(ContentData value, Stream stream) - { - PrimitiveSerializer.Boolean.WriteTo(value.Published, stream); - PrimitiveSerializer.String.WriteTo(value.Name, stream); - PrimitiveSerializer.Int32.WriteTo(value.VersionId, stream); - PrimitiveSerializer.DateTime.WriteTo(value.VersionDate, stream); - PrimitiveSerializer.Int32.WriteTo(value.WriterId, stream); - PrimitiveSerializer.Int32.WriteTo(value.TemplateId, stream); - PropertiesSerializer.WriteTo(value.Properties, stream); - CultureVariationsSerializer.WriteTo(value.CultureInfos, stream); - } - } - /* class ListOfIntSerializer : ISerializer> { @@ -133,195 +45,5 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } } */ - - private class DictionaryOfCultureVariationSerializer : ISerializer> - { - public IReadOnlyDictionary ReadFrom(Stream stream) - { - var dict = new Dictionary(); - - // read values count - var pcount = PrimitiveSerializer.Int32.ReadFrom(stream); - - // read each property - for (var i = 0; i < pcount; i++) - { - // read lang id - var key = PrimitiveSerializer.String.ReadFrom(stream); - - var val = new CultureVariation(); - - // read variation info - //TODO: This is supporting multiple properties but we only have one currently - var type = PrimitiveSerializer.Char.ReadFrom(stream); - switch(type) - { - case 'N': - val.Name = PrimitiveSerializer.String.ReadFrom(stream); - break; - default: - throw new ArgumentOutOfRangeException(); - } - - dict[key] = val; - } - return dict; - } - - private static readonly IReadOnlyDictionary Empty = new Dictionary(); - - public void WriteTo(IReadOnlyDictionary value, Stream stream) - { - var valToSerialize = value; - if (valToSerialize == null) - { - valToSerialize = Empty; - } - - // write values count - PrimitiveSerializer.Int32.WriteTo(valToSerialize.Count, stream); - - // write each name - foreach (var kvp in valToSerialize) - { - // write alias - PrimitiveSerializer.String.WriteTo(kvp.Key, stream); - - // write name - PrimitiveSerializer.Char.WriteTo('N', stream); - PrimitiveSerializer.String.WriteTo(kvp.Value.Name, stream); - //TODO: This is supporting multiple properties but we only have one currently - } - } - - } - - private class DictionaryOfPropertyDataSerializer : ISerializer> - { - public IDictionary ReadFrom(Stream stream) - { - var dict = new Dictionary(); - - // read properties count - var pcount = PrimitiveSerializer.Int32.ReadFrom(stream); - - // read each property - for (var i = 0; i < pcount; i++) - { - // read property alias - var key = PrimitiveSerializer.String.ReadFrom(stream); - - // read values count - var vcount = PrimitiveSerializer.Int32.ReadFrom(stream); - - // create pdata and add to the dictionary - var pdatas = new List(); - - // for each value, read and add to pdata - for (var j = 0; j < vcount; j++) - { - var pdata = new PropertyData(); - pdatas.Add(pdata); - - var type = PrimitiveSerializer.Char.ReadFrom(stream); - pdata.LanguageId = (int?) ReadObject(type, stream); - type = PrimitiveSerializer.Char.ReadFrom(stream); - pdata.Segment = (string) ReadObject(type, stream); - type = PrimitiveSerializer.Char.ReadFrom(stream); - pdata.Value = ReadObject(type, stream); - } - - dict[key] = pdatas.ToArray(); - } - return dict; - } - - private object ReadObject(char type, Stream stream) - { - switch (type) - { - case 'N': - return null; - case 'S': - return PrimitiveSerializer.String.ReadFrom(stream); - case 'I': - return PrimitiveSerializer.Int32.ReadFrom(stream); - case 'L': - return PrimitiveSerializer.Int64.ReadFrom(stream); - case 'F': - return PrimitiveSerializer.Float.ReadFrom(stream); - case 'B': - return PrimitiveSerializer.Double.ReadFrom(stream); - case 'D': - return PrimitiveSerializer.DateTime.ReadFrom(stream); - default: - throw new NotSupportedException("Cannot deserialize '" + type + "' value."); - } - } - - public void WriteTo(IDictionary value, Stream stream) - { - // write properties count - PrimitiveSerializer.Int32.WriteTo(value.Count, stream); - - // write each property - foreach (var kvp in value) - { - // write alias - PrimitiveSerializer.String.WriteTo(kvp.Key, stream); - - // write values count - PrimitiveSerializer.Int32.WriteTo(kvp.Value.Length, stream); - - // write each value - foreach (var pdata in kvp.Value) - { - WriteObject(pdata.LanguageId, stream); - WriteObject(pdata.Segment, stream); - WriteObject(pdata.Value, stream); - } - } - } - - private void WriteObject(object value, Stream stream) - { - if (value == null) - { - PrimitiveSerializer.Char.WriteTo('N', stream); - } - else if (value is string stringValue) - { - PrimitiveSerializer.Char.WriteTo('S', stream); - PrimitiveSerializer.String.WriteTo(stringValue, stream); - } - else if (value is int intValue) - { - PrimitiveSerializer.Char.WriteTo('I', stream); - PrimitiveSerializer.Int32.WriteTo(intValue, stream); - } - else if (value is long longValue) - { - PrimitiveSerializer.Char.WriteTo('L', stream); - PrimitiveSerializer.Int64.WriteTo(longValue, stream); - } - else if (value is float floatValue) - { - PrimitiveSerializer.Char.WriteTo('F', stream); - PrimitiveSerializer.Float.WriteTo(floatValue, stream); - } - else if (value is double doubleValue) - { - PrimitiveSerializer.Char.WriteTo('B', stream); - PrimitiveSerializer.Double.WriteTo(doubleValue, stream); - } - else if (value is DateTime dateValue) - { - PrimitiveSerializer.Char.WriteTo('D', stream); - PrimitiveSerializer.DateTime.WriteTo(dateValue, stream); - } - else - throw new NotSupportedException("Value type " + value.GetType().FullName + " cannot be serialized."); - } - } } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/SerializerBase.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/SerializerBase.cs new file mode 100644 index 0000000000..01f0bbad9b --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/SerializerBase.cs @@ -0,0 +1,107 @@ +using System; +using System.IO; +using CSharpTest.Net.Serialization; + +namespace Umbraco.Web.PublishedCache.NuCache.DataSource +{ + internal abstract class SerializerBase + { + protected string ReadString(Stream stream) => PrimitiveSerializer.String.ReadFrom(stream); + protected int ReadInt(Stream stream) => PrimitiveSerializer.Int32.ReadFrom(stream); + protected long ReadLong(Stream stream) => PrimitiveSerializer.Int64.ReadFrom(stream); + protected float ReadFloat(Stream stream) => PrimitiveSerializer.Float.ReadFrom(stream); + protected double ReadDouble(Stream stream) => PrimitiveSerializer.Double.ReadFrom(stream); + protected DateTime ReadDateTime(Stream stream) => PrimitiveSerializer.DateTime.ReadFrom(stream); + + private T? ReadObject(Stream stream, char t, Func read) + where T : struct + { + var type = PrimitiveSerializer.Char.ReadFrom(stream); + if (type == 'N') return null; + if (type != t) + throw new NotSupportedException($"Cannot deserialize type '{type}', expected '{t}'."); + return read(stream); + } + + protected string ReadStringObject(Stream stream) // required 'cos string is not a struct + { + var type = PrimitiveSerializer.Char.ReadFrom(stream); + if (type == 'N') return null; + if (type != 'S') + throw new NotSupportedException($"Cannot deserialize type '{type}', expected 'S'."); + return PrimitiveSerializer.String.ReadFrom(stream); + } + + protected int? ReadIntObject(Stream stream) => ReadObject(stream, 'I', ReadInt); + protected long? ReadLongObject(Stream stream) => ReadObject(stream, 'L', ReadLong); + protected float? ReadFloatObject(Stream stream) => ReadObject(stream, 'F', ReadFloat); + protected double? ReadDoubleObject(Stream stream) => ReadObject(stream, 'B', ReadDouble); + protected DateTime? ReadDateTimeObject(Stream stream) => ReadObject(stream, 'D', ReadDateTime); + + protected object ReadObject(Stream stream) + => ReadObject(PrimitiveSerializer.Char.ReadFrom(stream), stream); + + protected object ReadObject(char type, Stream stream) + { + switch (type) + { + case 'N': + return null; + case 'S': + return PrimitiveSerializer.String.ReadFrom(stream); + case 'I': + return PrimitiveSerializer.Int32.ReadFrom(stream); + case 'L': + return PrimitiveSerializer.Int64.ReadFrom(stream); + case 'F': + return PrimitiveSerializer.Float.ReadFrom(stream); + case 'B': + return PrimitiveSerializer.Double.ReadFrom(stream); + case 'D': + return PrimitiveSerializer.DateTime.ReadFrom(stream); + default: + throw new NotSupportedException($"Cannot deserialize unknow type '{type}'."); + } + } + + protected void WriteObject(object value, Stream stream) + { + if (value == null) + { + PrimitiveSerializer.Char.WriteTo('N', stream); + } + else if (value is string stringValue) + { + PrimitiveSerializer.Char.WriteTo('S', stream); + PrimitiveSerializer.String.WriteTo(stringValue, stream); + } + else if (value is int intValue) + { + PrimitiveSerializer.Char.WriteTo('I', stream); + PrimitiveSerializer.Int32.WriteTo(intValue, stream); + } + else if (value is long longValue) + { + PrimitiveSerializer.Char.WriteTo('L', stream); + PrimitiveSerializer.Int64.WriteTo(longValue, stream); + } + else if (value is float floatValue) + { + PrimitiveSerializer.Char.WriteTo('F', stream); + PrimitiveSerializer.Float.WriteTo(floatValue, stream); + } + else if (value is double doubleValue) + { + PrimitiveSerializer.Char.WriteTo('B', stream); + PrimitiveSerializer.Double.WriteTo(doubleValue, stream); + } + else if (value is DateTime dateValue) + { + PrimitiveSerializer.Char.WriteTo('D', stream); + PrimitiveSerializer.DateTime.WriteTo(dateValue, stream); + } + else + throw new NotSupportedException("Value type " + value.GetType().FullName + " cannot be serialized."); + } + } +} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 65ca4c44b4..01e064d398 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -342,9 +342,14 @@ + + + + + From 40f94d23d4e0c28fa114b0cd3950b1198b80cb5e Mon Sep 17 00:00:00 2001 From: Stephan Date: Wed, 25 Apr 2018 15:55:27 +0200 Subject: [PATCH 25/58] Cleanup --- ...SerializedData.cs => ContentNestedData.cs} | 2 +- .../NuCache/DataSource/Database.cs | 22 +++++++++---------- .../NuCache/PublishedContent.cs | 19 ++++++---------- .../NuCache/PublishedSnapshotService.cs | 14 ++++++------ src/Umbraco.Web/Umbraco.Web.csproj | 2 +- 5 files changed, 27 insertions(+), 32 deletions(-) rename src/Umbraco.Web/PublishedCache/NuCache/DataSource/{ContentSerializedData.cs => ContentNestedData.cs} (91%) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentNestedData.cs similarity index 91% rename from src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs rename to src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentNestedData.cs index b2cb22a74b..be3e813275 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentSerializedData.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/ContentNestedData.cs @@ -6,7 +6,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource /// /// The content item 1:M data that is serialized to JSON /// - internal class ContentSerializedData + internal class ContentNestedData { [JsonProperty("properties")] public Dictionary PropertyData { get; set; } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs index 2c4249cd08..342ad5b59f 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/Database.cs @@ -190,7 +190,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } else { - var deserialized = DeserializeData(dto.EditData); + var nested = DeserializeNestedData(dto.EditData); d = new ContentData { @@ -200,8 +200,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.EditVersionDate, WriterId = dto.EditWriterId, - Properties = deserialized.PropertyData, - CultureInfos = deserialized.CultureData + Properties = nested.PropertyData, + CultureInfos = nested.CultureData }; } @@ -215,7 +215,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource } else { - var deserialized = DeserializeData(dto.PubData); + var nested = DeserializeNestedData(dto.PubData); p = new ContentData { @@ -225,8 +225,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.PubVersionDate, WriterId = dto.PubWriterId, - Properties = deserialized.PropertyData, - CultureInfos = deserialized.CultureData + Properties = nested.PropertyData, + CultureInfos = nested.CultureData }; } } @@ -250,7 +250,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource if (dto.EditData == null) throw new Exception("No data for media " + dto.Id); - var deserialized = DeserializeData(dto.EditData); + var nested = DeserializeNestedData(dto.EditData); var p = new ContentData { @@ -260,8 +260,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource VersionId = dto.VersionId, VersionDate = dto.EditVersionDate, WriterId = dto.CreatorId, // what-else? - Properties = deserialized.PropertyData, - CultureInfos = deserialized.CultureData + Properties = nested.PropertyData, + CultureInfos = nested.CultureData }; var n = new ContentNode(dto.Id, dto.Uid, @@ -277,7 +277,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource return s; } - private static ContentSerializedData DeserializeData(string data) + private static ContentNestedData DeserializeNestedData(string data) { // by default JsonConvert will deserialize our numeric values as Int64 // which is bad, because they were Int32 in the database - take care @@ -287,7 +287,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource Converters = new List { new ForceInt32Converter() } }; - return JsonConvert.DeserializeObject(data, settings); + return JsonConvert.DeserializeObject(data, settings); } } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 4502245c5a..883a43a7d5 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -35,15 +35,10 @@ namespace Umbraco.Web.PublishedCache.NuCache var properties = new List(); foreach (var propertyType in _contentNode.ContentType.PropertyTypes) { - if (contentData.Properties.TryGetValue(propertyType.Alias, out var pdatas)) - { - properties.Add(new Property(propertyType, this, pdatas, _publishedSnapshotAccessor)); - } - else - { - //it doesn't exist in our serialized json but we should add it as an empty property so they are in sync - properties.Add(new Property(propertyType, this, null, _publishedSnapshotAccessor)); - } + // add one property per property type - this is required, for the indexing to work + // if contentData supplies pdatas, use them, else use null + contentData.Properties.TryGetValue(propertyType.Alias, out var pdatas); // else will be null + properties.Add(new Property(propertyType, this, pdatas, _publishedSnapshotAccessor)); } PropertiesArray = properties.ToArray(); } @@ -265,9 +260,9 @@ namespace Umbraco.Web.PublishedCache.NuCache public override IPublishedProperty GetProperty(string alias) { var index = _contentNode.ContentType.GetPropertyIndex(alias); - if (index < 0) return null; - //fixme: This should not happen since we align the PropertiesArray with the property types in the ctor, if this does happen maybe we should throw a descriptive exception - if (index >= PropertiesArray.Length) return null; + if (index < 0) return null; // happens when 'alias' does not match a content type property alias + if (index >= PropertiesArray.Length) // should never happen - properties array must be in sync with property type + throw new IndexOutOfRangeException("Index points outside the properties array, which means the properties array is corrupt."); var property = PropertiesArray[index]; return property; } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index eae0fd50b5..faff5e9793 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -1179,9 +1179,6 @@ namespace Umbraco.Web.PublishedCache.NuCache //var propertyEditorResolver = PropertyEditorResolver.Current; //var dataTypeService = ApplicationContext.Current.Services.DataTypeService; - //the dictionary that will be serialized - var data = new ContentSerializedData(); - var propertyData = new Dictionary(); foreach (var prop in content.Properties) { @@ -1216,8 +1213,6 @@ namespace Umbraco.Web.PublishedCache.NuCache propertyData[prop.Alias] = pdatas.ToArray(); } - data.PropertyData = propertyData; - var cultureData = new Dictionary(); if (content.Names != null) { @@ -1233,7 +1228,12 @@ namespace Umbraco.Web.PublishedCache.NuCache } } - data.CultureData = cultureData; + //the dictionary that will be serialized + var nestedData = new ContentNestedData + { + PropertyData = propertyData, + CultureData = cultureData + }; var dto = new ContentNuDto { @@ -1243,7 +1243,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // note that numeric values (which are Int32) are serialized without their // type (eg "value":1234) and JsonConvert by default deserializes them as Int64 - Data = JsonConvert.SerializeObject(data) + Data = JsonConvert.SerializeObject(nestedData) }; //Core.Composing.Current.Logger.Debug(dto.Data); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 01e064d398..98afb387d4 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -346,7 +346,7 @@ - + From 23c40cbf2c5df6096e1657275c67b21af496bd64 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 26 Apr 2018 21:37:29 +1000 Subject: [PATCH 26/58] Fixes a couple issues, changes name from PublishValues to TryPublishValues --- src/Umbraco.Core/Models/Content.cs | 14 +- src/Umbraco.Core/Models/ContentExtensions.cs | 2 +- src/Umbraco.Core/Models/IContent.cs | 6 +- .../Implement/DocumentRepository.cs | 10 +- .../Publishing/ScheduledPublisher.cs | 2 +- .../Services/Implement/ContentService.cs | 4 +- .../Integration/ContentEventsTests.cs | 146 +++++++++--------- src/Umbraco.Tests/Models/VariationTests.cs | 12 +- .../NPocoTests/PetaPocoCachesTest.cs | 4 +- .../Repositories/ContentRepositoryTest.cs | 8 +- .../Scoping/ScopedNuCacheTests.cs | 4 +- src/Umbraco.Tests/Scoping/ScopedXmlTests.cs | 8 +- .../Services/ContentServiceTests.cs | 124 +++++++-------- .../Services/ContentTypeServiceTests.cs | 20 +-- .../Services/PerformanceTests.cs | 4 +- src/Umbraco.Tests/Services/TagServiceTests.cs | 14 +- src/Umbraco.Web/Editors/ContentController.cs | 14 +- .../Mapping/ContentItemDisplayNameResolver.cs | 8 +- .../WebServices/BulkPublishController.cs | 2 +- 19 files changed, 208 insertions(+), 198 deletions(-) diff --git a/src/Umbraco.Core/Models/Content.cs b/src/Umbraco.Core/Models/Content.cs index 4ead233d6a..708f0ac853 100644 --- a/src/Umbraco.Core/Models/Content.cs +++ b/src/Umbraco.Core/Models/Content.cs @@ -306,11 +306,11 @@ namespace Umbraco.Core.Models public bool Blueprint { get; internal set; } /// - public virtual bool PublishAllValues() + public virtual bool TryPublishAllValues() { // the values we want to publish should be valid if (ValidateAll().Any()) - return false; + return false; //fixme this should return an attempt with error results // Name and PublishName are managed by the repository, but Names and PublishNames // must be managed here as they depend on the existing / supported variations. @@ -321,7 +321,8 @@ namespace Umbraco.Core.Models foreach (var (culture, name) in Names) { if (string.IsNullOrWhiteSpace(name)) - throw new InvalidOperationException($"Cannot publish {culture ?? "invariant"} culture without a name."); + return false; //fixme this should return an attempt with error results + SetPublishInfos(culture, name, now); } @@ -334,14 +335,14 @@ namespace Umbraco.Core.Models } /// - public virtual bool PublishValues(string culture = null, string segment = null) + public virtual bool TryPublishValues(string culture = null, string segment = null) { // the variation should be supported by the content type ContentType.ValidateVariation(culture, segment, throwIfInvalid: true); // the values we want to publish should be valid if (Validate(culture, segment).Any()) - return false; + return false; //fixme this should return an attempt with error results // Name and PublishName are managed by the repository, but Names and PublishNames // must be managed here as they depend on the existing / supported variations. @@ -349,7 +350,8 @@ namespace Umbraco.Core.Models { var name = GetName(culture); if (string.IsNullOrWhiteSpace(name)) - throw new InvalidOperationException($"Cannot publish {culture ?? "invariant"} culture without a name."); + return false; //fixme this should return an attempt with error results + SetPublishInfos(culture, name, DateTime.Now); } diff --git a/src/Umbraco.Core/Models/ContentExtensions.cs b/src/Umbraco.Core/Models/ContentExtensions.cs index 0940675346..c0e4214881 100644 --- a/src/Umbraco.Core/Models/ContentExtensions.cs +++ b/src/Umbraco.Core/Models/ContentExtensions.cs @@ -168,7 +168,7 @@ namespace Umbraco.Core.Models public static bool HasPropertyTypeVaryingByCulture(this IContent content) { // fixme - what about CultureSegment? what about content.ContentType.Variations? - return content.PropertyTypes.Any(x => x.Variations == ContentVariation.CultureNeutral); + return content.PropertyTypes.Any(x => x.Variations.Has(ContentVariation.CultureNeutral)); } #endregion diff --git a/src/Umbraco.Core/Models/IContent.cs b/src/Umbraco.Core/Models/IContent.cs index 25f980a597..2f3fd06f5f 100644 --- a/src/Umbraco.Core/Models/IContent.cs +++ b/src/Umbraco.Core/Models/IContent.cs @@ -169,7 +169,8 @@ namespace Umbraco.Core.Models /// The document must then be published via the content service. /// Values are not published if they are not valie. /// - bool PublishAllValues(); + //fixme return an Attempt with some error results if it doesn't work + bool TryPublishAllValues(); /// /// Publishes values. @@ -179,7 +180,8 @@ namespace Umbraco.Core.Models /// The document must then be published via the content service. /// Values are not published if they are not valid. /// - bool PublishValues(string culture = null, string segment = null); + //fixme return an Attempt with some error results if it doesn't work + bool TryPublishValues(string culture = null, string segment = null); /// /// Publishes the culture/any values. diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs index e47e8aa33e..76321abe6a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs @@ -341,10 +341,10 @@ namespace Umbraco.Core.Persistence.Repositories.Implement (editedCultures ?? (editedCultures = new HashSet(StringComparer.OrdinalIgnoreCase))).Add(culture); // insert content variations - Database.InsertBulk(GetContentVariationDtos(content, publishing)); + Database.BulkInsertRecords(GetContentVariationDtos(content, publishing)); // insert document variations - Database.InsertBulk(GetDocumentVariationDtos(content, publishing, editedCultures)); + Database.BulkInsertRecords(GetDocumentVariationDtos(content, publishing, editedCultures)); } // refresh content @@ -501,14 +501,14 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var deleteDocumentVariations = Sql().Delete().Where(x => x.NodeId == content.Id); Database.Execute(deleteDocumentVariations); - // fixme is it OK to use NPoco InsertBulk here, or should we use our own BulkInsertRecords? + // fixme is we'd like to use the native NPoco InsertBulk here but it causes problems (not sure exaclty all scenarios) but by using SQL Server and updating a variants name will cause: Unable to cast object of type 'Umbraco.Core.Persistence.FaultHandling.RetryDbConnection' to type 'System.Data.SqlClient.SqlConnection'. // (same in PersistNewItem above) // insert content variations - Database.InsertBulk(GetContentVariationDtos(content, publishing)); + Database.BulkInsertRecords(GetContentVariationDtos(content, publishing)); // insert document variations - Database.InsertBulk(GetDocumentVariationDtos(content, publishing, editedCultures)); + Database.BulkInsertRecords(GetDocumentVariationDtos(content, publishing, editedCultures)); } // refresh content diff --git a/src/Umbraco.Core/Publishing/ScheduledPublisher.cs b/src/Umbraco.Core/Publishing/ScheduledPublisher.cs index bb09195691..b16cd961f0 100644 --- a/src/Umbraco.Core/Publishing/ScheduledPublisher.cs +++ b/src/Umbraco.Core/Publishing/ScheduledPublisher.cs @@ -39,7 +39,7 @@ namespace Umbraco.Core.Publishing try { d.ReleaseDate = null; - d.PublishValues(); // fixme variants? + d.TryPublishValues(); // fixme variants? var result = _contentService.SaveAndPublish(d, d.GetWriterProfile().Id); _logger.Debug($"Result of publish attempt: {result.Result}"); if (result.Success == false) diff --git a/src/Umbraco.Core/Services/Implement/ContentService.cs b/src/Umbraco.Core/Services/Implement/ContentService.cs index 84e616d4d7..fc37000e13 100644 --- a/src/Umbraco.Core/Services/Implement/ContentService.cs +++ b/src/Umbraco.Core/Services/Implement/ContentService.cs @@ -1070,7 +1070,7 @@ namespace Umbraco.Core.Services.Implement try { d.ReleaseDate = null; - d.PublishValues(); // fixme variants? + d.TryPublishValues(); // fixme variants? result = SaveAndPublish(d, d.WriterId); if (result.Success == false) Logger.Error($"Failed to publish document id={d.Id}, reason={result.Result}."); @@ -1110,7 +1110,7 @@ namespace Umbraco.Core.Services.Implement bool IsEditing(IContent c, string l, string s) => c.Properties.Any(x => x.Values.Where(y => y.Culture == l && y.Segment == s).Any(y => y.EditedValue != y.PublishedValue)); - return SaveAndPublishBranch(content, force, document => IsEditing(document, culture, segment), document => document.PublishValues(culture, segment), userId); + return SaveAndPublishBranch(content, force, document => IsEditing(document, culture, segment), document => document.TryPublishValues(culture, segment), userId); } /// diff --git a/src/Umbraco.Tests/Integration/ContentEventsTests.cs b/src/Umbraco.Tests/Integration/ContentEventsTests.cs index 502178377e..c87774ba27 100644 --- a/src/Umbraco.Tests/Integration/ContentEventsTests.cs +++ b/src/Umbraco.Tests/Integration/ContentEventsTests.cs @@ -106,17 +106,17 @@ namespace Umbraco.Tests.Integration private IContent CreateBranch() { var content1 = MockedContent.CreateSimpleContent(_contentType, "Content1"); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); // 2 (published) // .1 (published) // .2 (not published) var content2 = MockedContent.CreateSimpleContent(_contentType, "Content2", content1); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content21 = MockedContent.CreateSimpleContent(_contentType, "Content21", content2); - content21.PublishValues(); + content21.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content21); var content22 = MockedContent.CreateSimpleContent(_contentType, "Content22", content2); ServiceContext.ContentService.Save(content22); @@ -135,12 +135,12 @@ namespace Umbraco.Tests.Integration // .1 (published) // .2 (not published) var content4 = MockedContent.CreateSimpleContent(_contentType, "Content4", content1); - content4.PublishValues(); + content4.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content4); content4.Name = "Content4X"; ServiceContext.ContentService.Save(content4); var content41 = MockedContent.CreateSimpleContent(_contentType, "Content41", content4); - content41.PublishValues(); + content41.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content41); var content42 = MockedContent.CreateSimpleContent(_contentType, "Content42", content4); ServiceContext.ContentService.Save(content42); @@ -149,10 +149,10 @@ namespace Umbraco.Tests.Integration // .1 (published) // .2 (not published) var content5 = MockedContent.CreateSimpleContent(_contentType, "Content5", content1); - content5.PublishValues(); + content5.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content5); var content51 = MockedContent.CreateSimpleContent(_contentType, "Content51", content5); - content51.PublishValues(); + content51.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content51); var content52 = MockedContent.CreateSimpleContent(_contentType, "Content52", content5); ServiceContext.ContentService.Save(content52); @@ -439,7 +439,7 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -476,7 +476,7 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -513,7 +513,7 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -553,7 +553,7 @@ namespace Umbraco.Tests.Integration ResetEvents(); content.Name = "changed"; - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.AreEqual(2, _msgCount); @@ -574,12 +574,12 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); content.Name = "changed"; - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.AreEqual(2, _msgCount); @@ -606,7 +606,7 @@ namespace Umbraco.Tests.Integration ResetEvents(); content.Name = "changed"; - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.AreEqual(2, _msgCount); @@ -630,12 +630,12 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); content.Name = "changed"; - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.AreEqual(2, _msgCount); @@ -656,7 +656,7 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -680,7 +680,7 @@ namespace Umbraco.Tests.Integration var content = ServiceContext.ContentService.GetRootContent().FirstOrDefault(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); content.Name = "changed"; ServiceContext.ContentService.Save(content); @@ -741,7 +741,7 @@ namespace Umbraco.Tests.Integration ServiceContext.ContentService.Unpublish(content1); ResetEvents(); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); Assert.AreEqual(2, _msgCount); @@ -984,7 +984,7 @@ namespace Umbraco.Tests.Integration var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -1008,7 +1008,7 @@ namespace Umbraco.Tests.Integration var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ServiceContext.ContentService.MoveToRecycleBin(content); @@ -1033,7 +1033,7 @@ namespace Umbraco.Tests.Integration var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); content.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content); @@ -1204,7 +1204,7 @@ namespace Umbraco.Tests.Integration { var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -1224,7 +1224,7 @@ namespace Umbraco.Tests.Integration { var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); content.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content); @@ -1246,11 +1246,11 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ServiceContext.ContentService.Unpublish(content1); @@ -1332,7 +1332,7 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); @@ -1354,7 +1354,7 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content1); @@ -1380,7 +1380,7 @@ namespace Umbraco.Tests.Integration Assert.IsNotNull(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ResetEvents(); @@ -1402,11 +1402,11 @@ namespace Umbraco.Tests.Integration Assert.IsNotNull(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content3 = CreateContent(); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ServiceContext.ContentService.Unpublish(content2); @@ -1427,11 +1427,11 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ResetEvents(); @@ -1451,15 +1451,15 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ServiceContext.ContentService.Unpublish(content2); @@ -1480,13 +1480,13 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ResetEvents(); @@ -1506,17 +1506,17 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); content1.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content1); var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ServiceContext.ContentService.Unpublish(content2); @@ -1537,16 +1537,16 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ServiceContext.ContentService.Unpublish(content1); var content3 = CreateContent(); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ResetEvents(); @@ -1566,20 +1566,20 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ServiceContext.ContentService.Unpublish(content1); var content3 = CreateContent(); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); var content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); - content4.PublishValues(); + content4.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content4); ServiceContext.ContentService.Unpublish(content3); @@ -1600,18 +1600,18 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content2); ServiceContext.ContentService.Unpublish(content1); var content3 = CreateContent(); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ResetEvents(); @@ -1631,22 +1631,22 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content2); ServiceContext.ContentService.Unpublish(content1); var content3 = CreateContent(); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); var content4 = CreateContent(content3.Id); Assert.IsNotNull(content4); - content4.PublishValues(); + content4.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content4); ServiceContext.ContentService.Unpublish(content3); @@ -1667,11 +1667,11 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ServiceContext.ContentService.Unpublish(content1); var content3 = CreateContent(); @@ -1694,11 +1694,11 @@ namespace Umbraco.Tests.Integration { var content1 = CreateContent(); Assert.IsNotNull(content1); - content1.PublishValues(); + content1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content1); var content2 = CreateContent(content1.Id); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); content2.Properties.First().SetValue("changed"); ServiceContext.ContentService.Save(content2); @@ -1778,7 +1778,7 @@ namespace Umbraco.Tests.Integration var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ResetEvents(); @@ -1832,11 +1832,11 @@ namespace Umbraco.Tests.Integration var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ServiceContext.ContentService.Unpublish(content2); @@ -1891,7 +1891,7 @@ namespace Umbraco.Tests.Integration var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); ServiceContext.ContentService.Move(content1, content2.Id); @@ -2001,11 +2001,11 @@ namespace Umbraco.Tests.Integration var content2 = CreateContent(); Assert.IsNotNull(content2); - content2.PublishValues(); + content2.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content2); var content3 = CreateContent(content2.Id); Assert.IsNotNull(content3); - content3.PublishValues(); + content3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content3); ServiceContext.ContentService.Unpublish(content2); @@ -2081,7 +2081,7 @@ namespace Umbraco.Tests.Integration { var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -2101,7 +2101,7 @@ namespace Umbraco.Tests.Integration { var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); var content2 = CreateContent(); Assert.IsNotNull(content2); @@ -2124,7 +2124,7 @@ namespace Umbraco.Tests.Integration { var content = CreateBranch(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); ResetEvents(); @@ -2166,17 +2166,17 @@ namespace Umbraco.Tests.Integration { var content = CreateContent(); Assert.IsNotNull(content); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); var v1 = content.VersionId; content.Properties.First().SetValue("changed"); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); var v2 = content.VersionId; content.Properties.First().SetValue("again"); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); var v3 = content.VersionId; @@ -2210,12 +2210,12 @@ namespace Umbraco.Tests.Integration Assert.IsFalse(content.IsPropertyDirty("Published")); Assert.IsFalse(content.WasPropertyDirty("Published")); - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.IsFalse(content.IsPropertyDirty("Published")); Assert.IsTrue(content.WasPropertyDirty("Published")); // has just been published - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); Assert.IsFalse(content.IsPropertyDirty("Published")); Assert.IsFalse(content.WasPropertyDirty("Published")); // was published already diff --git a/src/Umbraco.Tests/Models/VariationTests.cs b/src/Umbraco.Tests/Models/VariationTests.cs index 5bfd3f2de5..0bb1da5cc1 100644 --- a/src/Umbraco.Tests/Models/VariationTests.cs +++ b/src/Umbraco.Tests/Models/VariationTests.cs @@ -215,7 +215,7 @@ namespace Umbraco.Tests.Models // can publish value // and get edited and published values - content.PublishValues(); + content.TryPublishValues(); Assert.AreEqual("a", content.GetValue("prop")); Assert.AreEqual("a", content.GetValue("prop", published: true)); @@ -244,9 +244,9 @@ namespace Umbraco.Tests.Models // can publish value // and get edited and published values - Assert.Throws(() => content.PublishValues(langFr)); // no name + Assert.Throws(() => content.TryPublishValues(langFr)); // no name content.SetName(langFr, "name-fr"); - content.PublishValues(langFr); + content.TryPublishValues(langFr); Assert.AreEqual("b", content.GetValue("prop")); Assert.IsNull(content.GetValue("prop", published: true)); Assert.AreEqual("c", content.GetValue("prop", langFr)); @@ -260,7 +260,7 @@ namespace Umbraco.Tests.Models Assert.IsNull(content.GetValue("prop", langFr, published: true)); // can publish all - content.PublishAllValues(); + content.TryPublishAllValues(); Assert.AreEqual("b", content.GetValue("prop")); Assert.AreEqual("b", content.GetValue("prop", published: true)); Assert.AreEqual("c", content.GetValue("prop", langFr)); @@ -322,12 +322,12 @@ namespace Umbraco.Tests.Models content.SetValue("prop", "a-es", langEs); // cannot publish without a name - Assert.Throws(() => content.PublishValues(langFr)); + Assert.Throws(() => content.TryPublishValues(langFr)); // works with a name // and then FR is available, and published content.SetName(langFr, "name-fr"); - content.PublishValues(langFr); + content.TryPublishValues(langFr); // now UK is available too content.SetName(langUk, "name-uk"); diff --git a/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs b/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs index 3bc419ea95..0afc581f83 100644 --- a/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs +++ b/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs @@ -187,13 +187,13 @@ namespace Umbraco.Tests.Persistence.NPocoTests contentTypeService.Save(contentType); var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); id2 = content1.Id; var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); id3 = content2.Id; diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs index f01c59df03..caa2453aed 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs @@ -140,7 +140,7 @@ namespace Umbraco.Tests.Persistence.Repositories // publish = new edit version content1.SetValue("title", "title"); - ((Content) content1).PublishValues(); + ((Content) content1).TryPublishValues(); ((Content) content1).PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -202,7 +202,7 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.AreEqual(false, scope.Database.ExecuteScalar($"SELECT published FROM {Constants.DatabaseSchema.Tables.Document} WHERE nodeId=@id", new { id = content1.Id })); // publish = version - ((Content) content1).PublishValues(); + ((Content) content1).TryPublishValues(); ((Content) content1).PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -238,7 +238,7 @@ namespace Umbraco.Tests.Persistence.Repositories // publish = new version content1.Name = "name-4"; content1.SetValue("title", "title-4"); - ((Content) content1).PublishValues(); + ((Content) content1).TryPublishValues(); ((Content) content1).PublishedState = PublishedState.Publishing; repository.Save(content1); @@ -648,7 +648,7 @@ namespace Umbraco.Tests.Persistence.Repositories // publish them all foreach (var content in result) { - content.PublishValues(); + content.TryPublishValues(); repository.Save(content); } diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index bb3b41d128..06c13b2733 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -146,7 +146,7 @@ namespace Umbraco.Tests.Scoping using (var scope = ScopeProvider.CreateScope()) { - item.PublishValues(); + item.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(item); scope.Complete(); } @@ -161,7 +161,7 @@ namespace Umbraco.Tests.Scoping using (var scope = ScopeProvider.CreateScope()) { item.Name = "changed"; - item.PublishValues(); + item.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(item); if (complete) diff --git a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs index 258056f198..899d2f999e 100644 --- a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs @@ -123,10 +123,10 @@ namespace Umbraco.Tests.Scoping using (var scope = ScopeProvider.CreateScope()) { - item.PublishValues(); + item.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(item); // should create an xml clone item.Name = "changed"; - item.PublishValues(); + item.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(item); // should re-use the xml clone // this should never change @@ -230,13 +230,13 @@ namespace Umbraco.Tests.Scoping using (var scope = ScopeProvider.CreateScope()) { - item.PublishValues(); + item.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(item); for (var i = 0; i < count; i++) { var temp = new Content("content_" + i, -1, contentType); - temp.PublishValues(); + temp.TryPublishValues(); Current.Services.ContentService.SaveAndPublish(temp); ids[i] = temp.Id; } diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index c45d9be5f3..8bb5f1bc9e 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -182,16 +182,16 @@ namespace Umbraco.Tests.Services { var contentService = ServiceContext.ContentService; var root = ServiceContext.ContentService.GetById(NodeDto.NodeIdSeed + 1); - root.PublishValues(); + root.TryPublishValues(); Assert.IsTrue(contentService.SaveAndPublish(root).Success); var content = contentService.CreateAndSave("Test", -1, "umbTextpage", 0); - content.PublishValues(); + content.TryPublishValues(); Assert.IsTrue(contentService.SaveAndPublish(content).Success); var hierarchy = CreateContentHierarchy().OrderBy(x => x.Level).ToArray(); contentService.Save(hierarchy, 0); foreach (var c in hierarchy) { - c.PublishValues(); + c.TryPublishValues(); Assert.IsTrue(contentService.SaveAndPublish(c).Success); } @@ -241,7 +241,7 @@ namespace Umbraco.Tests.Services // Assert - content.PublishValues(); + content.TryPublishValues(); Assert.IsTrue(contentService.SaveAndPublish(content).Success); } @@ -256,7 +256,7 @@ namespace Umbraco.Tests.Services for (var i = 0; i < 20; i++) { content.SetValue("bodyText", "hello world " + Guid.NewGuid()); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); } @@ -395,12 +395,12 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags", "plus" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); // verify @@ -436,7 +436,7 @@ namespace Umbraco.Tests.Services allTags = tagService.GetAllContentTags(); Assert.AreEqual(4, allTags.Count()); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); Assert.IsTrue(content1.Published); @@ -466,12 +466,12 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags", "bam" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); // verify @@ -507,9 +507,9 @@ namespace Umbraco.Tests.Services allTags = tagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); // tags are back @@ -538,12 +538,12 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags", "plus" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", content1.Id); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); // verify @@ -578,7 +578,7 @@ namespace Umbraco.Tests.Services allTags = tagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); Assert.IsTrue(content1.Published); @@ -616,12 +616,12 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags", "bam" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); contentService.Unpublish(content1); @@ -637,7 +637,7 @@ namespace Umbraco.Tests.Services var allTags = tagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); tags = tagService.GetTagsForEntity(content2.Id); @@ -663,12 +663,12 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "hello", "world", "some", "tags", "bam" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", content1); content2.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); contentService.Unpublish(content1); @@ -684,7 +684,7 @@ namespace Umbraco.Tests.Services var allTags = tagService.GetAllContentTags(); Assert.AreEqual(0, allTags.Count()); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); tags = tagService.GetTagsForEntity(content2.Id); @@ -768,7 +768,7 @@ namespace Umbraco.Tests.Services // create a content with tags and publish var content = MockedContent.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // edit tags and save @@ -808,7 +808,7 @@ namespace Umbraco.Tests.Services // Act content.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Assert @@ -839,12 +839,12 @@ namespace Umbraco.Tests.Services contentTypeService.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Act content.AssignTags("tags", new[] { "another", "world" }, merge: true); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Assert @@ -875,12 +875,12 @@ namespace Umbraco.Tests.Services contentTypeService.Save(contentType); var content = MockedContent.CreateSimpleContent(contentType, "Tagged content", -1); content.AssignTags("tags", new[] { "hello", "world", "some", "tags" }); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Act content.RemoveTags("tags", new[] { "some", "world" }); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Assert @@ -1063,7 +1063,7 @@ namespace Umbraco.Tests.Services var parent = ServiceContext.ContentService.GetById(NodeDto.NodeIdSeed + 2); Assert.IsFalse(parent.Published); - parent.PublishValues(); + parent.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. var content = contentService.GetById(NodeDto.NodeIdSeed + 4); @@ -1076,7 +1076,7 @@ namespace Umbraco.Tests.Services content.Name = "Text Page 2 Updated"; content.SetValue("author", "Jane Doe"); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // publishes the current version, creates a version var version2 = content.VersionId; @@ -1084,7 +1084,7 @@ namespace Umbraco.Tests.Services content.Name = "Text Page 2 ReUpdated"; content.SetValue("author", "Bob Hope"); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // publishes again, creates a version var version3 = content.VersionId; @@ -1151,11 +1151,11 @@ namespace Umbraco.Tests.Services // Arrange var contentService = ServiceContext.ContentService; var root = contentService.GetById(NodeDto.NodeIdSeed + 2); - root.PublishValues(); + root.TryPublishValues(); contentService.SaveAndPublish(root); var content = contentService.GetById(NodeDto.NodeIdSeed + 4); content.ExpireDate = DateTime.Now.AddSeconds(1); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // Act @@ -1205,7 +1205,7 @@ namespace Umbraco.Tests.Services // Arrange var contentService = ServiceContext.ContentService; var content = contentService.GetById(NodeDto.NodeIdSeed + 2); - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); using (var scope = ScopeProvider.CreateScope()) @@ -1235,7 +1235,7 @@ namespace Umbraco.Tests.Services var content = contentService.GetById(NodeDto.NodeIdSeed + 2); // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); // Assert @@ -1249,7 +1249,7 @@ namespace Umbraco.Tests.Services // Arrange var contentService = ServiceContext.ContentService; var parent = contentService.Create("parent", -1, "umbTextpage"); - parent.PublishValues(); + parent.TryPublishValues(); contentService.SaveAndPublish(parent); var content = contentService.Create("child", parent, "umbTextpage"); contentService.Save(content); @@ -1275,7 +1275,7 @@ namespace Umbraco.Tests.Services Assert.AreEqual("Home", content.Name); content.Name = "foo"; - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); Assert.That(published.Success, Is.True); @@ -1316,7 +1316,7 @@ namespace Umbraco.Tests.Services var parent = contentService.GetById(parentId); - var parentCanPublishValues = parent.PublishValues(); + var parentCanPublishValues = parent.TryPublishValues(); var parentPublished = contentService.SaveAndPublish(parent); // parent can publish values @@ -1325,7 +1325,7 @@ namespace Umbraco.Tests.Services Assert.IsTrue(parentPublished.Success); Assert.IsTrue(parent.Published); - var contentCanPublishValues = content.PublishValues(); + var contentCanPublishValues = content.TryPublishValues(); var contentPublished = contentService.SaveAndPublish(content); // content cannot publish values because they are invalid @@ -1401,11 +1401,11 @@ namespace Umbraco.Tests.Services contentService.Save(content); var parent = contentService.GetById(NodeDto.NodeIdSeed + 2); - parent.PublishValues(); + parent.TryPublishValues(); var parentPublished = contentService.SaveAndPublish(parent, 0);//Publish root Home node to enable publishing of 'NodeDto.NodeIdSeed + 3' // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); // Assert @@ -1424,11 +1424,11 @@ namespace Umbraco.Tests.Services contentService.Save(content, 0); var parent = contentService.GetById(NodeDto.NodeIdSeed + 2); - parent.PublishValues(); + parent.TryPublishValues(); var parentPublished = contentService.SaveAndPublish(parent, 0);//Publish root Home node to enable publishing of 'NodeDto.NodeIdSeed + 3' // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); // Assert @@ -1461,7 +1461,7 @@ namespace Umbraco.Tests.Services var content = contentService.GetById(NodeDto.NodeIdSeed + 5); // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); // Assert @@ -1479,7 +1479,7 @@ namespace Umbraco.Tests.Services content.SetValue("author", "Barack Obama"); // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); // Assert @@ -1504,14 +1504,14 @@ namespace Umbraco.Tests.Services content.SetValue("author", "Barack Obama"); // Act - content.PublishValues(); + content.TryPublishValues(); var published = contentService.SaveAndPublish(content, 0); var childContent = contentService.Create("Child", content.Id, "umbTextpage", 0); // Reset all identity properties childContent.Id = 0; childContent.Path = null; ((Content)childContent).ResetIdentity(); - childContent.PublishValues(); + childContent.TryPublishValues(); var childPublished = contentService.SaveAndPublish(childContent, 0); // Assert @@ -1530,12 +1530,12 @@ namespace Umbraco.Tests.Services var contentService = ServiceContext.ContentService; var root = contentService.GetById(NodeDto.NodeIdSeed + 2); - root.PublishValues(); + root.TryPublishValues(); var rootPublished = contentService.SaveAndPublish(root); var content = contentService.GetById(NodeDto.NodeIdSeed + 4); content.Properties["title"].SetValue(content.Properties["title"].GetValue() + " Published"); - content.PublishValues(); + content.TryPublishValues(); var contentPublished = contentService.SaveAndPublish(content); var publishedVersion = content.VersionId; @@ -1835,13 +1835,13 @@ namespace Umbraco.Tests.Services content1.PropertyValues(obj); content1.ResetDirtyProperties(false); ServiceContext.ContentService.Save(content1, 0); - content1.PublishValues(); + content1.TryPublishValues(); Assert.IsTrue(ServiceContext.ContentService.SaveAndPublish(content1, 0).Success); var content2 = MockedContent.CreateBasicContent(contentType); content2.PropertyValues(obj); content2.ResetDirtyProperties(false); ServiceContext.ContentService.Save(content2, 0); - content2.PublishValues(); + content2.TryPublishValues(); Assert.IsTrue(ServiceContext.ContentService.SaveAndPublish(content2, 0).Success); var editorGroup = ServiceContext.UserService.GetUserGroupByAlias("editor"); @@ -1999,7 +1999,7 @@ namespace Umbraco.Tests.Services Assert.AreEqual(0, contentTags.Length); // publish - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // now tags have been set (published) @@ -2016,7 +2016,7 @@ namespace Umbraco.Tests.Services Assert.AreEqual(0, copiedTags.Length); // publish - copy.PublishValues(); + copy.TryPublishValues(); contentService.SaveAndPublish(copy); // now tags have been set (published) @@ -2035,7 +2035,7 @@ namespace Umbraco.Tests.Services var parent = ServiceContext.ContentService.GetById(NodeDto.NodeIdSeed + 2); Assert.IsFalse(parent.Published); - parent.PublishValues(); + parent.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(parent); // publishing parent, so Text Page 2 can be updated. var content = contentService.GetById(NodeDto.NodeIdSeed + 4); @@ -2052,7 +2052,7 @@ namespace Umbraco.Tests.Services // non published = edited Assert.IsTrue(content.Edited); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // new version var version2 = content.VersionId; Assert.AreNotEqual(version1, version2); @@ -2077,7 +2077,7 @@ namespace Umbraco.Tests.Services content.Name = "Text Page 2 ReReUpdated"; - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // new version var version3 = content.VersionId; Assert.AreNotEqual(version2, version3); @@ -2133,7 +2133,7 @@ namespace Umbraco.Tests.Services content = contentService.GetById(content.Id); Assert.AreEqual("Text Page 2 ReReUpdated", content.Name); Assert.AreEqual("Jane Doe", content.GetValue("author")); - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); Assert.IsFalse(content.Edited); content.Name = "Xxx"; @@ -2251,7 +2251,7 @@ namespace Umbraco.Tests.Services Assert.IsFalse(scope.Database.Exists(content.Id)); } - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); using (var scope = ScopeProvider.CreateScope()) @@ -2393,7 +2393,7 @@ namespace Umbraco.Tests.Services // becomes Published, !Edited // creates a new version // can get published property values - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); Assert.IsTrue(content.Published); @@ -2548,8 +2548,8 @@ namespace Umbraco.Tests.Services // act - content.PublishValues(langFr.IsoCode); - content.PublishValues(langUk.IsoCode); + content.TryPublishValues(langFr.IsoCode); + content.TryPublishValues(langUk.IsoCode); contentService.SaveAndPublish(content); // both FR and UK have been published, @@ -2591,7 +2591,7 @@ namespace Umbraco.Tests.Services // act - content.PublishValues(); + content.TryPublishValues(); contentService.SaveAndPublish(content); // now it has publish name for invariant neutral @@ -2780,7 +2780,7 @@ namespace Umbraco.Tests.Services // act - content.PublishValues(langUk.IsoCode); + content.TryPublishValues(langUk.IsoCode); contentService.SaveAndPublish(content); content2 = contentService.GetById(content.Id); diff --git a/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs b/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs index 1944516164..c9f8ba52ad 100644 --- a/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs @@ -88,7 +88,7 @@ namespace Umbraco.Tests.Services var contentType = contentTypes[index]; var contentItem = MockedContent.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ServiceContext.ContentService.Save(contentItem); - contentItem.PublishValues(); + contentItem.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; @@ -189,7 +189,7 @@ namespace Umbraco.Tests.Services var contentType = contentTypes[index]; var contentItem = MockedContent.CreateSimpleContent(contentType, "MyName_" + index + "_" + i, parentId); ServiceContext.ContentService.Save(contentItem); - contentItem.PublishValues(); + contentItem.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(contentItem); parentId = contentItem.Id; } @@ -225,19 +225,19 @@ namespace Umbraco.Tests.Services var root = MockedContent.CreateSimpleContent(contentType1, "Root", -1); ServiceContext.ContentService.Save(root); - root.PublishValues(); + root.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(root); var level1 = MockedContent.CreateSimpleContent(contentType2, "L1", root.Id); ServiceContext.ContentService.Save(level1); - level1.PublishValues(); + level1.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(level1); for (int i = 0; i < 2; i++) { var level3 = MockedContent.CreateSimpleContent(contentType3, "L2" + i, level1.Id); ServiceContext.ContentService.Save(level3); - level3.PublishValues(); + level3.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(level3); } @@ -267,7 +267,7 @@ namespace Umbraco.Tests.Services ServiceContext.FileService.SaveTemplate(contentType1.DefaultTemplate); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); - contentItem.PublishValues(); + contentItem.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); @@ -297,14 +297,14 @@ namespace Umbraco.Tests.Services var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); foreach (var x in contentItems1) { - x.PublishValues(); + x.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(x); } var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); foreach (var x in contentItems2) { - x.PublishValues(); + x.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(x); } @@ -362,7 +362,7 @@ namespace Umbraco.Tests.Services var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); foreach (var x in contentItems1) { - x.PublishValues(); + x.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(x); } var alias = contentType1.PropertyTypes.First().Alias; @@ -496,7 +496,7 @@ namespace Umbraco.Tests.Services // Act var homeDoc = cs.Create("Home Page", -1, contentTypeAlias); - homeDoc.PublishValues(); + homeDoc.TryPublishValues(); cs.SaveAndPublish(homeDoc); // Assert diff --git a/src/Umbraco.Tests/Services/PerformanceTests.cs b/src/Umbraco.Tests/Services/PerformanceTests.cs index b157eb669d..dd84c49ef0 100644 --- a/src/Umbraco.Tests/Services/PerformanceTests.cs +++ b/src/Umbraco.Tests/Services/PerformanceTests.cs @@ -249,7 +249,7 @@ namespace Umbraco.Tests.Services var result = new List(); ServiceContext.ContentTypeService.Save(contentType1); IContent lastParent = MockedContent.CreateSimpleContent(contentType1); - lastParent.PublishValues(); + lastParent.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(lastParent); result.Add(lastParent); //create 20 deep @@ -263,7 +263,7 @@ namespace Umbraco.Tests.Services //only publish evens if (j % 2 == 0) { - content.PublishValues(); + content.TryPublishValues(); ServiceContext.ContentService.SaveAndPublish(content); } else diff --git a/src/Umbraco.Tests/Services/TagServiceTests.cs b/src/Umbraco.Tests/Services/TagServiceTests.cs index 0db27e9f4c..c24c729bf8 100644 --- a/src/Umbraco.Tests/Services/TagServiceTests.cs +++ b/src/Umbraco.Tests/Services/TagServiceTests.cs @@ -36,21 +36,21 @@ namespace Umbraco.Tests.Services IContent content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "cow", "pig", "goat" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); // change content1.AssignTags("tags", new[] { "elephant" }, true); content1.RemoveTags("tags", new[] { "cow" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); // more changes content1.AssignTags("tags", new[] { "mouse" }, true); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); content1.RemoveTags("tags", new[] { "mouse" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); // get it back @@ -88,17 +88,17 @@ namespace Umbraco.Tests.Services var content1 = MockedContent.CreateSimpleContent(contentType, "Tagged content 1", -1); content1.AssignTags("tags", new[] { "cow", "pig", "goat" }); - content1.PublishValues(); + content1.TryPublishValues(); contentService.SaveAndPublish(content1); var content2 = MockedContent.CreateSimpleContent(contentType, "Tagged content 2", -1); content2.AssignTags("tags", new[] { "cow", "pig" }); - content2.PublishValues(); + content2.TryPublishValues(); contentService.SaveAndPublish(content2); var content3 = MockedContent.CreateSimpleContent(contentType, "Tagged content 3", -1); content3.AssignTags("tags", new[] { "cow" }); - content3.PublishValues(); + content3.TryPublishValues(); contentService.SaveAndPublish(content3); // Act diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index 6ce5f049e8..3612ee8847 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -643,22 +643,22 @@ namespace Umbraco.Web.Editors else { //publish the item and check if it worked, if not we will show a diff msg below - contentItem.PersistedContent.PublishValues(GetLanguageCulture(contentItem.LanguageId)); //we are not checking for a return value here because we've alraedy pre-validated the property values + contentItem.PersistedContent.TryPublishValues(GetLanguageCulture(contentItem.LanguageId)); //we are not checking for a return value here because we've already pre-validated the property values //check if we are publishing other variants and validate them - var allLangs = Services.LocalizationService.GetAllLanguages().ToList(); + var allLangs = Services.LocalizationService.GetAllLanguages().ToDictionary(x => x.Id, x => x); var variantsToValidate = contentItem.PublishVariations.Where(x => x.LanguageId != contentItem.LanguageId).ToList(); foreach (var publishVariation in variantsToValidate) { - if (!contentItem.PersistedContent.PublishValues(GetLanguageCulture(publishVariation.LanguageId))) + if (!contentItem.PersistedContent.TryPublishValues(GetLanguageCulture(publishVariation.LanguageId))) { - var errMsg = Services.TextService.Localize("speechBubbles/contentLangValidationError", new[]{allLangs.First(x => x.Id == publishVariation.LanguageId).CultureName}); + var errMsg = Services.TextService.Localize("speechBubbles/contentLangValidationError", new[] {allLangs[publishVariation.LanguageId].CultureName}); ModelState.AddModelError("publish_variant_" + publishVariation.LanguageId + "_", errMsg); } } //validate any mandatory variants that are not in the list - var mandatoryLangs = Mapper.Map, IEnumerable>(allLangs) + var mandatoryLangs = Mapper.Map, IEnumerable>(allLangs.Values) .Where(x => variantsToValidate.All(v => v.LanguageId != x.Id)) //don't include variants above .Where(x => x.Id != contentItem.LanguageId) //don't include the current variant .Where(x => x.Mandatory); @@ -666,7 +666,7 @@ namespace Umbraco.Web.Editors { if (contentItem.PersistedContent.Validate(GetLanguageCulture(lang.Id)).Length > 0) { - var errMsg = Services.TextService.Localize("speechBubbles/contentReqLangValidationError", new[]{allLangs.First(x => x.Id == lang.Id).CultureName}); + var errMsg = Services.TextService.Localize("speechBubbles/contentReqLangValidationError", new[]{allLangs[lang.Id].CultureName}); ModelState.AddModelError("publish_variant_" + lang.Id + "_", errMsg); } } @@ -749,7 +749,7 @@ namespace Umbraco.Web.Editors return HandleContentNotFound(id, false); } - foundContent.PublishValues(); // fixme variants? + foundContent.TryPublishValues(); // fixme variants? var publishResult = Services.ContentService.SaveAndPublish(foundContent, Security.GetUserId().ResultOr(0)); if (publishResult.Success == false) { diff --git a/src/Umbraco.Web/Models/Mapping/ContentItemDisplayNameResolver.cs b/src/Umbraco.Web/Models/Mapping/ContentItemDisplayNameResolver.cs index 41383764bb..2e8155e1a7 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentItemDisplayNameResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentItemDisplayNameResolver.cs @@ -1,4 +1,5 @@ using AutoMapper; +using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; using ContentVariation = Umbraco.Core.Models.ContentVariation; @@ -13,7 +14,12 @@ namespace Umbraco.Web.Models.Mapping public string Resolve(IContent source, ContentItemDisplay destination, string destMember, ResolutionContext context) { var culture = context.GetCulture(); - return source.GetName(culture); + if (culture != null && source.ContentType.Variations.Has(ContentVariation.CultureNeutral)) + { + //return the culture name being requested + return source.GetName(culture); + } + return source.Name; } } } diff --git a/src/Umbraco.Web/WebServices/BulkPublishController.cs b/src/Umbraco.Web/WebServices/BulkPublishController.cs index daea5cc58f..714c1ac0db 100644 --- a/src/Umbraco.Web/WebServices/BulkPublishController.cs +++ b/src/Umbraco.Web/WebServices/BulkPublishController.cs @@ -29,7 +29,7 @@ namespace Umbraco.Web.WebServices if (publishDescendants == false) { - content.PublishValues(); // fixme variants? validation - when this returns null? + content.TryPublishValues(); // fixme variants? validation - when this returns null? var result = Services.ContentService.SaveAndPublish(content, Security.CurrentUser.Id); return Json(new { From ffd85b4e94ee8b0f6ee8611d06a91280a73af528 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 26 Apr 2018 22:54:36 +1000 Subject: [PATCH 27/58] Fixes more bugs and outbound routing for additional urls --- .../Integration/GetCultureTests.cs | 120 ------------------ .../Routing/DomainsAndCulturesTests.cs | 44 +------ src/Umbraco.Tests/Umbraco.Tests.csproj | 1 - src/Umbraco.Web/Models/ContentExtensions.cs | 107 ---------------- .../NuCache/PublishedContent.cs | 2 +- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 91 ++++++++++--- src/Umbraco.Web/Routing/DomainHelper.cs | 3 +- src/Umbraco.Web/Umbraco.Web.csproj | 1 - src/Umbraco.Web/umbraco.presentation/page.cs | 2 +- 9 files changed, 75 insertions(+), 296 deletions(-) delete mode 100644 src/Umbraco.Tests/Integration/GetCultureTests.cs delete mode 100644 src/Umbraco.Web/Models/ContentExtensions.cs diff --git a/src/Umbraco.Tests/Integration/GetCultureTests.cs b/src/Umbraco.Tests/Integration/GetCultureTests.cs deleted file mode 100644 index ec3a73b37e..0000000000 --- a/src/Umbraco.Tests/Integration/GetCultureTests.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Linq; -using System.Threading; -using NUnit.Framework; -using Umbraco.Core.Models; -using Umbraco.Tests.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.TestHelpers.Entities; -using Umbraco.Tests.Testing; -using Umbraco.Web.Routing; - -namespace Umbraco.Tests.Integration -{ - [TestFixture] - [Apartment(ApartmentState.STA)] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class GetCultureTests : TestWithSomeContentBase - { - protected override void Compose() - { - base.Compose(); - Container.Register(); - } - - [Test] - public void GetCulture() - { - var contentTypeService = ServiceContext.ContentTypeService; - var contentType = MockedContentTypes.CreateSimpleContentType("umbBlah", "test Doc Type"); - contentTypeService.Save(contentType); - var contentService = ServiceContext.ContentService; - - var c1 = contentService.CreateAndSave("content", -1, "umbBlah"); - var c2 = contentService.CreateAndSave("content", c1, "umbBlah"); - var c3 = contentService.CreateAndSave("content", c1, "umbBlah"); - var c4 = contentService.CreateAndSave("content", c3, "umbBlah"); - - foreach (var l in ServiceContext.LocalizationService.GetAllLanguages().Where(x => x.CultureName != "en-US").ToArray()) - ServiceContext.LocalizationService.Delete(l); - - var l0 = ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"); - var l1 = new Core.Models.Language("fr-FR"); - var l2 = new Core.Models.Language("de-DE"); - ServiceContext.LocalizationService.Save(l1); - ServiceContext.LocalizationService.Save(l2); - - foreach (var d in ServiceContext.DomainService.GetAll(true).ToArray()) - ServiceContext.DomainService.Delete(d); - - ServiceContext.DomainService.Save(new UmbracoDomain("domain1.com") {DomainName="domain1.com", RootContentId = c1.Id, LanguageId = l0.Id}); - ServiceContext.DomainService.Save(new UmbracoDomain("domain1.fr") { DomainName = "domain1.fr", RootContentId = c1.Id, LanguageId = l1.Id }); - ServiceContext.DomainService.Save(new UmbracoDomain("*100112") { DomainName = "*100112", RootContentId = c3.Id, LanguageId = l2.Id }); - - var content = c2; - var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, - ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, - new SiteDomainHelper(), - content.Id, content.Path, new Uri("http://domain1.com/")); - Assert.AreEqual("en-US", culture.Name); - - content = c2; - culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, - ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, - new SiteDomainHelper(), - content.Id, content.Path, new Uri("http://domain1.fr/")); - Assert.AreEqual("fr-FR", culture.Name); - - content = c4; - culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(null, - ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, - new SiteDomainHelper(), - content.Id, content.Path, new Uri("http://domain1.fr/")); - Assert.AreEqual("de-DE", culture.Name); - } - - [Test] - public void GetCultureWithWildcard() - { - var contentTypeService = ServiceContext.ContentTypeService; - var contentType = MockedContentTypes.CreateSimpleContentType("umbBlah", "test Doc Type"); - contentTypeService.Save(contentType); - var contentService = ServiceContext.ContentService; - - var c1 = contentService.CreateAndSave("content", -1, "umbBlah"); - var c2 = contentService.CreateAndSave("content", c1, "umbBlah"); - var c3 = contentService.CreateAndSave("content", c1, "umbBlah"); - var c4 = contentService.CreateAndSave("content", c3, "umbBlah"); - - foreach (var l in ServiceContext.LocalizationService.GetAllLanguages().Where(x => x.CultureName != "en-US").ToArray()) - ServiceContext.LocalizationService.Delete(l); - - var l0 = ServiceContext.LocalizationService.GetLanguageByIsoCode("en-US"); - var l1 = new Core.Models.Language("fr-FR"); - var l2 = new Core.Models.Language("de-DE"); - ServiceContext.LocalizationService.Save(l1); - ServiceContext.LocalizationService.Save(l2); - - foreach (var d in ServiceContext.DomainService.GetAll(true).ToArray()) - ServiceContext.DomainService.Delete(d); - - ServiceContext.DomainService.Save(new UmbracoDomain("*0000") { DomainName = "*0000", RootContentId = c1.Id, LanguageId = l2.Id }); - ServiceContext.DomainService.Save(new UmbracoDomain("*0001") { DomainName = "*0001", RootContentId = c3.Id, LanguageId = l1.Id }); - //ServiceContext.DomainService.Save(new UmbracoDomain("*100112") { DomainName = "*100112", RootContentId = c3.Id, LanguageId = l2.Id }); - - var content = c2; - var culture = Umbraco.Web.Models.ContentExtensions.GetCulture(null, - ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, - new SiteDomainHelper(), - content.Id, content.Path, new Uri("http://domain1.com/")); - Assert.AreEqual("de-DE", culture.Name); - - content = c4; - culture = Umbraco.Web.Models.ContentExtensions.GetCulture(null, - ServiceContext.DomainService, ServiceContext.LocalizationService, ServiceContext.ContentService, - new SiteDomainHelper(), - content.Id, content.Path, new Uri("http://domain1.fr/")); - Assert.AreEqual("fr-FR", culture.Name); - } - } -} diff --git a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs index 1740f1288c..e4fcfc46f8 100644 --- a/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs +++ b/src/Umbraco.Tests/Routing/DomainsAndCulturesTests.cs @@ -338,48 +338,6 @@ namespace Umbraco.Tests.Routing } - - #region Cases - [TestCase(10011, "http://domain1.com/", "en-US")] - [TestCase(100111, "http://domain1.com/", "en-US")] - [TestCase(10011, "http://domain1.fr/", "fr-FR")] - [TestCase(100111, "http://domain1.fr/", "fr-FR")] - [TestCase(1001121, "http://domain1.fr/", "de-DE")] - #endregion - public void GetCulture(int nodeId, string currentUrl, string expectedCulture) - { - var domainService = SetupDomainServiceMock(new[] - { - new UmbracoDomain("domain1.com/") - { - Id = 1, - LanguageId = LangEngId, - RootContentId = 1001, - LanguageIsoCode = "en-US" - }, - new UmbracoDomain("domain1.fr/") - { - Id = 1, - LanguageId = LangFrId, - RootContentId = 1001, - LanguageIsoCode = "fr-FR" - }, - new UmbracoDomain("*100112") - { - Id = 1, - LanguageId = LangDeId, - RootContentId = 100112, - LanguageIsoCode = "de-DE" - } - }); - - var umbracoContext = GetUmbracoContext("http://anything/"); - - var content = umbracoContext.ContentCache.GetById(nodeId); - Assert.IsNotNull(content); - - var culture = global::Umbraco.Web.Models.ContentExtensions.GetCulture(umbracoContext, domainService, ServiceContext.LocalizationService, null, new SiteDomainHelper(), content.Id, content.Path, new Uri(currentUrl)); - Assert.AreEqual(expectedCulture, culture.Name); - } + } } diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 3da04b48ca..8ae1e4dede 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -232,7 +232,6 @@ - diff --git a/src/Umbraco.Web/Models/ContentExtensions.cs b/src/Umbraco.Web/Models/ContentExtensions.cs deleted file mode 100644 index d6700769a9..0000000000 --- a/src/Umbraco.Web/Models/ContentExtensions.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using Umbraco.Web.Composing; -using Umbraco.Web.Routing; -using Domain = Umbraco.Web.Routing.Domain; - -namespace Umbraco.Web.Models -{ - public static class ContentExtensions - { - //TODO: Not used - ///// - ///// Gets the culture that would be selected to render a specified content, - ///// within the context of a specified current request. - ///// - ///// The content. - ///// The request Uri. - ///// The culture that would be selected to render the content. - //public static CultureInfo GetCulture(this IContent content, Uri current = null) - //{ - // return GetCulture(UmbracoContext.Current, - // Current.Services.DomainService, - // Current.Services.LocalizationService, - // Current.Services.ContentService, - // content.Id, content.Path, - // current); - //} - - - - //TODO: Not used - only in tests - /// - /// Gets the culture that would be selected to render a specified content, - /// within the context of a specified current request. - /// - /// An instance. - /// An implementation. - /// An implementation. - /// An implementation. - /// The content identifier. - /// The content path. - /// The request Uri. - /// The culture that would be selected to render the content. - internal static CultureInfo GetCulture(UmbracoContext umbracoContext, - IDomainService domainService, ILocalizationService localizationService, IContentService contentService, - ISiteDomainHelper siteDomainHelper, - int contentId, string contentPath, Uri current) - { - var route = umbracoContext == null - ? null // for tests only - : umbracoContext.ContentCache.GetRouteById(contentId); // may be cached - - var domainCache = umbracoContext == null - ? new PublishedCache.XmlPublishedCache.DomainCache(domainService, localizationService) // for tests only - : umbracoContext.PublishedShapshot.Domains; // default - var domainHelper = umbracoContext.GetDomainHelper(siteDomainHelper); - Domain domain; - - if (route == null) - { - // if content is not published then route is null and we have to work - // on non-published content (note: could optimize by checking routes?) - - // fixme - even non-published content is stored in the cache or in the cmsContentNu table which would be faster to lookup - - var content = contentService.GetById(contentId); - if (content == null) - return GetDefaultCulture(localizationService); - - var hasDomain = domainHelper.NodeHasDomains(content.Id); - while (hasDomain == false && content != null) - { - content = content.Parent(contentService); - hasDomain = content != null && domainHelper.NodeHasDomains(content.Id); - } - - domain = hasDomain ? domainHelper.DomainForNode(content.Id, current) : null; - } - else - { - // if content is published then we have a route - // from which we can figure out the domain - - var pos = route.IndexOf('/'); - domain = pos == 0 - ? null - : domainHelper.DomainForNode(int.Parse(route.Substring(0, pos)), current); - } - - var rootContentId = domain == null ? -1 : domain.ContentId; - var wcDomain = DomainHelper.FindWildcardDomainInPath(domainCache.GetAll(true), contentPath, rootContentId); - - if (wcDomain != null) return wcDomain.Culture; - if (domain != null) return domain.Culture; - return GetDefaultCulture(localizationService); - } - - private static CultureInfo GetDefaultCulture(ILocalizationService localizationService) - { - var defaultLanguage = localizationService.GetDefaultVariantLanguage(); - return defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); - } - } -} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 883a43a7d5..480c18201f 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -170,7 +170,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (_cultureNames == null) { - var d = new Dictionary(); + var d = new Dictionary(StringComparer.InvariantCultureIgnoreCase); foreach(var c in _contentData.CultureInfos) { d[c.Key] = new PublishedCultureName(c.Value.Name, c.Value.Name.ToUrlSegment()); diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index d2f0c2662b..21a4b5c734 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; - +using Umbraco.Core.Models; + namespace Umbraco.Web.Routing { /// @@ -90,32 +92,79 @@ namespace Umbraco.Web.Routing /// urls for the node in other contexts (different domain for current request, umbracoUrlAlias...). /// public virtual IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, Uri current) - { - // will not use cache if previewing - var route = umbracoContext.ContentCache.GetRouteById(id); - - if (string.IsNullOrWhiteSpace(route)) - { - _logger.Debug(() => - $"Couldn't find any page with nodeId={id}. This is most likely caused by the page not being published."); - return null; + { + var node = umbracoContext.ContentCache.GetById(id); + var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); + + //if this is invariant, continue as we used to + if (!node.ContentType.Variations.Has(ContentVariation.CultureNeutral)) + { + // will not use cache if previewing + var route = umbracoContext.ContentCache.GetRouteById(id); + + return GetOtherUrlsForSinglePath(route, id, domainHelper, current); + } + else + { + //this is variant, so we need to find the domains and use the cultures assigned to get the route/paths + + var n = node; + var domainUris = domainHelper.DomainsForNode(n.Id, current, false); + while (domainUris == null && n != null) // n is null at root + { + // move to parent node + n = n.Parent; + domainUris = n == null ? null : domainHelper.DomainsForNode(n.Id, current); + } + + if (domainUris == null) + { + //we can't continue, there are no domains assigned but this is a culture variant node + return Enumerable.Empty(); + } + + var result = new List(); + foreach(var d in domainUris) + { + var route = umbracoContext.ContentCache.GetRouteById(id, d.Culture); + if (route == null) continue; + + //need to strip off the leading ID for the route + //TODO: Is there a nicer way to deal with this? + var pos = route.IndexOf('/'); + var path = pos == 0 ? route : route.Substring(pos); + + var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); + uri = UriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); + result.Add(uri.ToString()); + } + return result; } - - var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); - - // extract domainUri and path - // route is / or / - var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); - var domainUris = pos == 0 ? null : domainHelper.DomainsForNode(int.Parse(route.Substring(0, pos)), current); - - // assemble the alternate urls from domainUris (maybe empty) and path - return AssembleUrls(domainUris, path).Select(uri => uri.ToString()); + } #endregion #region Utilities + + private IEnumerable GetOtherUrlsForSinglePath(string route, int id, DomainHelper domainHelper, Uri current) + { + if (string.IsNullOrWhiteSpace(route)) + { + _logger.Debug(() => + $"Couldn't find any page with nodeId={id}. This is most likely caused by the page not being published."); + return null; + } + + // extract domainUri and path + // route is / or / + var pos = route.IndexOf('/'); + var path = pos == 0 ? route : route.Substring(pos); + var domainUris = pos == 0 ? null : domainHelper.DomainsForNode(int.Parse(route.Substring(0, pos)), current); + + // assemble the alternate urls from domainUris (maybe empty) and path + return AssembleUrls(domainUris, path).Select(uri => uri.ToString()); + } Uri AssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlProviderMode mode) { diff --git a/src/Umbraco.Web/Routing/DomainHelper.cs b/src/Umbraco.Web/Routing/DomainHelper.cs index d56473f530..ba7b59323b 100644 --- a/src/Umbraco.Web/Routing/DomainHelper.cs +++ b/src/Umbraco.Web/Routing/DomainHelper.cs @@ -128,7 +128,8 @@ namespace Umbraco.Web.Routing { //get the default domain (there should be one) domainAndUri = domainsAndUris.FirstOrDefault(x => x.IsDefault); - if (domainAndUri == null) domainsAndUris.First(); // take the first one by default (what else can we do?) + if (domainAndUri == null) + domainAndUri = domainsAndUris.First(); // take the first one by default (what else can we do?) } else { diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 98afb387d4..44bc3ec324 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -567,7 +567,6 @@ - diff --git a/src/Umbraco.Web/umbraco.presentation/page.cs b/src/Umbraco.Web/umbraco.presentation/page.cs index 274ea83214..89ac52949f 100644 --- a/src/Umbraco.Web/umbraco.presentation/page.cs +++ b/src/Umbraco.Web/umbraco.presentation/page.cs @@ -481,7 +481,7 @@ namespace umbraco if (_cultureNames == null) { - var d = new Dictionary(); + var d = new Dictionary(StringComparer.InvariantCultureIgnoreCase); foreach (var c in _inner.Names) { d[c.Key] = new PublishedCultureName(c.Value, c.Value.ToUrlSegment()); From cb3cba5b053aa364a395ead8711089c8cf7474e1 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 26 Apr 2018 23:34:06 +1000 Subject: [PATCH 28/58] Updates DefaultUrlProvider so that hieararchy of nodes that are variant and invariant still generate URLs correctly --- .../services/umbdataformatter.service.js | 30 +++--- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 101 +++++------------- 2 files changed, 44 insertions(+), 87 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js index 9608fe20fb..5ef6eae293 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js @@ -326,19 +326,23 @@ //get the selected variant and build the additional published variants saveModel.publishVariations = []; - _.each(displayModel.variants, - function (d) { - //set the selected variant if this is current - if (d.current === true) { - saveModel.languageId = d.language.id; - } - if (d.publish === true) { - saveModel.publishVariations.push({ - languageId: d.language.id, - segment: d.segment - }); - } - }); + + //if there's more than 1 variant than we need to set the language and include the variants to publish + if (displayModel.variants.length > 1) { + _.each(displayModel.variants, + function (d) { + //set the selected variant if this is current + if (d.current === true) { + saveModel.languageId = d.language.id; + } + if (d.publish === true) { + saveModel.publishVariations.push({ + languageId: d.language.id, + segment: d.segment + }); + } + }); + } var propExpireDate = displayModel.removeDate; var propReleaseDate = displayModel.releaseDate; diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 21a4b5c734..c451d91565 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -7,6 +7,7 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Models; +using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Web.Routing { @@ -96,75 +97,43 @@ namespace Umbraco.Web.Routing var node = umbracoContext.ContentCache.GetById(id); var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); - //if this is invariant, continue as we used to - if (!node.ContentType.Variations.Has(ContentVariation.CultureNeutral)) + var n = node; + var domainUris = domainHelper.DomainsForNode(n.Id, current, false); + while (domainUris == null && n != null) // n is null at root { - // will not use cache if previewing - var route = umbracoContext.ContentCache.GetRouteById(id); - - return GetOtherUrlsForSinglePath(route, id, domainHelper, current); + // move to parent node + n = n.Parent; + domainUris = n == null ? null : domainHelper.DomainsForNode(n.Id, current); } - else + + if (domainUris == null) { - //this is variant, so we need to find the domains and use the cultures assigned to get the route/paths + //there are no domains, exit + return Enumerable.Empty(); + } - var n = node; - var domainUris = domainHelper.DomainsForNode(n.Id, current, false); - while (domainUris == null && n != null) // n is null at root - { - // move to parent node - n = n.Parent; - domainUris = n == null ? null : domainHelper.DomainsForNode(n.Id, current); - } + var result = new List(); + foreach (var d in domainUris) + { + //although we are passing in culture here, if any node in this path is invariant, it ignores the culture anyways so this is ok + var route = umbracoContext.ContentCache.GetRouteById(id, d.Culture); + if (route == null) continue; - if (domainUris == null) - { - //we can't continue, there are no domains assigned but this is a culture variant node - return Enumerable.Empty(); - } + //need to strip off the leading ID for the route + //TODO: Is there a nicer way to deal with this? + var pos = route.IndexOf('/'); + var path = pos == 0 ? route : route.Substring(pos); - var result = new List(); - foreach(var d in domainUris) - { - var route = umbracoContext.ContentCache.GetRouteById(id, d.Culture); - if (route == null) continue; - - //need to strip off the leading ID for the route - //TODO: Is there a nicer way to deal with this? - var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); - - var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); - uri = UriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); - result.Add(uri.ToString()); - } - return result; - } - + var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); + uri = UriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); + result.Add(uri.ToString()); + } + return result; } #endregion #region Utilities - - private IEnumerable GetOtherUrlsForSinglePath(string route, int id, DomainHelper domainHelper, Uri current) - { - if (string.IsNullOrWhiteSpace(route)) - { - _logger.Debug(() => - $"Couldn't find any page with nodeId={id}. This is most likely caused by the page not being published."); - return null; - } - - // extract domainUri and path - // route is / or / - var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); - var domainUris = pos == 0 ? null : domainHelper.DomainsForNode(int.Parse(route.Substring(0, pos)), current); - - // assemble the alternate urls from domainUris (maybe empty) and path - return AssembleUrls(domainUris, path).Select(uri => uri.ToString()); - } Uri AssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlProviderMode mode) { @@ -231,22 +200,6 @@ namespace Umbraco.Web.Routing return path == "/" ? path : path.TrimEnd('/'); } - // always build absolute urls unless we really cannot - IEnumerable AssembleUrls(IEnumerable domainUris, string path) - { - // no domain == no "other" url - if (domainUris == null) - return Enumerable.Empty(); - - // if no domain was found and then we have no "other" url - // else return absolute urls, ignoring vdir at that point - var uris = domainUris.Select(domainUri => new Uri(CombinePaths(domainUri.Uri.GetLeftPart(UriPartial.Path), path))); - - // UriFromUmbraco will handle vdir - // meaning it will add vdir into domain urls too! - return uris.Select(x => UriUtility.UriFromUmbraco(x, _globalSettings, _requestSettings)); - } - #endregion } } From 12d56cd201075fc7a66fbb713ea555d98a406d54 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 26 Apr 2018 23:48:07 +1000 Subject: [PATCH 29/58] fixes null check which fixes a whole lot of failing tests --- src/Umbraco.Core/Models/DomainExtensions.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Umbraco.Core/Models/DomainExtensions.cs b/src/Umbraco.Core/Models/DomainExtensions.cs index 47cd34105b..616685b6b9 100644 --- a/src/Umbraco.Core/Models/DomainExtensions.cs +++ b/src/Umbraco.Core/Models/DomainExtensions.cs @@ -13,6 +13,9 @@ namespace Umbraco.Core.Models public static bool IsDefaultDomain(this IDomain domain, ILocalizationService localizationService) { var defaultLang = localizationService.GetDefaultVariantLanguage(); + if (defaultLang == null) + return false; //if for some reason a null value is returned (i.e. no languages or based on mock unit test data), then assume false + return domain.LanguageIsoCode == defaultLang.CultureName; } } From 270f3a75ffe88e39781021bbf41e542a7e29f0aa Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 09:57:04 +1000 Subject: [PATCH 30/58] Fixes more tests --- src/Umbraco.Core/Models/Content.cs | 2 +- src/Umbraco.Tests/Models/VariationTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Core/Models/Content.cs b/src/Umbraco.Core/Models/Content.cs index 708f0ac853..6b8732e70c 100644 --- a/src/Umbraco.Core/Models/Content.cs +++ b/src/Umbraco.Core/Models/Content.cs @@ -271,7 +271,7 @@ namespace Umbraco.Core.Models } /// - public IEnumerable PublishedCultures => _publishInfos.Keys; + public IEnumerable PublishedCultures => _publishInfos?.Keys; /// public bool IsCultureEdited(string culture) diff --git a/src/Umbraco.Tests/Models/VariationTests.cs b/src/Umbraco.Tests/Models/VariationTests.cs index 0bb1da5cc1..bc0891e397 100644 --- a/src/Umbraco.Tests/Models/VariationTests.cs +++ b/src/Umbraco.Tests/Models/VariationTests.cs @@ -244,7 +244,7 @@ namespace Umbraco.Tests.Models // can publish value // and get edited and published values - Assert.Throws(() => content.TryPublishValues(langFr)); // no name + Assert.IsFalse(content.TryPublishValues(langFr)); // no name content.SetName(langFr, "name-fr"); content.TryPublishValues(langFr); Assert.AreEqual("b", content.GetValue("prop")); @@ -322,7 +322,7 @@ namespace Umbraco.Tests.Models content.SetValue("prop", "a-es", langEs); // cannot publish without a name - Assert.Throws(() => content.TryPublishValues(langFr)); + Assert.IsFalse(content.TryPublishValues(langFr)); // works with a name // and then FR is available, and published From 3cdc0e11428ef07a1b5fa6746c897b0574a2b6ce Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 10:26:32 +1000 Subject: [PATCH 31/58] Removes IShortStringHelper.ReplaceMany, this should just be a normal string extension and removes the need to load in IUmbracoSettings for this simple purpose, this fixes some unit tests --- src/Umbraco.Core/StringExtensions.cs | 22 ++++++++-- .../Strings/DefaultShortStringHelper.cs | 41 +------------------ .../Strings/IShortStringHelper.cs | 17 -------- .../Strings/DefaultShortStringHelperTests.cs | 27 +----------- .../Strings/MockShortStringHelper.cs | 10 ----- .../Strings/StringExtensionsTests.cs | 29 +++++++++---- 6 files changed, 42 insertions(+), 104 deletions(-) diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 8040e6397b..0985e0521c 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -1051,7 +1051,14 @@ namespace Umbraco.Core /// The filtered string. public static string ReplaceMany(this string text, IDictionary replacements) { - return Current.ShortStringHelper.ReplaceMany(text, replacements); + if (text == null) throw new ArgumentNullException(nameof(text)); + if (replacements == null) throw new ArgumentNullException(nameof(replacements)); + + + foreach (KeyValuePair item in replacements) + text = text.Replace(item.Key, item.Value); + + return text; } /// @@ -1062,9 +1069,16 @@ namespace Umbraco.Core /// The replacement character. /// The filtered string. public static string ReplaceMany(this string text, char[] chars, char replacement) - { - return Current.ShortStringHelper.ReplaceMany(text, chars, replacement); - } + { + if (text == null) throw new ArgumentNullException(nameof(text)); + if (chars == null) throw new ArgumentNullException(nameof(chars)); + + + for (int i = 0; i < chars.Length; i++) + text = text.Replace(chars[i], replacement); + + return text; + } // FORMAT STRINGS diff --git a/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs b/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs index 42a2d3b5d4..3a9d9433f4 100644 --- a/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs +++ b/src/Umbraco.Core/Strings/DefaultShortStringHelper.cs @@ -670,45 +670,6 @@ function validateSafeAlias(input, value, immediate, callback) {{ #endregion - #region ReplaceMany - - /// - /// Returns a new string in which all occurences of specified strings are replaced by other specified strings. - /// - /// The string to filter. - /// The replacements definition. - /// The filtered string. - public virtual string ReplaceMany(string text, IDictionary replacements) - { - if (text == null) throw new ArgumentNullException(nameof(text)); - if (replacements == null) throw new ArgumentNullException(nameof(replacements)); - - - foreach (KeyValuePair item in replacements) - text = text.Replace(item.Key, item.Value); - - return text; - } - - /// - /// Returns a new string in which all occurences of specified characters are replaced by a specified character. - /// - /// The string to filter. - /// The characters to replace. - /// The replacement character. - /// The filtered string. - public virtual string ReplaceMany(string text, char[] chars, char replacement) - { - if (text == null) throw new ArgumentNullException(nameof(text)); - if (chars == null) throw new ArgumentNullException(nameof(chars)); - - - for (int i = 0; i < chars.Length; i++) - text = text.Replace(chars[i], replacement); - - return text; - } - - #endregion + } } diff --git a/src/Umbraco.Core/Strings/IShortStringHelper.cs b/src/Umbraco.Core/Strings/IShortStringHelper.cs index f48d43aa4f..7232b0efe7 100644 --- a/src/Umbraco.Core/Strings/IShortStringHelper.cs +++ b/src/Umbraco.Core/Strings/IShortStringHelper.cs @@ -77,23 +77,6 @@ namespace Umbraco.Core.Strings /// Supports Utf8 and Ascii strings, not Unicode strings. string SplitPascalCasing(string text, char separator); - /// - /// Returns a new string in which all occurences of specified strings are replaced by other specified strings. - /// - /// The string to filter. - /// The replacements definition. - /// The filtered string. - string ReplaceMany(string text, IDictionary replacements); - - /// - /// Returns a new string in which all occurences of specified characters are replaced by a specified character. - /// - /// The string to filter. - /// The characters to replace. - /// The replacement character. - /// The filtered string. - string ReplaceMany(string text, char[] chars, char replacement); - /// /// Cleans a string. /// diff --git a/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs b/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs index 19cac22287..543b4133f9 100644 --- a/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs +++ b/src/Umbraco.Tests/Strings/DefaultShortStringHelperTests.cs @@ -596,32 +596,7 @@ namespace Umbraco.Tests.Strings Assert.AreEqual(expected, output); } - [Test] // can't do cases with an IDictionary - public void ReplaceManyWithCharMap() - { - const string input = "télévisiön tzvâr ßup   pof"; - const string expected = "television tzvar ssup pof"; - IDictionary replacements = new Dictionary - { - { "é", "e" }, - { "ö", "o" }, - { "â", "a" }, - { "ß", "ss" }, - { " ", " " }, - }; - var output = _helper.ReplaceMany(input, replacements); - Assert.AreEqual(expected, output); - } - - #region Cases - [TestCase("val$id!ate|this|str'ing", "$!'", '-', "val-id-ate|this|str-ing")] - [TestCase("val$id!ate|this|str'ing", "$!'", '*', "val*id*ate|this|str*ing")] - #endregion - public void ReplaceManyByOneChar(string input, string toReplace, char replacement, string expected) - { - var output = _helper.ReplaceMany(input, toReplace.ToArray(), replacement); - Assert.AreEqual(expected, output); - } + #region Cases [TestCase("foo.txt", "foo.txt")] diff --git a/src/Umbraco.Tests/Strings/MockShortStringHelper.cs b/src/Umbraco.Tests/Strings/MockShortStringHelper.cs index dfdb307502..964e1d7ad2 100644 --- a/src/Umbraco.Tests/Strings/MockShortStringHelper.cs +++ b/src/Umbraco.Tests/Strings/MockShortStringHelper.cs @@ -59,16 +59,6 @@ namespace Umbraco.Tests.Strings return "SPLIT-PASCAL-CASING::" + text; } - public string ReplaceMany(string text, IDictionary replacements) - { - return "REPLACE-MANY-A::" + text; - } - - public string ReplaceMany(string text, char[] chars, char replacement) - { - return "REPLACE-MANY-B::" + text; - } - public string CleanString(string text, CleanStringType stringType) { return "CLEAN-STRING-A::" + text; diff --git a/src/Umbraco.Tests/Strings/StringExtensionsTests.cs b/src/Umbraco.Tests/Strings/StringExtensionsTests.cs index be64ecbbd6..b297f27656 100644 --- a/src/Umbraco.Tests/Strings/StringExtensionsTests.cs +++ b/src/Umbraco.Tests/Strings/StringExtensionsTests.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Composing; @@ -232,18 +234,31 @@ namespace Umbraco.Tests.Strings Assert.AreEqual("SPLIT-PASCAL-CASING::JUST-ANYTHING", output); } - [Test] + [Test] // can't do cases with an IDictionary public void ReplaceManyWithCharMap() { - var output = "JUST-ANYTHING".ReplaceMany(null); - Assert.AreEqual("REPLACE-MANY-A::JUST-ANYTHING", output); + const string input = "télévisiön tzvâr ßup   pof"; + const string expected = "television tzvar ssup pof"; + IDictionary replacements = new Dictionary + { + { "é", "e" }, + { "ö", "o" }, + { "â", "a" }, + { "ß", "ss" }, + { " ", " " }, + }; + var output = input.ReplaceMany(replacements); + Assert.AreEqual(expected, output); } - [Test] - public void ReplaceManyByOneChar() + #region Cases + [TestCase("val$id!ate|this|str'ing", "$!'", '-', "val-id-ate|this|str-ing")] + [TestCase("val$id!ate|this|str'ing", "$!'", '*', "val*id*ate|this|str*ing")] + #endregion + public void ReplaceManyByOneChar(string input, string toReplace, char replacement, string expected) { - var output = "JUST-ANYTHING".ReplaceMany(new char[] {}, '*'); - Assert.AreEqual("REPLACE-MANY-B::JUST-ANYTHING", output); + var output = input.ReplaceMany(toReplace.ToArray(), replacement); + Assert.AreEqual(expected, output); } } } From 59b6665ff3d669094643d7c604e1b186db8b0e06 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 10:57:51 +1000 Subject: [PATCH 32/58] Removes NiceUrl methods, renames NiceUrl test cases --- ... => ContentFinderByUrlAndTemplateTests.cs} | 96 +- ...UrlTests.cs => ContentFinderByUrlTests.cs} | 314 +++---- ... => ContentFinderByUrlWithDomainsTests.cs} | 374 ++++---- ...rlProviderTests.cs => UrlProviderTests.cs} | 404 ++++----- ...iceUrlRoutesTests.cs => UrlRoutesTests.cs} | 2 +- ...sts.cs => UrlsProviderWithDomainsTests.cs} | 832 +++++++++--------- src/Umbraco.Tests/Umbraco.Tests.csproj | 12 +- src/Umbraco.Web/Editors/ContentController.cs | 2 +- .../RelatedLinksLegacyValueConverter.cs | 2 +- src/Umbraco.Web/RelatedLinksTypeConverter.cs | 2 +- src/Umbraco.Web/Search/UmbracoTreeSearcher.cs | 2 +- src/Umbraco.Web/UmbracoHelper.cs | 28 +- .../umbraco.presentation/library.cs | 4 +- 13 files changed, 1028 insertions(+), 1046 deletions(-) rename src/Umbraco.Tests/Routing/{ContentFinderByNiceUrlAndTemplateTests.cs => ContentFinderByUrlAndTemplateTests.cs} (94%) rename src/Umbraco.Tests/Routing/{ContentFinderByNiceUrlTests.cs => ContentFinderByUrlTests.cs} (97%) rename src/Umbraco.Tests/Routing/{ContentFinderByNiceUrlWithDomainsTests.cs => ContentFinderByUrlWithDomainsTests.cs} (98%) rename src/Umbraco.Tests/Routing/{NiceUrlProviderTests.cs => UrlProviderTests.cs} (97%) rename src/Umbraco.Tests/Routing/{NiceUrlRoutesTests.cs => UrlRoutesTests.cs} (99%) rename src/Umbraco.Tests/Routing/{NiceUrlsProviderWithDomainsTests.cs => UrlsProviderWithDomainsTests.cs} (98%) diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs similarity index 94% rename from src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs rename to src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs index 7a4be24fbf..5080ab339d 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlAndTemplateTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlAndTemplateTests.cs @@ -1,52 +1,52 @@ -using Moq; +using Moq; using NUnit.Framework; -using LightInject; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web.Routing; -using Umbraco.Core.Models; -using Umbraco.Tests.Testing; -using Current = Umbraco.Web.Composing.Current; +using LightInject; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web.Routing; +using Umbraco.Core.Models; +using Umbraco.Tests.Testing; +using Current = Umbraco.Web.Composing.Current; using Umbraco.Core.Configuration.UmbracoSettings; -namespace Umbraco.Tests.Routing -{ - [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] - public class ContentFinderByNiceUrlAndTemplateTests : BaseWebTest - { - Template CreateTemplate(string alias) - { - var template = new Template(alias, alias); - template.Content = ""; // else saving throws with a dirty internal error - Current.Services.FileService.SaveTemplate(template); - return template; - } - - [TestCase("/blah")] - [TestCase("/default.aspx/blah")] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! - [TestCase("/home/Sub1/blah")] - [TestCase("/Home/Sub1/Blah")] //different cases - [TestCase("/home/Sub1.aspx/blah")] - public void Match_Document_By_Url_With_Template(string urlAsString) - { - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); +namespace Umbraco.Tests.Routing +{ + [TestFixture] + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] + public class ContentFinderByUrlAndTemplateTests : BaseWebTest + { + Template CreateTemplate(string alias) + { + var template = new Template(alias, alias); + template.Content = ""; // else saving throws with a dirty internal error + Current.Services.FileService.SaveTemplate(template); + return template; + } + + [TestCase("/blah")] + [TestCase("/default.aspx/blah")] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! + [TestCase("/home/Sub1/blah")] + [TestCase("/Home/Sub1/Blah")] //different cases + [TestCase("/home/Sub1.aspx/blah")] + public void Match_Document_By_Url_With_Template(string urlAsString) + { + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var template1 = CreateTemplate("test"); - var template2 = CreateTemplate("blah"); - var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByUrlAndTemplate(Logger, ServiceContext.FileService); - - var result = lookup.TryFindContent(frequest); - - Assert.IsTrue(result); - Assert.IsNotNull(frequest.PublishedContent); - Assert.IsNotNull(frequest.TemplateAlias); - Assert.AreEqual("blah".ToUpperInvariant(), frequest.TemplateAlias.ToUpperInvariant()); - } - } -} + + var template1 = CreateTemplate("test"); + var template2 = CreateTemplate("blah"); + var umbracoContext = GetUmbracoContext(urlAsString, template1.Id, globalSettings:globalSettings.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + var lookup = new ContentFinderByUrlAndTemplate(Logger, ServiceContext.FileService); + + var result = lookup.TryFindContent(frequest); + + Assert.IsTrue(result); + Assert.IsNotNull(frequest.PublishedContent); + Assert.IsNotNull(frequest.TemplateAlias); + Assert.AreEqual("blah".ToUpperInvariant(), frequest.TemplateAlias.ToUpperInvariant()); + } + } +} diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs similarity index 97% rename from src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs rename to src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs index 3e8101a212..108abfe446 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs @@ -1,166 +1,166 @@ -using System; -using System.Globalization; -using Moq; -using NUnit.Framework; -using Umbraco.Core.Configuration; -using Umbraco.Core.Models; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; -using Umbraco.Web.Routing; - -namespace Umbraco.Tests.Routing -{ - [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class ContentFinderByNiceUrlTests : BaseWebTest - { - [TestCase("/", 1046)] - [TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! - [TestCase("/Sub1", 1173)] - [TestCase("/sub1", 1173)] - [TestCase("/sub1.aspx", 1173)] - [TestCase("/home/sub1", -1)] // should fail - - // these two are special. getNiceUrl(1046) returns "/" but getNiceUrl(1172) cannot also return "/" so - // we've made it return "/test-page" => we have to support that url back in the lookup... - [TestCase("/home", 1046)] - [TestCase("/test-page", 1172)] - public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId) - { - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); +using System; +using System.Globalization; +using Moq; +using NUnit.Framework; +using Umbraco.Core.Configuration; +using Umbraco.Core.Models; +using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.Testing; +using Umbraco.Web.Routing; + +namespace Umbraco.Tests.Routing +{ + [TestFixture] + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] + public class ContentFinderByUrlTests : BaseWebTest + { + [TestCase("/", 1046)] + [TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! + [TestCase("/Sub1", 1173)] + [TestCase("/sub1", 1173)] + [TestCase("/sub1.aspx", 1173)] + [TestCase("/home/sub1", -1)] // should fail + + // these two are special. getNiceUrl(1046) returns "/" but getNiceUrl(1172) cannot also return "/" so + // we've made it return "/test-page" => we have to support that url back in the lookup... + [TestCase("/home", 1046)] + [TestCase("/test-page", 1172)] + public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId) + { + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByUrl(Logger); - - Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); - - // fixme debugging - going further down, the routes cache is NOT empty?! - if (urlString == "/home/sub1") - System.Diagnostics.Debugger.Break(); - - var result = lookup.TryFindContent(frequest); - - if (expectedId > 0) - { - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - else - { - Assert.IsFalse(result); - } - } - - [TestCase("/", 1046)] - [TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! - [TestCase("/home", 1046)] - [TestCase("/home/Sub1", 1173)] - [TestCase("/Home/Sub1", 1173)] //different cases - [TestCase("/home/Sub1.aspx", 1173)] - public void Match_Document_By_Url(string urlString, int expectedId) - { - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + var lookup = new ContentFinderByUrl(Logger); + + Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); + + // fixme debugging - going further down, the routes cache is NOT empty?! + if (urlString == "/home/sub1") + System.Diagnostics.Debugger.Break(); + + var result = lookup.TryFindContent(frequest); + + if (expectedId > 0) + { + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + else + { + Assert.IsFalse(result); + } + } + + [TestCase("/", 1046)] + [TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' ! + [TestCase("/home", 1046)] + [TestCase("/home/Sub1", 1173)] + [TestCase("/Home/Sub1", 1173)] //different cases + [TestCase("/home/Sub1.aspx", 1173)] + public void Match_Document_By_Url(string urlString, int expectedId) + { + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByUrl(Logger); - - Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); - - var result = lookup.TryFindContent(frequest); - - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - /// - /// This test handles requests with special characters in the URL. - /// - /// - /// - [TestCase("/", 1046)] - [TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)] - [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] - public void Match_Document_By_Url_With_Special_Characters(string urlString, int expectedId) - { - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + var lookup = new ContentFinderByUrl(Logger); + + Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); + + var result = lookup.TryFindContent(frequest); + + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + /// + /// This test handles requests with special characters in the URL. + /// + /// + /// + [TestCase("/", 1046)] + [TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)] + [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] + public void Match_Document_By_Url_With_Special_Characters(string urlString, int expectedId) + { + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - var lookup = new ContentFinderByUrl(Logger); - - var result = lookup.TryFindContent(frequest); - - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - - /// - /// This test handles requests with a hostname associated. - /// The logic for handling this goes through the DomainHelper and is a bit different - /// from what happens in a normal request - so it has a separate test with a mocked - /// hostname added. - /// - /// - /// - [TestCase("/", 1046)] - [TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)] - [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] - public void Match_Document_By_Url_With_Special_Characters_Using_Hostname(string urlString, int expectedId) - { - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + var lookup = new ContentFinderByUrl(Logger); + + var result = lookup.TryFindContent(frequest); + + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + + /// + /// This test handles requests with a hostname associated. + /// The logic for handling this goes through the DomainHelper and is a bit different + /// from what happens in a normal request - so it has a separate test with a mocked + /// hostname added. + /// + /// + /// + [TestCase("/", 1046)] + [TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)] + [TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)] + public void Match_Document_By_Url_With_Special_Characters_Using_Hostname(string urlString, int expectedId) + { + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/")); - var lookup = new ContentFinderByUrl(Logger); - - var result = lookup.TryFindContent(frequest); - - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - - /// - /// This test handles requests with a hostname with special characters associated. - /// The logic for handling this goes through the DomainHelper and is a bit different - /// from what happens in a normal request - so it has a separate test with a mocked - /// hostname added. - /// - /// - /// - [TestCase("/æøå/", 1046)] - [TestCase("/æøå/home/sub1", 1173)] - [TestCase("/æøå/home/sub1/custom-sub-3-with-accént-character", 1179)] - [TestCase("/æøå/home/sub1/custom-sub-4-with-æøå", 1180)] - public void Match_Document_By_Url_With_Special_Characters_In_Hostname(string urlString, int expectedId) - { - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/")); + var lookup = new ContentFinderByUrl(Logger); + + var result = lookup.TryFindContent(frequest); + + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + + /// + /// This test handles requests with a hostname with special characters associated. + /// The logic for handling this goes through the DomainHelper and is a bit different + /// from what happens in a normal request - so it has a separate test with a mocked + /// hostname added. + /// + /// + /// + [TestCase("/æøå/", 1046)] + [TestCase("/æøå/home/sub1", 1173)] + [TestCase("/æøå/home/sub1/custom-sub-3-with-accént-character", 1179)] + [TestCase("/æøå/home/sub1/custom-sub-4-with-æøå", 1180)] + public void Match_Document_By_Url_With_Special_Characters_In_Hostname(string urlString, int expectedId) + { + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(); - var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/æøå")); - var lookup = new ContentFinderByUrl(Logger); - - var result = lookup.TryFindContent(frequest); - - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - } -} + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(); + var frequest = publishedRouter.CreateRequest(umbracoContext); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/æøå")); + var lookup = new ContentFinderByUrl(Logger); + + var result = lookup.TryFindContent(frequest); + + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + } +} diff --git a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs similarity index 98% rename from src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs rename to src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs index 2e9bccf398..949467a6fe 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByNiceUrlWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlWithDomainsTests.cs @@ -1,188 +1,188 @@ -using Moq; -using NUnit.Framework; -using Umbraco.Core.Models; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web.Routing; - -namespace Umbraco.Tests.Routing -{ - - [TestFixture] - public class ContentFinderByNiceUrlWithDomainsTests : UrlRoutingTestBase - { - void SetDomains3() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangDeId, RootContentId = 1001, LanguageIsoCode = "de-DE"} - }); - - } - - void SetDomains4() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1001, LanguageIsoCode = "en-US"}, - new UmbracoDomain("domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, - new UmbracoDomain("domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, - new UmbracoDomain("http://domain3.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1003, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} - }); - - } - - protected override string GetXmlContent(int templateId) - { - return @" - - -]> - - - - - This is some content
    ]]> - - - - - - - - - - - - - - - This is some content
    ]]> - - - - - - - - - - - - - - - - - - - - - - This is some content]]> - - - - - - - - - - - - - - - This is some content]]> - - - - - - - - - - - - - - - - -"; - } - - [TestCase("http://domain1.com/", 1001)] - [TestCase("http://domain1.com/1001-1", 10011)] - [TestCase("http://domain1.com/1001-2/1001-2-1", 100121)] - - public void Lookup_SingleDomain(string url, int expectedId) - { - SetDomains3(); - - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container +using Moq; +using NUnit.Framework; +using Umbraco.Core.Models; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web.Routing; + +namespace Umbraco.Tests.Routing +{ + + [TestFixture] + public class ContentFinderByUrlWithDomainsTests : UrlRoutingTestBase + { + void SetDomains3() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangDeId, RootContentId = 1001, LanguageIsoCode = "de-DE"} + }); + + } + + void SetDomains4() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1001, LanguageIsoCode = "en-US"}, + new UmbracoDomain("domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, + new UmbracoDomain("domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, + new UmbracoDomain("http://domain3.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1003, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} + }); + + } + + protected override string GetXmlContent(int templateId) + { + return @" + + +]> + + + + + This is some content]]> + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + + +"; + } + + [TestCase("http://domain1.com/", 1001)] + [TestCase("http://domain1.com/1001-1", 10011)] + [TestCase("http://domain1.com/1001-2/1001-2-1", 100121)] + + public void Lookup_SingleDomain(string url, int expectedId) + { + SetDomains3(); + + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); - SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - - var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(Container); - var frequest = publishedRouter.CreateRequest(umbracoContext); - - // must lookup domain else lookup by url fails - publishedRouter.FindDomain(frequest); - - var lookup = new ContentFinderByUrl(Logger); - var result = lookup.TryFindContent(frequest); - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - - [TestCase("http://domain1.com/", 1001, "en-US")] - [TestCase("http://domain1.com/en", 10011, "en-US")] - [TestCase("http://domain1.com/en/1001-1-1", 100111, "en-US")] - [TestCase("http://domain1.com/fr", 10012, "fr-FR")] - [TestCase("http://domain1.com/fr/1001-2-1", 100121, "fr-FR")] - [TestCase("http://domain1.com/1001-3", 10013, "en-US")] - - [TestCase("http://domain2.com/1002", 1002, null)] - - [TestCase("http://domain3.com/", 1003, "en-US")] - [TestCase("http://domain3.com/en", 10031, "en-US")] - [TestCase("http://domain3.com/en/1003-1-1", 100311, "en-US")] - [TestCase("http://domain3.com/fr", 10032, "fr-FR")] - [TestCase("http://domain3.com/fr/1003-2-1", 100321, "fr-FR")] - [TestCase("http://domain3.com/1003-3", 10033, "en-US")] - - [TestCase("https://domain1.com/", 1001, "en-US")] - [TestCase("https://domain3.com/", 1001, null)] // because domain3 is explicitely set on http - - public void Lookup_NestedDomains(string url, int expectedId, string expectedCulture) - { - SetDomains4(); - - // defaults depend on test environment - expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; - - var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); - SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - - var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); - var publishedRouter = CreatePublishedRouter(Container); - var frequest = publishedRouter.CreateRequest(umbracoContext); - - // must lookup domain else lookup by url fails - publishedRouter.FindDomain(frequest); - Assert.AreEqual(expectedCulture, frequest.Culture.Name); - - var lookup = new ContentFinderByUrl(Logger); - var result = lookup.TryFindContent(frequest); - Assert.IsTrue(result); - Assert.AreEqual(expectedId, frequest.PublishedContent.Id); - } - } -} + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(Container); + var frequest = publishedRouter.CreateRequest(umbracoContext); + + // must lookup domain else lookup by url fails + publishedRouter.FindDomain(frequest); + + var lookup = new ContentFinderByUrl(Logger); + var result = lookup.TryFindContent(frequest); + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + + [TestCase("http://domain1.com/", 1001, "en-US")] + [TestCase("http://domain1.com/en", 10011, "en-US")] + [TestCase("http://domain1.com/en/1001-1-1", 100111, "en-US")] + [TestCase("http://domain1.com/fr", 10012, "fr-FR")] + [TestCase("http://domain1.com/fr/1001-2-1", 100121, "fr-FR")] + [TestCase("http://domain1.com/1001-3", 10013, "en-US")] + + [TestCase("http://domain2.com/1002", 1002, null)] + + [TestCase("http://domain3.com/", 1003, "en-US")] + [TestCase("http://domain3.com/en", 10031, "en-US")] + [TestCase("http://domain3.com/en/1003-1-1", 100311, "en-US")] + [TestCase("http://domain3.com/fr", 10032, "fr-FR")] + [TestCase("http://domain3.com/fr/1003-2-1", 100321, "fr-FR")] + [TestCase("http://domain3.com/1003-3", 10033, "en-US")] + + [TestCase("https://domain1.com/", 1001, "en-US")] + [TestCase("https://domain3.com/", 1001, null)] // because domain3 is explicitely set on http + + public void Lookup_NestedDomains(string url, int expectedId, string expectedCulture) + { + SetDomains4(); + + // defaults depend on test environment + expectedCulture = expectedCulture ?? System.Threading.Thread.CurrentThread.CurrentUICulture.Name; + + var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + SettingsForTests.ConfigureSettings(globalSettingsMock.Object); + + var umbracoContext = GetUmbracoContext(url, globalSettings:globalSettingsMock.Object); + var publishedRouter = CreatePublishedRouter(Container); + var frequest = publishedRouter.CreateRequest(umbracoContext); + + // must lookup domain else lookup by url fails + publishedRouter.FindDomain(frequest); + Assert.AreEqual(expectedCulture, frequest.Culture.Name); + + var lookup = new ContentFinderByUrl(Logger); + var result = lookup.TryFindContent(frequest); + Assert.IsTrue(result); + Assert.AreEqual(expectedId, frequest.PublishedContent.Id); + } + } +} diff --git a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs similarity index 97% rename from src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs rename to src/Umbraco.Tests/Routing/UrlProviderTests.cs index a4b51bad85..23d3c84bc9 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -1,208 +1,208 @@ -using System; -using System.Collections.Generic; -using Moq; -using NUnit.Framework; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Tests.TestHelpers; -using Umbraco.Tests.Testing; -using Umbraco.Web.PublishedCache.XmlPublishedCache; -using Umbraco.Web.Routing; - -namespace Umbraco.Tests.Routing -{ - [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] - public class NiceUrlProviderTests : BaseWebTest - { - protected override void Compose() - { - base.Compose(); - Container.Register(); - } - - private IUmbracoSettingsSection _umbracoSettings; - - public override void SetUp() - { - base.SetUp(); - - //generate new mock settings and assign so we can configure in individual tests - _umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings(); - SettingsForTests.ConfigureSettings(_umbracoSettings); - } - - /// - /// This checks that when we retrieve a NiceUrl for multiple items that there are no issues with cache overlap - /// and that they are all cached correctly. - /// - [Test] - public void Ensure_Cache_Is_Correct() - { - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); +using System; +using System.Collections.Generic; +using Moq; +using NUnit.Framework; +using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.Testing; +using Umbraco.Web.PublishedCache.XmlPublishedCache; +using Umbraco.Web.Routing; + +namespace Umbraco.Tests.Routing +{ + [TestFixture] + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] + public class UrlProviderTests : BaseWebTest + { + protected override void Compose() + { + base.Compose(); + Container.Register(); + } + + private IUmbracoSettingsSection _umbracoSettings; + + public override void SetUp() + { + base.SetUp(); + + //generate new mock settings and assign so we can configure in individual tests + _umbracoSettings = SettingsForTests.GenerateMockUmbracoSettings(); + SettingsForTests.ConfigureSettings(_umbracoSettings); + } + + /// + /// This checks that when we retrieve a NiceUrl for multiple items that there are no issues with cache overlap + /// and that they are all cached correctly. + /// + [Test] + public void Ensure_Cache_Is_Correct() + { + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] - { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler); - requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none) - - var samples = new Dictionary { - { 1046, "/home" }, - { 1173, "/home/sub1" }, - { 1174, "/home/sub1/sub2" }, - { 1176, "/home/sub1/sub-3" }, - { 1177, "/home/sub1/custom-sub-1" }, - { 1178, "/home/sub1/custom-sub-2" }, - { 1175, "/home/sub-2" }, - { 1172, "/test-page" } - }; - - foreach (var sample in samples) - { - var result = umbracoContext.UrlProvider.GetUrl(sample.Key); - Assert.AreEqual(sample.Value, result); - } - - var randomSample = new KeyValuePair(1177, "/home/sub1/custom-sub-1"); - for (int i = 0; i < 5; i++) - { - var result = umbracoContext.UrlProvider.GetUrl(randomSample.Key); - Assert.AreEqual(randomSample.Value, result); - } - - var cache = umbracoContext.ContentCache as PublishedContentCache; - if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - var cachedRoutes = cache.RoutesCache.GetCachedRoutes(); - Assert.AreEqual(8, cachedRoutes.Count); - - foreach (var sample in samples) - { - Assert.IsTrue(cachedRoutes.ContainsKey(sample.Key)); - Assert.AreEqual(sample.Value, cachedRoutes[sample.Key]); - } - - var cachedIds = cache.RoutesCache.GetCachedIds(); - Assert.AreEqual(0, cachedIds.Count); - } - - // test hideTopLevelNodeFromPath false - [TestCase(1046, "/home/")] - [TestCase(1173, "/home/sub1/")] - [TestCase(1174, "/home/sub1/sub2/")] - [TestCase(1176, "/home/sub1/sub-3/")] - [TestCase(1177, "/home/sub1/custom-sub-1/")] - [TestCase(1178, "/home/sub1/custom-sub-2/")] - [TestCase(1175, "/home/sub-2/")] - [TestCase(1172, "/test-page/")] - public void Get_Nice_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) - { - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler); + requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none) + + var samples = new Dictionary { + { 1046, "/home" }, + { 1173, "/home/sub1" }, + { 1174, "/home/sub1/sub2" }, + { 1176, "/home/sub1/sub-3" }, + { 1177, "/home/sub1/custom-sub-1" }, + { 1178, "/home/sub1/custom-sub-2" }, + { 1175, "/home/sub-2" }, + { 1172, "/test-page" } + }; + + foreach (var sample in samples) + { + var result = umbracoContext.UrlProvider.GetUrl(sample.Key); + Assert.AreEqual(sample.Value, result); + } + + var randomSample = new KeyValuePair(1177, "/home/sub1/custom-sub-1"); + for (int i = 0; i < 5; i++) + { + var result = umbracoContext.UrlProvider.GetUrl(randomSample.Key); + Assert.AreEqual(randomSample.Value, result); + } + + var cache = umbracoContext.ContentCache as PublishedContentCache; + if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); + var cachedRoutes = cache.RoutesCache.GetCachedRoutes(); + Assert.AreEqual(8, cachedRoutes.Count); + + foreach (var sample in samples) + { + Assert.IsTrue(cachedRoutes.ContainsKey(sample.Key)); + Assert.AreEqual(sample.Value, cachedRoutes[sample.Key]); + } + + var cachedIds = cache.RoutesCache.GetCachedIds(); + Assert.AreEqual(0, cachedIds.Count); + } + + // test hideTopLevelNodeFromPath false + [TestCase(1046, "/home/")] + [TestCase(1173, "/home/sub1/")] + [TestCase(1174, "/home/sub1/sub2/")] + [TestCase(1176, "/home/sub1/sub-3/")] + [TestCase(1177, "/home/sub1/custom-sub-1/")] + [TestCase(1178, "/home/sub1/custom-sub-2/")] + [TestCase(1175, "/home/sub-2/")] + [TestCase(1172, "/test-page/")] + public void Get_Nice_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) + { + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] - { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - var requestMock = Mock.Get(_umbracoSettings.RequestHandler); - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - var result = umbracoContext.UrlProvider.GetUrl(nodeId); - Assert.AreEqual(niceUrlMatch, result); - } - - // no need for umbracoUseDirectoryUrls test = should be handled by UriUtilityTests - - // test hideTopLevelNodeFromPath true - [TestCase(1046, "/")] - [TestCase(1173, "/sub1/")] - [TestCase(1174, "/sub1/sub2/")] - [TestCase(1176, "/sub1/sub-3/")] - [TestCase(1177, "/sub1/custom-sub-1/")] - [TestCase(1178, "/sub1/custom-sub-2/")] - [TestCase(1175, "/sub-2/")] - [TestCase(1172, "/test-page/")] // not hidden because not first root - public void Get_Nice_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) - { - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); + + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var result = umbracoContext.UrlProvider.GetUrl(nodeId); + Assert.AreEqual(niceUrlMatch, result); + } + + // no need for umbracoUseDirectoryUrls test = should be handled by UriUtilityTests + + // test hideTopLevelNodeFromPath true + [TestCase(1046, "/")] + [TestCase(1173, "/sub1/")] + [TestCase(1174, "/sub1/sub2/")] + [TestCase(1176, "/sub1/sub-3/")] + [TestCase(1177, "/sub1/custom-sub-1/")] + [TestCase(1178, "/sub1/custom-sub-2/")] + [TestCase(1175, "/sub-2/")] + [TestCase(1172, "/test-page/")] // not hidden because not first root + public void Get_Nice_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) + { + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(true); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] - { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - var requestMock = Mock.Get(_umbracoSettings.RequestHandler); - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - var result = umbracoContext.UrlProvider.GetUrl(nodeId); - Assert.AreEqual(niceUrlMatch, result); - } - - [Test] - public void Get_Nice_Url_Relative_Or_Absolute() - { - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var result = umbracoContext.UrlProvider.GetUrl(nodeId); + Assert.AreEqual(niceUrlMatch, result); + } + + [Test] + public void Get_Nice_Url_Relative_Or_Absolute() + { + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var requestMock = Mock.Get(_umbracoSettings.RequestHandler); - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] - { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); - Assert.AreEqual("http://example.com/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; - Assert.AreEqual("http://example.com/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); - } - - [Test] - public void Get_Nice_Url_Unpublished() - { - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); + Assert.AreEqual("http://example.com/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; + Assert.AreEqual("http://example.com/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); + } + + [Test] + public void Get_Nice_Url_Unpublished() + { + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] - { - new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - //mock the Umbraco settings that we need - var requestMock = Mock.Get(_umbracoSettings.RequestHandler); - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); - - Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; - - Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); - } - } -} + + var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] + { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + //mock the Umbraco settings that we need + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); + + Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; + + Assert.AreEqual("#", umbracoContext.UrlProvider.GetUrl(999999)); + } + } +} diff --git a/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs b/src/Umbraco.Tests/Routing/UrlRoutesTests.cs similarity index 99% rename from src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs rename to src/Umbraco.Tests/Routing/UrlRoutesTests.cs index 2c44a26117..9b291249c9 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlRoutesTests.cs +++ b/src/Umbraco.Tests/Routing/UrlRoutesTests.cs @@ -13,7 +13,7 @@ namespace Umbraco.Tests.Routing // the quirks due to hideTopLevelFromPath and backward compatibility. [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)] - public class NiceUrlRoutesTests : TestWithDatabaseBase + public class UrlRoutesTests : TestWithDatabaseBase { #region Test Setup diff --git a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs similarity index 98% rename from src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs rename to src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs index 938f0cbec6..4f4e35f7e2 100644 --- a/src/Umbraco.Tests/Routing/NiceUrlsProviderWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs @@ -1,423 +1,423 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Moq; -using NUnit.Framework; -using Umbraco.Core.Models; -using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web.PublishedCache.XmlPublishedCache; -using Umbraco.Web.Routing; -using Umbraco.Core.Composing; - -namespace Umbraco.Tests.Routing -{ - [TestFixture] - public class NiceUrlsProviderWithDomainsTests : UrlRoutingTestBase - { - protected override void Compose() - { - base.Compose(); - - Container.RegisterSingleton(_ => Mock.Of()); - Container.Register(); - } - - void SetDomains1() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("domain1.com") {Id = 1, LanguageId = LangFrId, RootContentId = 1001, LanguageIsoCode = "fr-FR"} - }); - } - - void SetDomains2() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("http://domain1.com/foo") {Id = 1, LanguageId = LangFrId, RootContentId = 1001, LanguageIsoCode = "fr-FR"} - }); - } - - void SetDomains3() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("http://domain1.com/") {Id = 1, LanguageId = LangFrId, RootContentId = 10011, LanguageIsoCode = "fr-FR"} - }); - } - - void SetDomains4() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("http://domain1.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1001, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, - new UmbracoDomain("http://domain3.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1003, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} - }); - } - - void SetDomains5() - { - SetupDomainServiceMock(new[] - { - new UmbracoDomain("http://domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain1a.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain1b.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, - new UmbracoDomain("http://domain1a.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, - new UmbracoDomain("http://domain1b.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, - new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, - new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} - }); - } - - protected override string GetXmlContent(int templateId) - { - return @" - - -]> - - - - - This is some content]]> - - - - - - - - - - - - - - - This is some content]]> - - - - - - - - - - - - - - - - - - - - - - This is some content]]> - - - - - - - - - - - - - - - This is some content]]> - - - - - - - - - - - - - - - - -"; - } - - // with one simple domain "domain1.com" - // basic tests - [TestCase(1001, "http://domain1.com", false, "/")] - [TestCase(10011, "http://domain1.com", false, "/1001-1/")] - [TestCase(1002, "http://domain1.com", false, "/1002/")] - // absolute tests - [TestCase(1001, "http://domain1.com", true, "http://domain1.com/")] - [TestCase(10011, "http://domain1.com", true, "http://domain1.com/1001-1/")] - // different current tests - [TestCase(1001, "http://domain2.com", false, "http://domain1.com/")] - [TestCase(10011, "http://domain2.com", false, "http://domain1.com/1001-1/")] - [TestCase(1001, "https://domain1.com", false, "/")] - [TestCase(10011, "https://domain1.com", false, "/1001-1/")] - public void Get_Nice_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var request = Mock.Get(settings.RequestHandler); - request.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains +using System; +using System.Collections.Generic; +using System.Linq; +using Moq; +using NUnit.Framework; +using Umbraco.Core.Models; +using Umbraco.Core.Services; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web.PublishedCache.XmlPublishedCache; +using Umbraco.Web.Routing; +using Umbraco.Core.Composing; + +namespace Umbraco.Tests.Routing +{ + [TestFixture] + public class UrlsProviderWithDomainsTests : UrlRoutingTestBase + { + protected override void Compose() + { + base.Compose(); + + Container.RegisterSingleton(_ => Mock.Of()); + Container.Register(); + } + + void SetDomains1() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("domain1.com") {Id = 1, LanguageId = LangFrId, RootContentId = 1001, LanguageIsoCode = "fr-FR"} + }); + } + + void SetDomains2() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("http://domain1.com/foo") {Id = 1, LanguageId = LangFrId, RootContentId = 1001, LanguageIsoCode = "fr-FR"} + }); + } + + void SetDomains3() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("http://domain1.com/") {Id = 1, LanguageId = LangFrId, RootContentId = 10011, LanguageIsoCode = "fr-FR"} + }); + } + + void SetDomains4() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("http://domain1.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1001, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, + new UmbracoDomain("http://domain3.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1003, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} + }); + } + + void SetDomains5() + { + SetupDomainServiceMock(new[] + { + new UmbracoDomain("http://domain1.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain1a.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain1b.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain1.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, + new UmbracoDomain("http://domain1a.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, + new UmbracoDomain("http://domain1b.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, + new UmbracoDomain("http://domain3.com/en") {Id = 1, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, + new UmbracoDomain("http://domain3.com/fr") {Id = 1, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} + }); + } + + protected override string GetXmlContent(int templateId) + { + return @" + + +]> + + + + + This is some content]]> + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + This is some content]]> + + + + + + + + + + + + + + + + +"; + } + + // with one simple domain "domain1.com" + // basic tests + [TestCase(1001, "http://domain1.com", false, "/")] + [TestCase(10011, "http://domain1.com", false, "/1001-1/")] + [TestCase(1002, "http://domain1.com", false, "/1002/")] + // absolute tests + [TestCase(1001, "http://domain1.com", true, "http://domain1.com/")] + [TestCase(10011, "http://domain1.com", true, "http://domain1.com/1001-1/")] + // different current tests + [TestCase(1001, "http://domain2.com", false, "http://domain1.com/")] + [TestCase(10011, "http://domain2.com", false, "http://domain1.com/1001-1/")] + [TestCase(1001, "https://domain1.com", false, "/")] + [TestCase(10011, "https://domain1.com", false, "/1001-1/")] + public void Get_Nice_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var request = Mock.Get(settings.RequestHandler); + request.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains1(); - - var currentUri = new Uri(currentUrl); - var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); - Assert.AreEqual(expected, result); - } - - // with one complete domain "http://domain1.com/foo" - // basic tests - [TestCase(1001, "http://domain1.com", false, "/foo/")] - [TestCase(10011, "http://domain1.com", false, "/foo/1001-1/")] - [TestCase(1002, "http://domain1.com", false, "/1002/")] - // absolute tests - [TestCase(1001, "http://domain1.com", true, "http://domain1.com/foo/")] - [TestCase(10011, "http://domain1.com", true, "http://domain1.com/foo/1001-1/")] - // different current tests - [TestCase(1001, "http://domain2.com", false, "http://domain1.com/foo/")] - [TestCase(10011, "http://domain2.com", false, "http://domain1.com/foo/1001-1/")] - [TestCase(1001, "https://domain1.com", false, "http://domain1.com/foo/")] - [TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")] - public void Get_Nice_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var request = Mock.Get(settings.RequestHandler); - request.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains1(); + + var currentUri = new Uri(currentUrl); + var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); + Assert.AreEqual(expected, result); + } + + // with one complete domain "http://domain1.com/foo" + // basic tests + [TestCase(1001, "http://domain1.com", false, "/foo/")] + [TestCase(10011, "http://domain1.com", false, "/foo/1001-1/")] + [TestCase(1002, "http://domain1.com", false, "/1002/")] + // absolute tests + [TestCase(1001, "http://domain1.com", true, "http://domain1.com/foo/")] + [TestCase(10011, "http://domain1.com", true, "http://domain1.com/foo/1001-1/")] + // different current tests + [TestCase(1001, "http://domain2.com", false, "http://domain1.com/foo/")] + [TestCase(10011, "http://domain2.com", false, "http://domain1.com/foo/1001-1/")] + [TestCase(1001, "https://domain1.com", false, "http://domain1.com/foo/")] + [TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")] + public void Get_Nice_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var request = Mock.Get(settings.RequestHandler); + request.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains2(); - - var currentUri = new Uri(currentUrl); - var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); - Assert.AreEqual(expected, result); - } - - // with one domain, not at root - [TestCase(1001, "http://domain1.com", false, "/1001/")] - [TestCase(10011, "http://domain1.com", false, "/")] - [TestCase(100111, "http://domain1.com", false, "/1001-1-1/")] - [TestCase(1002, "http://domain1.com", false, "/1002/")] - public void Get_Nice_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var request = Mock.Get(settings.RequestHandler); - request.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains2(); + + var currentUri = new Uri(currentUrl); + var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); + Assert.AreEqual(expected, result); + } + + // with one domain, not at root + [TestCase(1001, "http://domain1.com", false, "/1001/")] + [TestCase(10011, "http://domain1.com", false, "/")] + [TestCase(100111, "http://domain1.com", false, "/1001-1-1/")] + [TestCase(1002, "http://domain1.com", false, "/1002/")] + public void Get_Nice_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var request = Mock.Get(settings.RequestHandler); + request.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains3(); - - var currentUri = new Uri(currentUrl); - var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); - Assert.AreEqual(expected, result); - } - - // with nested domains - [TestCase(1001, "http://domain1.com", false, "/")] - [TestCase(10011, "http://domain1.com", false, "/en/")] - [TestCase(100111, "http://domain1.com", false, "/en/1001-1-1/")] - [TestCase(10012, "http://domain1.com", false, "/fr/")] - [TestCase(100121, "http://domain1.com", false, "/fr/1001-2-1/")] - [TestCase(10013, "http://domain1.com", false, "/1001-3/")] - [TestCase(1002, "http://domain1.com", false, "/1002/")] - [TestCase(1003, "http://domain3.com", false, "/")] - [TestCase(10031, "http://domain3.com", false, "/en/")] - [TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")] - public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var request = Mock.Get(settings.RequestHandler); - request.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains3(); + + var currentUri = new Uri(currentUrl); + var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); + Assert.AreEqual(expected, result); + } + + // with nested domains + [TestCase(1001, "http://domain1.com", false, "/")] + [TestCase(10011, "http://domain1.com", false, "/en/")] + [TestCase(100111, "http://domain1.com", false, "/en/1001-1-1/")] + [TestCase(10012, "http://domain1.com", false, "/fr/")] + [TestCase(100121, "http://domain1.com", false, "/fr/1001-2-1/")] + [TestCase(10013, "http://domain1.com", false, "/1001-3/")] + [TestCase(1002, "http://domain1.com", false, "/1002/")] + [TestCase(1003, "http://domain3.com", false, "/")] + [TestCase(10031, "http://domain3.com", false, "/en/")] + [TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")] + public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var request = Mock.Get(settings.RequestHandler); + request.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains4(); - - var currentUri = new Uri(currentUrl); - var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); - Assert.AreEqual(expected, result); - } - - [Test] - public void Get_Nice_Url_DomainsAndCache() - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var request = Mock.Get(settings.RequestHandler); - request.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains4(); + + var currentUri = new Uri(currentUrl); + var result = umbracoContext.UrlProvider.GetUrl(nodeId, currentUri, absolute); + Assert.AreEqual(expected, result); + } + + [Test] + public void Get_Nice_Url_DomainsAndCache() + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var request = Mock.Get(settings.RequestHandler); + request.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains4(); - - string ignore; - ignore = umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain2.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain2.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain2.com"), false); - ignore = umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain2.com"), false); - - var cache = umbracoContext.ContentCache as PublishedContentCache; - if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); - var cachedRoutes = cache.RoutesCache.GetCachedRoutes(); - Assert.AreEqual(7, cachedRoutes.Count); - - var cachedIds = cache.RoutesCache.GetCachedIds(); - Assert.AreEqual(0, cachedIds.Count); - - CheckRoute(cachedRoutes, cachedIds, 1001, "1001/"); - CheckRoute(cachedRoutes, cachedIds, 10011, "10011/"); - CheckRoute(cachedRoutes, cachedIds, 100111, "10011/1001-1-1"); - CheckRoute(cachedRoutes, cachedIds, 10012, "10012/"); - CheckRoute(cachedRoutes, cachedIds, 100121, "10012/1001-2-1"); - CheckRoute(cachedRoutes, cachedIds, 10013, "1001/1001-3"); - CheckRoute(cachedRoutes, cachedIds, 1002, "/1002"); - - // use the cache - Assert.AreEqual("/", umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/en/", umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/fr/", umbracoContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/fr/1001-2-1/", umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/1001-3/", umbracoContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false)); - Assert.AreEqual("/1002/", umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false)); - - Assert.AreEqual("http://domain1.com/fr/1001-2-1/", umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain2.com"), false)); - } - - private static void CheckRoute(IDictionary routes, IDictionary ids, int id, string route) - { - Assert.IsTrue(routes.ContainsKey(id)); - Assert.AreEqual(route, routes[id]); - Assert.IsFalse(ids.ContainsKey(route)); - } - - [Test] - public void Get_Nice_Url_Relative_Or_Absolute() - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - var requestMock = Mock.Get(settings.RequestHandler); - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains4(); + + string ignore; + ignore = umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain2.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain2.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain2.com"), false); + ignore = umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain2.com"), false); + + var cache = umbracoContext.ContentCache as PublishedContentCache; + if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); + var cachedRoutes = cache.RoutesCache.GetCachedRoutes(); + Assert.AreEqual(7, cachedRoutes.Count); + + var cachedIds = cache.RoutesCache.GetCachedIds(); + Assert.AreEqual(0, cachedIds.Count); + + CheckRoute(cachedRoutes, cachedIds, 1001, "1001/"); + CheckRoute(cachedRoutes, cachedIds, 10011, "10011/"); + CheckRoute(cachedRoutes, cachedIds, 100111, "10011/1001-1-1"); + CheckRoute(cachedRoutes, cachedIds, 10012, "10012/"); + CheckRoute(cachedRoutes, cachedIds, 100121, "10012/1001-2-1"); + CheckRoute(cachedRoutes, cachedIds, 10013, "1001/1001-3"); + CheckRoute(cachedRoutes, cachedIds, 1002, "/1002"); + + // use the cache + Assert.AreEqual("/", umbracoContext.UrlProvider.GetUrl(1001, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/en/", umbracoContext.UrlProvider.GetUrl(10011, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/fr/", umbracoContext.UrlProvider.GetUrl(10012, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/fr/1001-2-1/", umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/1001-3/", umbracoContext.UrlProvider.GetUrl(10013, new Uri("http://domain1.com"), false)); + Assert.AreEqual("/1002/", umbracoContext.UrlProvider.GetUrl(1002, new Uri("http://domain1.com"), false)); + + Assert.AreEqual("http://domain1.com/fr/1001-2-1/", umbracoContext.UrlProvider.GetUrl(100121, new Uri("http://domain2.com"), false)); + } + + private static void CheckRoute(IDictionary routes, IDictionary ids, int id, string route) + { + Assert.IsTrue(routes.ContainsKey(id)); + Assert.AreEqual(route, routes[id]); + Assert.IsFalse(ids.ContainsKey(route)); + } + + [Test] + public void Get_Nice_Url_Relative_Or_Absolute() + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + var requestMock = Mock.Get(settings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains4(); - - Assert.AreEqual("/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); - Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); - - Assert.AreEqual("http://domain1.com/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); - Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); - - requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); - umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; - - Assert.AreEqual("http://domain1.com/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); - Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); - } - - [Test] - public void Get_Nice_Url_Alternate() - { - var settings = SettingsForTests.GenerateMockUmbracoSettings(); - - var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container - globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); - globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains + + var umbracoContext = GetUmbracoContext("http://domain1.com/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains4(); + + Assert.AreEqual("/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); + Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(true); + + Assert.AreEqual("http://domain1.com/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); + Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); + + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + umbracoContext.UrlProvider.Mode = UrlProviderMode.Absolute; + + Assert.AreEqual("http://domain1.com/en/1001-1-1/", umbracoContext.UrlProvider.GetUrl(100111)); + Assert.AreEqual("http://domain3.com/en/1003-1-1/", umbracoContext.UrlProvider.GetUrl(100311)); + } + + [Test] + public void Get_Nice_Url_Alternate() + { + var settings = SettingsForTests.GenerateMockUmbracoSettings(); + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); // ignored w/domains SettingsForTests.ConfigureSettings(globalSettings.Object); - - var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] - { - new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - - SetDomains5(); - - var url = umbracoContext.UrlProvider.GetUrl(100111, true); - Assert.AreEqual("http://domain1.com/en/1001-1-1/", url); - - var result = umbracoContext.UrlProvider.GetOtherUrls(100111).ToArray(); - - Assert.AreEqual(2, result.Count()); - Assert.IsTrue(result.Contains("http://domain1a.com/en/1001-1-1/")); - Assert.IsTrue(result.Contains("http://domain1b.com/en/1001-1-1/")); - } - } -} + + var umbracoContext = GetUmbracoContext("http://domain1.com/en/test", 1111, umbracoSettings: settings, urlProviders: new[] + { + new DefaultUrlProvider(settings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, globalSettings:globalSettings.Object); + + SetDomains5(); + + var url = umbracoContext.UrlProvider.GetUrl(100111, true); + Assert.AreEqual("http://domain1.com/en/1001-1-1/", url); + + var result = umbracoContext.UrlProvider.GetOtherUrls(100111).ToArray(); + + Assert.AreEqual(2, result.Count()); + Assert.IsTrue(result.Contains("http://domain1a.com/en/1001-1-1/")); + Assert.IsTrue(result.Contains("http://domain1b.com/en/1001-1-1/")); + } + } +} diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 8ae1e4dede..863b875394 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -146,7 +146,12 @@ - + + + + + + @@ -425,9 +430,7 @@ - - @@ -451,10 +454,7 @@ - - - diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index 3612ee8847..ffaffa05f4 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -343,7 +343,7 @@ namespace Umbraco.Web.Editors /// public HttpResponseMessage GetNiceUrl(int id) { - var url = Umbraco.NiceUrl(id); + var url = Umbraco.Url(id); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(url, Encoding.UTF8, "application/json"); return response; diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksLegacyValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksLegacyValueConverter.cs index ca6f54fcd8..1e8197ec7a 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksLegacyValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/RelatedLinksLegacyValueConverter.cs @@ -73,7 +73,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters { var content = helper.PublishedContent(udiAttempt.Result); if (content == null) break; - a["link"] = helper.NiceUrl(content.Id); + a["link"] = helper.Url(content.Id); } break; } diff --git a/src/Umbraco.Web/RelatedLinksTypeConverter.cs b/src/Umbraco.Web/RelatedLinksTypeConverter.cs index e06b5b5c62..9ed9398d2e 100644 --- a/src/Umbraco.Web/RelatedLinksTypeConverter.cs +++ b/src/Umbraco.Web/RelatedLinksTypeConverter.cs @@ -67,7 +67,7 @@ namespace Umbraco.Web if (type == "internal") { var linkId = a.Value("link"); - var link = umbracoHelper.NiceUrl(linkId); + var link = umbracoHelper.Url(linkId); a["link"] = link; } } diff --git a/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs b/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs index 66a7115dc7..262c2c80e3 100644 --- a/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs +++ b/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs @@ -329,7 +329,7 @@ namespace Umbraco.Web.Search var intId = m.Id.TryConvertTo(); if (intId.Success) { - m.AdditionalData["Url"] = umbracoHelper.NiceUrl(intId.Result); + m.AdditionalData["Url"] = umbracoHelper.Url(intId.Result); } } return mapped; diff --git a/src/Umbraco.Web/UmbracoHelper.cs b/src/Umbraco.Web/UmbracoHelper.cs index 2386e4abef..fca5c200b7 100644 --- a/src/Umbraco.Web/UmbracoHelper.cs +++ b/src/Umbraco.Web/UmbracoHelper.cs @@ -331,19 +331,9 @@ namespace Umbraco.Web #endregion - #region NiceUrls - - /// - /// Returns a string with a friendly url from a node. - /// IE.: Instead of having /482 (id) as an url, you can have - /// /screenshots/developer/macros (spoken url) - /// - /// Identifier for the node that should be returned - /// String with a friendly url from a node - public string NiceUrl(int nodeId) - { - return Url(nodeId); - } + #region Urls + + //TODO: We will need an optional culture parameter, by default it will be the current thread culture /// /// Gets the url of a content identified by its identifier. @@ -365,16 +355,8 @@ namespace Umbraco.Web { return UrlProvider.GetUrl(contentId, mode); } - - /// - /// This method will always add the domain to the path if the hostnames are set up correctly. - /// - /// Identifier for the node that should be returned - /// String with a friendly url with full domain from a node - public string NiceUrlWithDomain(int nodeId) - { - return UrlAbsolute(nodeId); - } + + //TODO: We will need an optional culture parameter, by default it will be the current thread culture /// /// Gets the absolute url of a content identified by its identifier. diff --git a/src/Umbraco.Web/umbraco.presentation/library.cs b/src/Umbraco.Web/umbraco.presentation/library.cs index d85fce59cd..5a2353cdde 100644 --- a/src/Umbraco.Web/umbraco.presentation/library.cs +++ b/src/Umbraco.Web/umbraco.presentation/library.cs @@ -127,7 +127,7 @@ namespace umbraco /// String with a friendly url from a node public static string NiceUrl(int nodeID) { - return GetUmbracoHelper().NiceUrl(nodeID); + return GetUmbracoHelper().Url(nodeID); } /// @@ -137,7 +137,7 @@ namespace umbraco /// String with a friendly url with full domain from a node public static string NiceUrlWithDomain(int nodeId) { - return GetUmbracoHelper().NiceUrlWithDomain(nodeId); + return GetUmbracoHelper().UrlAbsolute(nodeId); } /// From ad6a7456811f772f92bc53d6a474306c7942d270 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 11:08:20 +1000 Subject: [PATCH 33/58] Changes CultureInfo to string where required, fixes tests --- .../PublishedContentTestElements.cs | 8 ++++---- .../TestControllerActivatorBase.cs | 2 +- .../Testing/TestingTests/MockTests.cs | 2 +- .../Web/TemplateUtilitiesTests.cs | 4 ++-- .../PublishedCache/IPublishedContentCache.cs | 8 ++++---- .../PublishedCache/NuCache/CacheKeys.cs | 8 ++++---- .../PublishedCache/NuCache/ContentCache.cs | 14 +++++++------- .../XmlPublishedCache/PublishedContentCache.cs | 8 ++++---- src/Umbraco.Web/PublishedContentExtensions.cs | 4 ++-- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 2 +- .../Routing/ContentFinderByLegacy404.cs | 2 +- src/Umbraco.Web/Routing/ContentFinderByUrl.cs | 4 +++- .../Routing/CustomRouteUrlProvider.cs | 2 +- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 4 ++-- src/Umbraco.Web/Routing/IUrlProvider.cs | 2 +- src/Umbraco.Web/Routing/UrlProvider.cs | 18 +++++++++--------- 16 files changed, 47 insertions(+), 45 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs index 9e416015b4..6e5953544f 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs @@ -59,22 +59,22 @@ namespace Umbraco.Tests.PublishedContent _content.Clear(); } - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) { throw new NotImplementedException(); } - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) { throw new NotImplementedException(); } - public string GetRouteById(bool preview, int contentId, CultureInfo culture = null) + public string GetRouteById(bool preview, int contentId, string culture = null) { throw new NotImplementedException(); } - public string GetRouteById(int contentId, CultureInfo culture = null) + public string GetRouteById(int contentId, string culture = null) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 05e9a39551..96404b1e59 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -153,7 +153,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting true); //replace it var urlHelper = new Mock(); - urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlHelper.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var membershipHelper = new MembershipHelper(umbCtx, Mock.Of(), Mock.Of()); diff --git a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs index 7575bb3d1f..59bc24ed10 100644 --- a/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs +++ b/src/Umbraco.Tests/Testing/TestingTests/MockTests.cs @@ -74,7 +74,7 @@ namespace Umbraco.Tests.Testing.TestingTests var umbracoContext = TestObjects.GetUmbracoContextMock(); var urlProviderMock = new Mock(); - urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + urlProviderMock.Setup(provider => provider.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns("/hello/world/1234"); var urlProvider = urlProviderMock.Object; diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index ed06948e3f..d35b4e5823 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -73,8 +73,8 @@ namespace Umbraco.Tests.Web //setup a mock url provider which we'll use fo rtesting var testUrlProvider = new Mock(); - testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode) => + testUrlProvider.Setup(x => x.GetUrl(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((UmbracoContext umbCtx, int id, Uri url, UrlProviderMode mode, string culture) => { return "/my-test-url"; }); diff --git a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs index 2d7c93d93e..3254207280 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedContentCache.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.PublishedCache /// If is null then the settings value is used. /// The value of overrides defaults. /// - IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null); + IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null); /// /// Gets content identified by a route. @@ -31,7 +31,7 @@ namespace Umbraco.Web.PublishedCache /// If is null then the settings value is used. /// Considers published or unpublished content depending on defaults. /// - IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null); + IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null); /// /// Gets the route for a content identified by its unique identifier. @@ -40,7 +40,7 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// The value of overrides defaults. - string GetRouteById(bool preview, int contentId, CultureInfo culture = null); + string GetRouteById(bool preview, int contentId, string culture = null); /// /// Gets the route for a content identified by its unique identifier. @@ -48,6 +48,6 @@ namespace Umbraco.Web.PublishedCache /// The content unique identifier. /// The route. /// Considers published or unpublished content depending on defaults. - string GetRouteById(int contentId, CultureInfo culture = null); + string GetRouteById(int contentId, string culture = null); } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs index e1b86b9ad6..5bdee5a416 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/CacheKeys.cs @@ -13,9 +13,9 @@ namespace Umbraco.Web.PublishedCache.NuCache } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static string LangId(CultureInfo culture) + private static string LangId(string culture) { - return culture != null ? ("-L:" + culture.Name) : string.Empty; + return culture != null ? ("-L:" + culture) : string.Empty; } public static string PublishedContentChildren(Guid contentUid, bool previewing) @@ -57,12 +57,12 @@ namespace Umbraco.Web.PublishedCache.NuCache // a valid ID in the database at that point, whereas content and properties // may be virtual (and not in umbracoNode). - public static string ContentCacheRouteByContent(int id, bool previewing, CultureInfo culture) + public static string ContentCacheRouteByContent(int id, bool previewing, string culture) { return "NuCache.ContentCache.RouteByContent[" + DraftOrPub(previewing) + id + LangId(culture) + "]"; } - public static string ContentCacheContentByRoute(string route, bool previewing, CultureInfo culture) + public static string ContentCacheContentByRoute(string route, bool previewing, string culture) { return "NuCache.ContentCache.ContentByRoute[" + DraftOrPub(previewing) + route + LangId(culture) + "]"; } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index c6d380ca55..fc95557dd1 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -55,12 +55,12 @@ namespace Umbraco.Web.PublishedCache.NuCache // at the moment we try our best to be backward compatible, but really, // should get rid of hideTopLevelNode and other oddities entirely, eventually - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) { return GetByRoute(PreviewDefault, route, hideTopLevelNode, culture); } - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) { if (route == null) throw new ArgumentNullException(nameof(route)); @@ -69,7 +69,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return cache.GetCacheItem(key, () => GetByRouteInternal(preview, route, hideTopLevelNode, culture)); } - private IPublishedContent GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode, CultureInfo culture) + private IPublishedContent GetByRouteInternal(bool preview, string route, bool? hideTopLevelNode, string culture) { hideTopLevelNode = hideTopLevelNode ?? HideTopLevelNodeFromPath; // default = settings @@ -120,19 +120,19 @@ namespace Umbraco.Web.PublishedCache.NuCache return content; } - public string GetRouteById(int contentId, CultureInfo culture = null) + public string GetRouteById(int contentId, string culture = null) { return GetRouteById(PreviewDefault, contentId, culture); } - public string GetRouteById(bool preview, int contentId, CultureInfo culture = null) + public string GetRouteById(bool preview, int contentId, string culture = null) { var cache = (preview == false || PublishedSnapshotService.FullCacheWhenPreviewing) ? _elementsCache : _snapshotCache; var key = CacheKeys.ContentCacheRouteByContent(contentId, preview, culture); return cache.GetCacheItem(key, () => GetRouteByIdInternal(preview, contentId, null, culture)); } - private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, CultureInfo culture) + private string GetRouteByIdInternal(bool preview, int contentId, bool? hideTopLevelNode, string culture) { var node = GetById(preview, contentId); if (node == null) @@ -168,7 +168,7 @@ namespace Umbraco.Web.PublishedCache.NuCache return route; } - private IPublishedContent FollowRoute(IPublishedContent content, IReadOnlyList parts, int start, CultureInfo culture) + private IPublishedContent FollowRoute(IPublishedContent content, IReadOnlyList parts, int start, string culture) { var i = start; while (content != null && i < parts.Count) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs index 01ab37554e..57d9e0a980 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedContentCache.cs @@ -64,7 +64,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache #region Routes - public virtual IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public virtual IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) { if (route == null) throw new ArgumentNullException(nameof(route)); @@ -108,12 +108,12 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _routesCache.Store(content.Id, route, true); // trusted route } - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, CultureInfo culture = null) + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) { return GetByRoute(PreviewDefault, route, hideTopLevelNode); } - public virtual string GetRouteById(bool preview, int contentId, CultureInfo culture = null) + public virtual string GetRouteById(bool preview, int contentId, string culture = null) { // try to get from cache if not previewing var route = preview || _routesCache == null ? null : _routesCache.GetRoute(contentId); @@ -138,7 +138,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache return route; } - public string GetRouteById(int contentId, CultureInfo culture = null) + public string GetRouteById(int contentId, string culture = null) { return GetRouteById(PreviewDefault, contentId, culture); } diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index e68365416d..d11a168b88 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -1253,11 +1253,11 @@ namespace Umbraco.Web /// /// /// - public static string GetUrlName(this IPublishedContent content, ILocalizationService localizationService, CultureInfo culture = null) + public static string GetUrlName(this IPublishedContent content, ILocalizationService localizationService, string culture = null) { if (content.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) { - var cultureCode = culture != null ? culture.Name : localizationService.GetDefaultVariantLanguage()?.IsoCode; + var cultureCode = culture ?? localizationService.GetDefaultVariantLanguage()?.IsoCode; if (cultureCode != null && content.CultureNames.TryGetValue(cultureCode, out var cultureName)) { return cultureName.UrlName; diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 67e2d56fcb..5e3f8ea919 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it should return null. /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null) { return null; // we have nothing to say } diff --git a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs index 090b7d421d..6cc3b74972 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.Routing while (pos > 1) { route = route.Substring(0, pos); - node = frequest.UmbracoContext.ContentCache.GetByRoute(route, culture: frequest.Culture); + node = frequest.UmbracoContext.ContentCache.GetByRoute(route, culture: frequest?.Culture?.Name); if (node != null) break; pos = route.LastIndexOf('/'); } diff --git a/src/Umbraco.Web/Routing/ContentFinderByUrl.cs b/src/Umbraco.Web/Routing/ContentFinderByUrl.cs index 66b8024c6b..042ca5882f 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByUrl.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByUrl.cs @@ -44,9 +44,11 @@ namespace Umbraco.Web.Routing /// The document node, or null. protected IPublishedContent FindContent(PublishedRequest docreq, string route) { + if (docreq == null) throw new System.ArgumentNullException(nameof(docreq)); + Logger.Debug(() => $"Test route \"{route}\""); - var node = docreq.UmbracoContext.ContentCache.GetByRoute(route, culture: docreq.Culture); + var node = docreq.UmbracoContext.ContentCache.GetByRoute(route, culture: docreq.Culture?.Name); if (node != null) { docreq.PublishedContent = node; diff --git a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs index 7a3d8fffed..926db253c8 100644 --- a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs +++ b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.Routing /// /// /// - public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) + public string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null) { if (umbracoContext == null) return null; if (umbracoContext.PublishedRequest == null) return null; diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index c451d91565..788a7a809b 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -43,7 +43,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) + public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null) { if (!current.IsAbsoluteUri) throw new ArgumentException("Current url must be absolute.", "current"); @@ -116,7 +116,7 @@ namespace Umbraco.Web.Routing foreach (var d in domainUris) { //although we are passing in culture here, if any node in this path is invariant, it ignores the culture anyways so this is ok - var route = umbracoContext.ContentCache.GetRouteById(id, d.Culture); + var route = umbracoContext.ContentCache.GetRouteById(id, d?.Culture?.Name); if (route == null) continue; //need to strip off the leading ID for the route diff --git a/src/Umbraco.Web/Routing/IUrlProvider.cs b/src/Umbraco.Web/Routing/IUrlProvider.cs index 086f9c4767..e4c6e23022 100644 --- a/src/Umbraco.Web/Routing/IUrlProvider.cs +++ b/src/Umbraco.Web/Routing/IUrlProvider.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it should return null. /// - string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, CultureInfo culture = null); + string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null); /// /// Gets the other urls of a published content. diff --git a/src/Umbraco.Web/Routing/UrlProvider.cs b/src/Umbraco.Web/Routing/UrlProvider.cs index 3fb0d6fd1d..422fb4d4e7 100644 --- a/src/Umbraco.Web/Routing/UrlProvider.cs +++ b/src/Umbraco.Web/Routing/UrlProvider.cs @@ -77,7 +77,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on Mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, CultureInfo culture = null) + public string GetUrl(Guid id, string culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, culture); @@ -94,7 +94,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, bool absolute, CultureInfo culture = null) + public string GetUrl(Guid id, bool absolute, string culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, absolute, culture); @@ -112,7 +112,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, Uri current, bool absolute, CultureInfo culture = null) + public string GetUrl(Guid id, Uri current, bool absolute, string culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, current, absolute, culture); @@ -128,7 +128,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(Guid id, UrlProviderMode mode, CultureInfo culture = null) + public string GetUrl(Guid id, UrlProviderMode mode, string culture = null) { var intId = _entityService.GetId(id, UmbracoObjectTypes.Document); return GetUrl(intId.Success ? intId.Result : -1, mode, culture); @@ -143,7 +143,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on Mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, CultureInfo culture = null) + public string GetUrl(int id, string culture = null) { return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, Mode, culture); } @@ -159,7 +159,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, bool absolute, CultureInfo culture = null) + public string GetUrl(int id, bool absolute, string culture = null) { var mode = absolute ? UrlProviderMode.Absolute : Mode; return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode, culture); @@ -177,7 +177,7 @@ namespace Umbraco.Web.Routing /// absolute is true, in which case the url is always absolute. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, Uri current, bool absolute, CultureInfo culture = null) + public string GetUrl(int id, Uri current, bool absolute, string culture = null) { var mode = absolute ? UrlProviderMode.Absolute : Mode; return GetUrl(id, current, mode, culture); @@ -193,7 +193,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on the current url. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, UrlProviderMode mode, CultureInfo culture = null) + public string GetUrl(int id, UrlProviderMode mode, string culture = null) { return GetUrl(id, _umbracoContext.CleanedUmbracoUrl, mode, culture); } @@ -209,7 +209,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, Uri current, UrlProviderMode mode, CultureInfo culture = null) + public string GetUrl(int id, Uri current, UrlProviderMode mode, string culture = null) { var url = _urlProviders.Select(provider => provider.GetUrl(_umbracoContext, id, current, mode, culture)) .FirstOrDefault(u => u != null); From 73567ffdce3ebe2c01db50c0cbf13de5e20021e0 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 11:38:50 +1000 Subject: [PATCH 34/58] Fixes IPublishedShapshot and friends --- .../PublishedContentCacheTests.cs | 2 +- .../Published/ConvertersTests.cs | 4 +- .../Published/NestedContentTests.cs | 2 +- .../Published/PropertyCacheLevelTests.cs | 2 +- .../PublishedContentMoreTests.cs | 4 +- ...tElements.cs => SolidPublishedSnapshot.cs} | 690 +++++++++--------- src/Umbraco.Tests/Routing/RoutesCacheTests.cs | 2 +- src/Umbraco.Tests/Routing/UrlProviderTests.cs | 7 +- .../Routing/UrlsProviderWithDomainsTests.cs | 14 +- .../TestControllerActivatorBase.cs | 2 +- .../Stubs/TestPublishedSnapshotAccessor.cs | 2 +- .../TestHelpers/TestObjects-Mocks.cs | 2 +- .../TestHelpers/TestWithDatabaseBase.cs | 19 +- src/Umbraco.Tests/Umbraco.Tests.csproj | 2 +- .../Web/Mvc/SurfaceControllerTests.cs | 2 +- .../Web/Mvc/UmbracoViewPageTests.cs | 2 +- src/Umbraco.Web/Composing/Current.cs | 2 +- ...ishedShapshot.cs => IPublishedSnapshot.cs} | 2 +- .../IPublishedSnapshotAccessor.cs | 4 +- .../IPublishedSnapshotService.cs | 4 +- .../PublishedCache/NuCache/Property.cs | 6 +- .../NuCache/PublishedContent.cs | 8 +- ...lishedShapshot.cs => PublishedSnapshot.cs} | 12 +- .../NuCache/PublishedSnapshotService.cs | 18 +- .../PublishedSnapshotServiceBase.cs | 4 +- ...UmbracoContextPublishedSnapshotAccessor.cs | 4 +- ...lishedShapshot.cs => PublishedSnapshot.cs} | 6 +- .../PublishedSnapshotService.cs | 4 +- .../XmlPublishedCache/XmlStore.cs | 2 +- .../Routing/ContentFinderByLegacy404.cs | 2 +- src/Umbraco.Web/Routing/PublishedRouter.cs | 8 +- src/Umbraco.Web/Security/MembershipHelper.cs | 2 +- src/Umbraco.Web/Umbraco.Web.csproj | 6 +- src/Umbraco.Web/UmbracoContext.cs | 14 +- 34 files changed, 435 insertions(+), 431 deletions(-) rename src/Umbraco.Tests/PublishedContent/{PublishedContentTestElements.cs => SolidPublishedSnapshot.cs} (96%) rename src/Umbraco.Web/PublishedCache/{IPublishedShapshot.cs => IPublishedSnapshot.cs} (97%) rename src/Umbraco.Web/PublishedCache/NuCache/{PublishedShapshot.cs => PublishedSnapshot.cs} (88%) rename src/Umbraco.Web/PublishedCache/XmlPublishedCache/{PublishedShapshot.cs => PublishedSnapshot.cs} (92%) diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 304c20c78f..234b31d5a0 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 var xmlStore = new XmlStore(() => _xml, null, null, null); var cacheProvider = new StaticCacheProvider(); var domainCache = new DomainCache(ServiceContext.DomainService, ServiceContext.LocalizationService); - var publishedShapshot = new Umbraco.Web.PublishedCache.XmlPublishedCache.PublishedShapshot( + 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), new PublishedMemberCache(null, cacheProvider, Current.Services.MemberService, ContentTypesCache), diff --git a/src/Umbraco.Tests/Published/ConvertersTests.cs b/src/Umbraco.Tests/Published/ConvertersTests.cs index bc17a7fb03..0c47a551bc 100644 --- a/src/Umbraco.Tests/Published/ConvertersTests.cs +++ b/src/Umbraco.Tests/Published/ConvertersTests.cs @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Published var cacheMock = new Mock(); var cacheContent = new Dictionary(); cacheMock.Setup(x => x.GetById(It.IsAny())).Returns(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null); - var publishedSnapshotMock = new Mock(); + var publishedSnapshotMock = new Mock(); publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object); var publishedSnapshotAccessorMock = new Mock(); publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object); @@ -164,7 +164,7 @@ namespace Umbraco.Tests.Published var cacheMock = new Mock(); var cacheContent = new Dictionary(); cacheMock.Setup(x => x.GetById(It.IsAny())).Returns(id => cacheContent.TryGetValue(id, out IPublishedContent content) ? content : null); - var publishedSnapshotMock = new Mock(); + var publishedSnapshotMock = new Mock(); publishedSnapshotMock.Setup(x => x.Content).Returns(cacheMock.Object); var publishedSnapshotAccessorMock = new Mock(); publishedSnapshotAccessorMock.Setup(x => x.PublishedSnapshot).Returns(publishedSnapshotMock.Object); diff --git a/src/Umbraco.Tests/Published/NestedContentTests.cs b/src/Umbraco.Tests/Published/NestedContentTests.cs index 28e103ad7c..c806930704 100644 --- a/src/Umbraco.Tests/Published/NestedContentTests.cs +++ b/src/Umbraco.Tests/Published/NestedContentTests.cs @@ -104,7 +104,7 @@ namespace Umbraco.Tests.Published }); var contentCache = new Mock(); - var publishedSnapshot = new Mock(); + var publishedSnapshot = new Mock(); // mocked published snapshot returns a content cache publishedSnapshot diff --git a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs index 49d1707567..950d81ee36 100644 --- a/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs +++ b/src/Umbraco.Tests/Published/PropertyCacheLevelTests.cs @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Published var elementsCache = new DictionaryCacheProvider(); var snapshotCache = new DictionaryCacheProvider(); - var publishedSnapshot = new Mock(); + var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.SnapshotCache).Returns(snapshotCache); publishedSnapshot.Setup(x => x.ElementsCache).Returns(elementsCache); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs index 3e715792cb..61c37d6a51 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentMoreTests.cs @@ -197,13 +197,13 @@ namespace Umbraco.Tests.PublishedContent Assert.AreEqual(2, result[1].Id); } - private static SolidPublishedShapshot CreatePublishedSnapshot() + private static SolidPublishedSnapshot CreatePublishedSnapshot() { var dataTypeService = new TestObjects.TestDataTypeService( new DataType(new VoidEditor(Mock.Of())) { Id = 1 }); var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); - var caches = new SolidPublishedShapshot(); + var caches = new SolidPublishedSnapshot(); var cache = caches.InnerContentCache; var props = new[] diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs similarity index 96% rename from src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs rename to src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs index 6e5953544f..4b7a131bd0 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTestElements.cs +++ b/src/Umbraco.Tests/PublishedContent/SolidPublishedSnapshot.cs @@ -1,347 +1,347 @@ -using System; -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Globalization; -using System.Linq; -using Moq; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Models; -using Umbraco.Core.Models.PublishedContent; -using Umbraco.Core.PropertyEditors; -using Umbraco.Tests.TestHelpers; -using Umbraco.Web; -using Umbraco.Web.PublishedCache; - -namespace Umbraco.Tests.PublishedContent -{ - class SolidPublishedShapshot : IPublishedShapshot - { - public readonly SolidPublishedContentCache InnerContentCache = new SolidPublishedContentCache(); - public readonly SolidPublishedContentCache InnerMediaCache = new SolidPublishedContentCache(); - - public IPublishedContentCache Content => InnerContentCache; - - public IPublishedMediaCache Media => InnerMediaCache; - - public IPublishedMemberCache Members => null; - - public IDomainCache Domains => null; - - public IDisposable ForcedPreview(bool forcedPreview, Action callback = null) - { - throw new NotImplementedException(); - } - - public void Resync() - { } - - public ICacheProvider SnapshotCache => null; - - public ICacheProvider ElementsCache => null; - } - - class SolidPublishedContentCache : PublishedCacheBase, IPublishedContentCache, IPublishedMediaCache - { - private readonly Dictionary _content = new Dictionary(); - - public SolidPublishedContentCache() - : base(false) - { } - - public void Add(SolidPublishedContent content) - { - _content[content.Id] = content.CreateModel(); - } - - public void Clear() - { - _content.Clear(); - } - - public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) - { - throw new NotImplementedException(); - } - - public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) - { - throw new NotImplementedException(); - } - - public string GetRouteById(bool preview, int contentId, string culture = null) - { - throw new NotImplementedException(); - } - - public string GetRouteById(int contentId, string culture = null) - { - throw new NotImplementedException(); - } - - public override IPublishedContent GetById(bool preview, int contentId) - { - return _content.ContainsKey(contentId) ? _content[contentId] : null; - } - - public override IPublishedContent GetById(bool preview, Guid contentId) - { - throw new NotImplementedException(); - } - - public override bool HasById(bool preview, int contentId) - { - return _content.ContainsKey(contentId); - } - - public override IEnumerable GetAtRoot(bool preview) - { - return _content.Values.Where(x => x.Parent == null); - } - - public override IPublishedContent GetSingleByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } - - public override IPublishedContent GetSingleByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } - - public override IEnumerable GetByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } - - public override IEnumerable GetByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) - { - throw new NotImplementedException(); - } - - public override System.Xml.XPath.XPathNavigator CreateNavigator(bool preview) - { - throw new NotImplementedException(); - } - - public override System.Xml.XPath.XPathNavigator CreateNodeNavigator(int id, bool preview) - { - throw new NotImplementedException(); - } - - public override bool HasContent(bool preview) - { - return _content.Count > 0; - } - - public override PublishedContentType GetContentType(int id) - { - throw new NotImplementedException(); - } - - public override PublishedContentType GetContentType(string alias) - { - throw new NotImplementedException(); - } - - public override IEnumerable GetByContentType(PublishedContentType contentType) - { - throw new NotImplementedException(); - } - } - - class SolidPublishedContent : IPublishedContent - { - #region Constructor - - public SolidPublishedContent(PublishedContentType contentType) - { - // initialize boring stuff - TemplateId = 0; - WriterName = CreatorName = string.Empty; - WriterId = CreatorId = 0; - CreateDate = UpdateDate = DateTime.Now; - Version = Guid.Empty; - IsDraft = false; - - ContentType = contentType; - DocumentTypeAlias = contentType.Alias; - DocumentTypeId = contentType.Id; - } - - #endregion - - #region Content - - public int Id { get; set; } - public Guid Key { get; set; } - public int TemplateId { get; set; } - public int SortOrder { get; set; } +using System.Linq; +using Moq; +using Umbraco.Core; +using Umbraco.Core.Cache; +using Umbraco.Core.Logging; +using Umbraco.Core.Models; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core.PropertyEditors; +using Umbraco.Tests.TestHelpers; +using Umbraco.Web; +using Umbraco.Web.PublishedCache; + +namespace Umbraco.Tests.PublishedContent +{ + class SolidPublishedSnapshot : IPublishedSnapshot + { + public readonly SolidPublishedContentCache InnerContentCache = new SolidPublishedContentCache(); + public readonly SolidPublishedContentCache InnerMediaCache = new SolidPublishedContentCache(); + + public IPublishedContentCache Content => InnerContentCache; + + public IPublishedMediaCache Media => InnerMediaCache; + + public IPublishedMemberCache Members => null; + + public IDomainCache Domains => null; + + public IDisposable ForcedPreview(bool forcedPreview, Action callback = null) + { + throw new NotImplementedException(); + } + + public void Resync() + { } + + public ICacheProvider SnapshotCache => null; + + public ICacheProvider ElementsCache => null; + } + + class SolidPublishedContentCache : PublishedCacheBase, IPublishedContentCache, IPublishedMediaCache + { + private readonly Dictionary _content = new Dictionary(); + + public SolidPublishedContentCache() + : base(false) + { } + + public void Add(SolidPublishedContent content) + { + _content[content.Id] = content.CreateModel(); + } + + public void Clear() + { + _content.Clear(); + } + + public IPublishedContent GetByRoute(bool preview, string route, bool? hideTopLevelNode = null, string culture = null) + { + throw new NotImplementedException(); + } + + public IPublishedContent GetByRoute(string route, bool? hideTopLevelNode = null, string culture = null) + { + throw new NotImplementedException(); + } + + public string GetRouteById(bool preview, int contentId, string culture = null) + { + throw new NotImplementedException(); + } + + public string GetRouteById(int contentId, string culture = null) + { + throw new NotImplementedException(); + } + + public override IPublishedContent GetById(bool preview, int contentId) + { + return _content.ContainsKey(contentId) ? _content[contentId] : null; + } + + public override IPublishedContent GetById(bool preview, Guid contentId) + { + throw new NotImplementedException(); + } + + public override bool HasById(bool preview, int contentId) + { + return _content.ContainsKey(contentId); + } + + public override IEnumerable GetAtRoot(bool preview) + { + return _content.Values.Where(x => x.Parent == null); + } + + public override IPublishedContent GetSingleByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) + { + throw new NotImplementedException(); + } + + public override IPublishedContent GetSingleByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) + { + throw new NotImplementedException(); + } + + public override IEnumerable GetByXPath(bool preview, string xpath, Core.Xml.XPathVariable[] vars) + { + throw new NotImplementedException(); + } + + public override IEnumerable GetByXPath(bool preview, System.Xml.XPath.XPathExpression xpath, Core.Xml.XPathVariable[] vars) + { + throw new NotImplementedException(); + } + + public override System.Xml.XPath.XPathNavigator CreateNavigator(bool preview) + { + throw new NotImplementedException(); + } + + public override System.Xml.XPath.XPathNavigator CreateNodeNavigator(int id, bool preview) + { + throw new NotImplementedException(); + } + + public override bool HasContent(bool preview) + { + return _content.Count > 0; + } + + public override PublishedContentType GetContentType(int id) + { + throw new NotImplementedException(); + } + + public override PublishedContentType GetContentType(string alias) + { + throw new NotImplementedException(); + } + + public override IEnumerable GetByContentType(PublishedContentType contentType) + { + throw new NotImplementedException(); + } + } + + class SolidPublishedContent : IPublishedContent + { + #region Constructor + + public SolidPublishedContent(PublishedContentType contentType) + { + // initialize boring stuff + TemplateId = 0; + WriterName = CreatorName = string.Empty; + WriterId = CreatorId = 0; + CreateDate = UpdateDate = DateTime.Now; + Version = Guid.Empty; + IsDraft = false; + + ContentType = contentType; + DocumentTypeAlias = contentType.Alias; + DocumentTypeId = contentType.Id; + } + + #endregion + + #region Content + + public int Id { get; set; } + public Guid Key { get; set; } + public int TemplateId { get; set; } + public int SortOrder { get; set; } public string Name { get; set; } - public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); - public string UrlName { get; set; } - public string DocumentTypeAlias { get; private set; } - public int DocumentTypeId { get; private set; } - public string WriterName { get; set; } - public string CreatorName { get; set; } - public int WriterId { get; set; } - public int CreatorId { get; set; } - public string Path { get; set; } - public DateTime CreateDate { get; set; } - public DateTime UpdateDate { get; set; } - public Guid Version { get; set; } - public int Level { get; set; } - public string Url { get; set; } - - public PublishedItemType ItemType { get { return PublishedItemType.Content; } } - public bool IsDraft { get; set; } - - #endregion - - #region Tree - - public int ParentId { get; set; } - public IEnumerable ChildIds { get; set; } - - public IPublishedContent Parent { get; set; } - public IEnumerable Children { get; set; } - - #endregion - - #region ContentType - - public PublishedContentType ContentType { get; private set; } - - #endregion - - #region Properties - - public IEnumerable Properties { get; set; } - - public IPublishedProperty GetProperty(string alias) - { - return Properties.FirstOrDefault(p => p.Alias.InvariantEquals(alias)); - } - - public IPublishedProperty GetProperty(string alias, bool recurse) - { - var property = GetProperty(alias); - if (recurse == false) return property; - - IPublishedContent content = this; - while (content != null && (property == null || property.HasValue() == false)) - { - content = content.Parent; - property = content == null ? null : content.GetProperty(alias); - } - - return property; - } - - public object this[string alias] - { - get - { - var property = GetProperty(alias); - return property == null || property.HasValue() == false ? null : property.GetValue(); - } - } - - #endregion - } - - class SolidPublishedProperty : IPublishedProperty - { - public string Alias { get; set; } - public object SolidSourceValue { get; set; } - public object SolidValue { get; set; } - public bool SolidHasValue { get; set; } - public object SolidXPathValue { get; set; } - - public object GetSourceValue(string culture = null, string segment = null) => SolidSourceValue; - public object GetValue(string culture = null, string segment = null) => SolidValue; - public object GetXPathValue(string culture = null, string segment = null) => SolidXPathValue; - public bool HasValue(string culture = null, string segment = null) => SolidHasValue; - } - - [PublishedModel("ContentType2")] - internal class ContentType2 : PublishedContentModel - { - #region Plumbing - - public ContentType2(IPublishedContent content) - : base(content) - { } - - #endregion - - public int Prop1 => this.Value("prop1"); - } - - [PublishedModel("ContentType2Sub")] - internal class ContentType2Sub : ContentType2 - { - #region Plumbing - - public ContentType2Sub(IPublishedContent content) - : base(content) - { } - - #endregion - } - - class PublishedContentStrong1 : PublishedContentModel - { - public PublishedContentStrong1(IPublishedContent content) - : base(content) - { } - - public int StrongValue => this.Value("strongValue"); - } - - class PublishedContentStrong1Sub : PublishedContentStrong1 - { - public PublishedContentStrong1Sub(IPublishedContent content) - : base(content) - { } - - public int AnotherValue => this.Value("anotherValue"); - } - - class PublishedContentStrong2 : PublishedContentModel - { - public PublishedContentStrong2(IPublishedContent content) - : base(content) - { } - - public int StrongValue => this.Value("strongValue"); - } - - class AutoPublishedContentType : PublishedContentType - { - private static readonly PublishedPropertyType Default; - - static AutoPublishedContentType() - { - var dataTypeService = new TestObjects.TestDataTypeService( - new DataType(new VoidEditor(Mock.Of())) { Id = 666 }); - - var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); - Default = factory.CreatePropertyType("*", 666); - } - - public AutoPublishedContentType(int id, string alias, IEnumerable propertyTypes) - : base(id, alias, PublishedItemType.Content, Enumerable.Empty(), propertyTypes, ContentVariation.InvariantNeutral) - { } - - public AutoPublishedContentType(int id, string alias, IEnumerable compositionAliases, IEnumerable propertyTypes) - : base(id, alias, PublishedItemType.Content, compositionAliases, propertyTypes, ContentVariation.InvariantNeutral) - { } - - public override PublishedPropertyType GetPropertyType(string alias) - { - var propertyType = base.GetPropertyType(alias); - return propertyType ?? Default; - } - } -} + public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); + public string UrlName { get; set; } + public string DocumentTypeAlias { get; private set; } + public int DocumentTypeId { get; private set; } + public string WriterName { get; set; } + public string CreatorName { get; set; } + public int WriterId { get; set; } + public int CreatorId { get; set; } + public string Path { get; set; } + public DateTime CreateDate { get; set; } + public DateTime UpdateDate { get; set; } + public Guid Version { get; set; } + public int Level { get; set; } + public string Url { get; set; } + + public PublishedItemType ItemType { get { return PublishedItemType.Content; } } + public bool IsDraft { get; set; } + + #endregion + + #region Tree + + public int ParentId { get; set; } + public IEnumerable ChildIds { get; set; } + + public IPublishedContent Parent { get; set; } + public IEnumerable Children { get; set; } + + #endregion + + #region ContentType + + public PublishedContentType ContentType { get; private set; } + + #endregion + + #region Properties + + public IEnumerable Properties { get; set; } + + public IPublishedProperty GetProperty(string alias) + { + return Properties.FirstOrDefault(p => p.Alias.InvariantEquals(alias)); + } + + public IPublishedProperty GetProperty(string alias, bool recurse) + { + var property = GetProperty(alias); + if (recurse == false) return property; + + IPublishedContent content = this; + while (content != null && (property == null || property.HasValue() == false)) + { + content = content.Parent; + property = content == null ? null : content.GetProperty(alias); + } + + return property; + } + + public object this[string alias] + { + get + { + var property = GetProperty(alias); + return property == null || property.HasValue() == false ? null : property.GetValue(); + } + } + + #endregion + } + + class SolidPublishedProperty : IPublishedProperty + { + public string Alias { get; set; } + public object SolidSourceValue { get; set; } + public object SolidValue { get; set; } + public bool SolidHasValue { get; set; } + public object SolidXPathValue { get; set; } + + public object GetSourceValue(string culture = null, string segment = null) => SolidSourceValue; + public object GetValue(string culture = null, string segment = null) => SolidValue; + public object GetXPathValue(string culture = null, string segment = null) => SolidXPathValue; + public bool HasValue(string culture = null, string segment = null) => SolidHasValue; + } + + [PublishedModel("ContentType2")] + internal class ContentType2 : PublishedContentModel + { + #region Plumbing + + public ContentType2(IPublishedContent content) + : base(content) + { } + + #endregion + + public int Prop1 => this.Value("prop1"); + } + + [PublishedModel("ContentType2Sub")] + internal class ContentType2Sub : ContentType2 + { + #region Plumbing + + public ContentType2Sub(IPublishedContent content) + : base(content) + { } + + #endregion + } + + class PublishedContentStrong1 : PublishedContentModel + { + public PublishedContentStrong1(IPublishedContent content) + : base(content) + { } + + public int StrongValue => this.Value("strongValue"); + } + + class PublishedContentStrong1Sub : PublishedContentStrong1 + { + public PublishedContentStrong1Sub(IPublishedContent content) + : base(content) + { } + + public int AnotherValue => this.Value("anotherValue"); + } + + class PublishedContentStrong2 : PublishedContentModel + { + public PublishedContentStrong2(IPublishedContent content) + : base(content) + { } + + public int StrongValue => this.Value("strongValue"); + } + + class AutoPublishedContentType : PublishedContentType + { + private static readonly PublishedPropertyType Default; + + static AutoPublishedContentType() + { + var dataTypeService = new TestObjects.TestDataTypeService( + new DataType(new VoidEditor(Mock.Of())) { Id = 666 }); + + var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), dataTypeService); + Default = factory.CreatePropertyType("*", 666); + } + + public AutoPublishedContentType(int id, string alias, IEnumerable propertyTypes) + : base(id, alias, PublishedItemType.Content, Enumerable.Empty(), propertyTypes, ContentVariation.InvariantNeutral) + { } + + public AutoPublishedContentType(int id, string alias, IEnumerable compositionAliases, IEnumerable propertyTypes) + : base(id, alias, PublishedItemType.Content, compositionAliases, propertyTypes, ContentVariation.InvariantNeutral) + { } + + public override PublishedPropertyType GetPropertyType(string alias) + { + var propertyType = base.GetPropertyType(alias); + return propertyType ?? Default; + } + } +} diff --git a/src/Umbraco.Tests/Routing/RoutesCacheTests.cs b/src/Umbraco.Tests/Routing/RoutesCacheTests.cs index 4b04ebb50d..68e80076dd 100644 --- a/src/Umbraco.Tests/Routing/RoutesCacheTests.cs +++ b/src/Umbraco.Tests/Routing/RoutesCacheTests.cs @@ -19,7 +19,7 @@ namespace Umbraco.Tests.Routing { //var routingContext = GetRoutingContext("/test", 1111); var umbracoContext = GetUmbracoContext("/test", 0); - var cache = umbracoContext.PublishedShapshot.Content as PublishedContentCache; + var cache = umbracoContext.PublishedSnapshot.Content as PublishedContentCache; if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported."); // fixme not sure? diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs index 23d3c84bc9..818e1f6817 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; +using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.XmlPublishedCache; using Umbraco.Web.Routing; @@ -99,7 +100,7 @@ namespace Umbraco.Tests.Routing [TestCase(1178, "/home/sub1/custom-sub-2/")] [TestCase(1175, "/home/sub-2/")] [TestCase(1172, "/test-page/")] - public void Get_Nice_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) + public void Get_Url_Not_Hiding_Top_Level(int nodeId, string niceUrlMatch) { var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); @@ -129,7 +130,7 @@ namespace Umbraco.Tests.Routing [TestCase(1178, "/sub1/custom-sub-2/")] [TestCase(1175, "/sub-2/")] [TestCase(1172, "/test-page/")] // not hidden because not first root - public void Get_Nice_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) + public void Get_Url_Hiding_Top_Level(int nodeId, string niceUrlMatch) { var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); @@ -176,7 +177,7 @@ namespace Umbraco.Tests.Routing } [Test] - public void Get_Nice_Url_Unpublished() + public void Get_Url_Unpublished() { var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); diff --git a/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs index 4f4e35f7e2..b064e9685c 100644 --- a/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs +++ b/src/Umbraco.Tests/Routing/UrlsProviderWithDomainsTests.cs @@ -171,7 +171,7 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "http://domain2.com", false, "http://domain1.com/1001-1/")] [TestCase(1001, "https://domain1.com", false, "/")] [TestCase(10011, "https://domain1.com", false, "/1001-1/")] - public void Get_Nice_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) + public void Get_Url_SimpleDomain(int nodeId, string currentUrl, bool absolute, string expected) { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); @@ -207,7 +207,7 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "http://domain2.com", false, "http://domain1.com/foo/1001-1/")] [TestCase(1001, "https://domain1.com", false, "http://domain1.com/foo/")] [TestCase(10011, "https://domain1.com", false, "http://domain1.com/foo/1001-1/")] - public void Get_Nice_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) + public void Get_Url_SimpleWithSchemeAndPath(int nodeId, string currentUrl, bool absolute, string expected) { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); @@ -235,7 +235,7 @@ namespace Umbraco.Tests.Routing [TestCase(10011, "http://domain1.com", false, "/")] [TestCase(100111, "http://domain1.com", false, "/1001-1-1/")] [TestCase(1002, "http://domain1.com", false, "/1002/")] - public void Get_Nice_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) + public void Get_Url_DeepDomain(int nodeId, string currentUrl, bool absolute, string expected) { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); @@ -269,7 +269,7 @@ namespace Umbraco.Tests.Routing [TestCase(1003, "http://domain3.com", false, "/")] [TestCase(10031, "http://domain3.com", false, "/en/")] [TestCase(100321, "http://domain3.com", false, "/fr/1003-2-1/")] - public void Get_Nice_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) + public void Get_Url_NestedDomains(int nodeId, string currentUrl, bool absolute, string expected) { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); @@ -293,7 +293,7 @@ namespace Umbraco.Tests.Routing } [Test] - public void Get_Nice_Url_DomainsAndCache() + public void Get_Url_DomainsAndCache() { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var request = Mock.Get(settings.RequestHandler); @@ -360,7 +360,7 @@ namespace Umbraco.Tests.Routing } [Test] - public void Get_Nice_Url_Relative_Or_Absolute() + public void Get_Url_Relative_Or_Absolute() { var settings = SettingsForTests.GenerateMockUmbracoSettings(); var requestMock = Mock.Get(settings.RequestHandler); @@ -394,7 +394,7 @@ namespace Umbraco.Tests.Routing } [Test] - public void Get_Nice_Url_Alternate() + public void Get_Url_Alternate() { var settings = SettingsForTests.GenerateMockUmbracoSettings(); diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 96404b1e59..97d88a680b 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -131,7 +131,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting webSecurity.Setup(x => x.UserHasSectionAccess(It.IsAny(), It.IsAny())) .Returns(() => true); - var publishedSnapshot = new Mock(); + var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of()); var publishedSnapshotService = new Mock(); publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedSnapshot.Object); diff --git a/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedSnapshotAccessor.cs b/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedSnapshotAccessor.cs index 10c8739029..3768803de2 100644 --- a/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedSnapshotAccessor.cs +++ b/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedSnapshotAccessor.cs @@ -4,6 +4,6 @@ namespace Umbraco.Tests.TestHelpers.Stubs { public class TestPublishedSnapshotAccessor : IPublishedSnapshotAccessor { - public IPublishedShapshot PublishedSnapshot { get; set; } + public IPublishedSnapshot PublishedSnapshot { get; set; } } } diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs index 050c10757a..ee0dd38c45 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects-Mocks.cs @@ -106,7 +106,7 @@ namespace Umbraco.Tests.TestHelpers { var httpContext = Mock.Of(); - var publishedSnapshotMock = new Mock(); + var publishedSnapshotMock = new Mock(); publishedSnapshotMock.Setup(x => x.Members).Returns(Mock.Of()); var publishedSnapshot = publishedSnapshotMock.Object; var publishedSnapshotServiceMock = new Mock(); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 2b6dcffeab..80a4da3fb5 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -343,20 +343,23 @@ namespace Umbraco.Tests.TestHelpers } } - protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null, IGlobalSettings globalSettings = null) + protected UmbracoContext GetUmbracoContext(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null, IGlobalSettings globalSettings = null, IPublishedSnapshotService snapshotService = null) { // ensure we have a PublishedCachesService - var service = PublishedSnapshotService as PublishedSnapshotService; + var service = snapshotService ?? PublishedSnapshotService as PublishedSnapshotService; if (service == null) throw new Exception("Not a proper XmlPublishedCache.PublishedCachesService."); - // re-initialize PublishedCacheService content with an Xml source with proper template id - service.XmlStore.GetXmlDocument = () => + if (service is PublishedSnapshotService) { - var doc = new XmlDocument(); - doc.LoadXml(GetXmlContent(templateId)); - return doc; - }; + // re-initialize PublishedCacheService content with an Xml source with proper template id + ((PublishedSnapshotService)service).XmlStore.GetXmlDocument = () => + { + var doc = new XmlDocument(); + doc.LoadXml(GetXmlContent(templateId)); + return doc; + }; + } var httpContext = GetHttpContextFactory(url, routeData).HttpContext; diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 863b875394..655dac8796 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -128,6 +128,7 @@ + @@ -375,7 +376,6 @@ - diff --git a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs index 927b5557bd..931cc57493 100644 --- a/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/SurfaceControllerTests.cs @@ -100,7 +100,7 @@ namespace Umbraco.Tests.Web.Mvc [Test] public void Can_Lookup_Content() { - var publishedSnapshot = new Mock(); + var publishedSnapshot = new Mock(); publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of()); var publishedSnapshotService = new Mock(); publishedSnapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(publishedSnapshot.Object); diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index 9fe3b44264..afc461c6de 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -432,7 +432,7 @@ namespace Umbraco.Tests.Web.Mvc var globalSettings = TestObjects.GetGlobalSettings(); var ctx = new UmbracoContext( - GetHttpContextFactory(url, routeData).HttpContext, + http, _service, new WebSecurity(http, Current.Services.UserService, globalSettings), TestObjects.GetUmbracoSettings(), diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 5ca7b60cf0..d2a1ee6f80 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -98,7 +98,7 @@ namespace Umbraco.Web.Composing public static DistributedCache DistributedCache => Container.GetInstance(); - public static IPublishedShapshot PublishedSnapshot + public static IPublishedSnapshot PublishedSnapshot => Container.GetInstance().PublishedSnapshot; public static EventMessages EventMessages diff --git a/src/Umbraco.Web/PublishedCache/IPublishedShapshot.cs b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs similarity index 97% rename from src/Umbraco.Web/PublishedCache/IPublishedShapshot.cs rename to src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs index 6e859d0f02..628a67b561 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedShapshot.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedSnapshot.cs @@ -8,7 +8,7 @@ namespace Umbraco.Web.PublishedCache /// /// A published snapshot is a point-in-time capture of the current state of /// everything that is "published". - public interface IPublishedShapshot + public interface IPublishedSnapshot { /// /// Gets the . diff --git a/src/Umbraco.Web/PublishedCache/IPublishedSnapshotAccessor.cs b/src/Umbraco.Web/PublishedCache/IPublishedSnapshotAccessor.cs index 9c0bc5a1e7..775de214ec 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedSnapshotAccessor.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedSnapshotAccessor.cs @@ -1,10 +1,10 @@ namespace Umbraco.Web.PublishedCache { /// - /// Provides access to the "current" . + /// Provides access to the "current" . /// public interface IPublishedSnapshotAccessor { - IPublishedShapshot PublishedSnapshot { get; set; } + IPublishedSnapshot PublishedSnapshot { get; set; } } } diff --git a/src/Umbraco.Web/PublishedCache/IPublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/IPublishedSnapshotService.cs index 40c3538ed9..cf10ed5f3a 100644 --- a/src/Umbraco.Web/PublishedCache/IPublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/IPublishedSnapshotService.cs @@ -6,7 +6,7 @@ using Umbraco.Web.Cache; namespace Umbraco.Web.PublishedCache { /// - /// Creates and manages instances. + /// Creates and manages instances. /// public interface IPublishedSnapshotService : IDisposable { @@ -32,7 +32,7 @@ namespace Umbraco.Web.PublishedCache /// If is null, the snapshot is not previewing, else it /// is previewing, and what is or is not visible in preview depends on the content of the token, /// which is not specified and depends on the actual published snapshot service implementation. - IPublishedShapshot CreatePublishedSnapshot(string previewToken); + IPublishedSnapshot CreatePublishedSnapshot(string previewToken); /// /// Gets the published snapshot accessor. diff --git a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs index 7fe898b080..f2e3355750 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/Property.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/Property.cs @@ -98,7 +98,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private CacheValues GetCacheValues(PropertyCacheLevel cacheLevel) { CacheValues cacheValues; - PublishedShapshot publishedSnapshot; + PublishedSnapshot publishedSnapshot; ICacheProvider cache; switch (cacheLevel) { @@ -115,7 +115,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // elements cache (if we don't want to pollute the elements cache with short-lived // data) depending on settings // for members, always cache in the snapshot cache - never pollute elements cache - publishedSnapshot = (PublishedShapshot) _publishedSnapshotAccessor.PublishedSnapshot; + publishedSnapshot = (PublishedSnapshot) _publishedSnapshotAccessor.PublishedSnapshot; cache = publishedSnapshot == null ? null : ((_isPreviewing == false || PublishedSnapshotService.FullCacheWhenPreviewing) && (_isMember == false) @@ -125,7 +125,7 @@ namespace Umbraco.Web.PublishedCache.NuCache break; case PropertyCacheLevel.Snapshot: // cache within the snapshot cache - publishedSnapshot = (PublishedShapshot) _publishedSnapshotAccessor.PublishedSnapshot; + publishedSnapshot = (PublishedSnapshot) _publishedSnapshotAccessor.PublishedSnapshot; cache = publishedSnapshot?.SnapshotCache; cacheValues = GetCacheValues(cache); break; diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 480c18201f..b5201716ac 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -102,10 +102,10 @@ namespace Umbraco.Web.PublishedCache.NuCache // this is for tests purposes // args are: current published snapshot (may be null), previewing, content id - returns: content - internal static Func GetContentByIdFunc { get; set; } + internal static Func GetContentByIdFunc { get; set; } = (publishedShapshot, previewing, id) => publishedShapshot.Content.GetById(previewing, id); - internal static Func GetMediaByIdFunc { get; set; } + internal static Func GetMediaByIdFunc { get; set; } = (publishedShapshot, previewing, id) => publishedShapshot.Media.GetById(previewing, id); private IPublishedContent GetContentById(bool previewing, int id) @@ -289,7 +289,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // beware what you use that one for - you don't want to cache its result private ICacheProvider GetAppropriateCache() { - var publishedSnapshot = (PublishedShapshot)_publishedSnapshotAccessor.PublishedSnapshot; + var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; var cache = publishedSnapshot == null ? null : ((IsPreviewing == false || PublishedSnapshotService.FullCacheWhenPreviewing) && (ItemType != PublishedItemType.Member) @@ -300,7 +300,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private ICacheProvider GetCurrentSnapshotCache() { - var publishedSnapshot = (PublishedShapshot)_publishedSnapshotAccessor.PublishedSnapshot; + var publishedSnapshot = (PublishedSnapshot)_publishedSnapshotAccessor.PublishedSnapshot; return publishedSnapshot?.SnapshotCache; } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedShapshot.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs similarity index 88% rename from src/Umbraco.Web/PublishedCache/NuCache/PublishedShapshot.cs rename to src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs index b21834f7b4..741e4d09f5 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedShapshot.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshot.cs @@ -5,7 +5,7 @@ using Umbraco.Core.Cache; namespace Umbraco.Web.PublishedCache.NuCache { // implements published snapshot - internal class PublishedShapshot : IPublishedShapshot, IDisposable + internal class PublishedSnapshot : IPublishedSnapshot, IDisposable { private readonly PublishedSnapshotService _service; private bool _defaultPreview; @@ -13,7 +13,7 @@ namespace Umbraco.Web.PublishedCache.NuCache #region Constructors - public PublishedShapshot(PublishedSnapshotService service, bool defaultPreview) + public PublishedSnapshot(PublishedSnapshotService service, bool defaultPreview) { _service = service; _defaultPreview = defaultPreview; @@ -72,13 +72,13 @@ namespace Umbraco.Web.PublishedCache.NuCache private class ForcedPreviewObject : DisposableObject { - private readonly PublishedShapshot _publishedShapshot; + private readonly PublishedSnapshot _publishedSnapshot; private readonly bool _origPreview; private readonly Action _callback; - public ForcedPreviewObject(PublishedShapshot publishedShapshot, bool preview, Action callback) + public ForcedPreviewObject(PublishedSnapshot publishedShapshot, bool preview, Action callback) { - _publishedShapshot = publishedShapshot; + _publishedSnapshot = publishedShapshot; _callback = callback; // save and force @@ -89,7 +89,7 @@ namespace Umbraco.Web.PublishedCache.NuCache protected override void DisposeResources() { // restore - _publishedShapshot._defaultPreview = _origPreview; + _publishedSnapshot._defaultPreview = _origPreview; _callback?.Invoke(_origPreview); } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 1d83dcaae3..e611a738e5 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -533,7 +533,7 @@ namespace Umbraco.Web.PublishedCache.NuCache } if (draftChanged || publishedChanged) - ((PublishedShapshot)CurrentPublishedShapshot).Resync(); + ((PublishedSnapshot)CurrentPublishedSnapshot).Resync(); } private void NotifyLocked(IEnumerable payloads, out bool draftChanged, out bool publishedChanged) @@ -630,7 +630,7 @@ namespace Umbraco.Web.PublishedCache.NuCache } if (anythingChanged) - ((PublishedShapshot)CurrentPublishedShapshot).Resync(); + ((PublishedSnapshot)CurrentPublishedSnapshot).Resync(); } private void NotifyLocked(IEnumerable payloads, out bool anythingChanged) @@ -719,7 +719,7 @@ namespace Umbraco.Web.PublishedCache.NuCache Notify(_contentStore, payloads, RefreshContentTypesLocked); Notify(_mediaStore, payloads, RefreshMediaTypesLocked); - ((PublishedShapshot)CurrentPublishedShapshot).Resync(); + ((PublishedSnapshot)CurrentPublishedSnapshot).Resync(); } private void Notify(ContentStore store, ContentTypeCacheRefresher.JsonPayload[] payloads, Action, IEnumerable, IEnumerable, IEnumerable> action) @@ -796,7 +796,7 @@ namespace Umbraco.Web.PublishedCache.NuCache } } - ((PublishedShapshot)CurrentPublishedShapshot).Resync(); + ((PublishedSnapshot)CurrentPublishedSnapshot).Resync(); } public override void Notify(DomainCacheRefresher.JsonPayload[] payloads) @@ -945,17 +945,17 @@ namespace Umbraco.Web.PublishedCache.NuCache private long _contentGen, _mediaGen, _domainGen; private ICacheProvider _elementsCache; - public override IPublishedShapshot CreatePublishedSnapshot(string previewToken) + public override IPublishedSnapshot CreatePublishedSnapshot(string previewToken) { // no cache, no joy if (_isReady == false) throw new InvalidOperationException("The published snapshot service has not properly initialized."); var preview = previewToken.IsNullOrWhiteSpace() == false; - return new PublishedShapshot(this, preview); + return new PublishedSnapshot(this, preview); } - public PublishedShapshot.PublishedSnapshotElements GetElements(bool previewDefault) + public PublishedSnapshot.PublishedSnapshotElements GetElements(bool previewDefault) { // note: using ObjectCacheRuntimeCacheProvider for elements and snapshot caches // is not recommended because it creates an inner MemoryCache which is a heavy @@ -996,7 +996,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // a MaxValue to make sure this one runs last, and it should be ok scopeContext.Enlist("Umbraco.Web.PublishedCache.NuCache.PublishedSnapshotService.Resync", () => this, (completed, svc) => { - ((PublishedShapshot)svc.CurrentPublishedShapshot).Resync(); + ((PublishedSnapshot)svc.CurrentPublishedSnapshot).Resync(); }, int.MaxValue); } @@ -1017,7 +1017,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var domainCache = new DomainCache(domainSnap); var domainHelper = new DomainHelper(domainCache, _siteDomainHelper); - return new PublishedShapshot.PublishedSnapshotElements + return new PublishedSnapshot.PublishedSnapshotElements { ContentCache = new ContentCache(previewDefault, contentSnap, snapshotCache, elementsCache, domainHelper, _globalSettings, _serviceContext.LocalizationService), MediaCache = new MediaCache(previewDefault, mediaSnap, snapshotCache, elementsCache), diff --git a/src/Umbraco.Web/PublishedCache/PublishedSnapshotServiceBase.cs b/src/Umbraco.Web/PublishedCache/PublishedSnapshotServiceBase.cs index 08a754153c..685c129224 100644 --- a/src/Umbraco.Web/PublishedCache/PublishedSnapshotServiceBase.cs +++ b/src/Umbraco.Web/PublishedCache/PublishedSnapshotServiceBase.cs @@ -15,9 +15,9 @@ namespace Umbraco.Web.PublishedCache // note: NOT setting _publishedSnapshotAccessor.PublishedSnapshot here because it is the // responsibility of the caller to manage what the 'current' facade is - public abstract IPublishedShapshot CreatePublishedSnapshot(string previewToken); + public abstract IPublishedSnapshot CreatePublishedSnapshot(string previewToken); - protected IPublishedShapshot CurrentPublishedShapshot => PublishedSnapshotAccessor.PublishedSnapshot; + protected IPublishedSnapshot CurrentPublishedSnapshot => PublishedSnapshotAccessor.PublishedSnapshot; public abstract bool EnsureEnvironment(out IEnumerable errors); diff --git a/src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs b/src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs index cc4b09f657..706d67020a 100644 --- a/src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs +++ b/src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs @@ -11,13 +11,13 @@ namespace Umbraco.Web.PublishedCache _umbracoContextAccessor = umbracoContextAccessor; } - public IPublishedShapshot PublishedSnapshot + public IPublishedSnapshot PublishedSnapshot { get { var umbracoContext = _umbracoContextAccessor.UmbracoContext; if (umbracoContext == null) throw new Exception("The IUmbracoContextAccessor could not provide an UmbracoContext."); - return umbracoContext.PublishedShapshot; + return umbracoContext.PublishedSnapshot; } set diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedShapshot.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs similarity index 92% rename from src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedShapshot.cs rename to src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs index e0417bdebf..61ea7d2534 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedShapshot.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshot.cs @@ -7,13 +7,13 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache /// /// Implements a published snapshot. /// - class PublishedShapshot : IPublishedShapshot + class PublishedSnapshot : IPublishedSnapshot { /// - /// Initializes a new instance of the class with a content cache + /// Initializes a new instance of the class with a content cache /// and a media cache. /// - public PublishedShapshot( + public PublishedSnapshot( PublishedContentCache contentCache, PublishedMediaCache mediaCache, PublishedMemberCache memberCache, diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs index 7cde462dbc..1f327f4cd3 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs @@ -139,7 +139,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache #region Caches - public override IPublishedShapshot CreatePublishedSnapshot(string previewToken) + public override IPublishedSnapshot CreatePublishedSnapshot(string previewToken) { // use _requestCache to store recursive properties lookup, etc. both in content // and media cache. Life span should be the current request. Or, ideally @@ -148,7 +148,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache var domainCache = new DomainCache(_domainService, _localizationService); - return new PublishedShapshot( + return new PublishedSnapshot( new PublishedContentCache(_xmlStore, domainCache, _requestCache, _globalSettings, _siteDomainHelper, _contentTypeCache, _routesCache, previewToken), new PublishedMediaCache(_xmlStore, _mediaService, _userService, _requestCache, _contentTypeCache), new PublishedMemberCache(_xmlStore, _requestCache, _memberService, _contentTypeCache), diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs index 60b5aa1643..85deb72066 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs @@ -1250,7 +1250,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; private void ResyncCurrentPublishedSnapshot(XmlDocument xml) { - var publishedSnapshot = (PublishedShapshot) _publishedSnapshotAccessor.PublishedSnapshot; + var publishedSnapshot = (PublishedSnapshot) _publishedSnapshotAccessor.PublishedSnapshot; if (publishedSnapshot == null) return; ((PublishedContentCache) publishedSnapshot.Content).Resync(xml); ((PublishedMediaCache) publishedSnapshot.Media).Resync(); diff --git a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs index 6cc3b74972..8ffde220c2 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByLegacy404.cs @@ -54,7 +54,7 @@ namespace Umbraco.Web.Routing } if (node != null) { - var d = DomainHelper.FindWildcardDomainInPath(frequest.UmbracoContext.PublishedShapshot.Domains.GetAll(true), node.Path, null); + var d = DomainHelper.FindWildcardDomainInPath(frequest.UmbracoContext.PublishedSnapshot.Domains.GetAll(true), node.Path, null); if (d != null) errorCulture = d.Culture; } diff --git a/src/Umbraco.Web/Routing/PublishedRouter.cs b/src/Umbraco.Web/Routing/PublishedRouter.cs index ac07f1ad32..0b4fc89b6b 100644 --- a/src/Umbraco.Web/Routing/PublishedRouter.cs +++ b/src/Umbraco.Web/Routing/PublishedRouter.cs @@ -266,7 +266,7 @@ namespace Umbraco.Web.Routing _logger.Debug(() => $"{tracePrefix}Uri=\"{request.Uri}\""); // try to find a domain matching the current request - var domainAndUri = DomainHelper.DomainForUri(request.UmbracoContext.PublishedShapshot.Domains.GetAll(false), request.Uri); + var domainAndUri = DomainHelper.DomainForUri(request.UmbracoContext.PublishedSnapshot.Domains.GetAll(false), request.Uri); // handle domain - always has a contentId and a culture if (domainAndUri != null) @@ -311,7 +311,7 @@ namespace Umbraco.Web.Routing var nodePath = request.PublishedContent.Path; _logger.Debug(() => $"{tracePrefix}Path=\"{nodePath}\""); var rootNodeId = request.HasDomain ? request.Domain.ContentId : (int?)null; - var domain = DomainHelper.FindWildcardDomainInPath(request.UmbracoContext.PublishedShapshot.Domains.GetAll(true), nodePath, rootNodeId); + var domain = DomainHelper.FindWildcardDomainInPath(request.UmbracoContext.PublishedSnapshot.Domains.GetAll(true), nodePath, rootNodeId); // always has a contentId and a culture if (domain != null) @@ -602,14 +602,14 @@ namespace Umbraco.Web.Routing var loginPageId = publicAccessAttempt.Result.LoginNodeId; if (loginPageId != request.PublishedContent.Id) - request.PublishedContent = request.UmbracoContext.PublishedShapshot.Content.GetById(loginPageId); + request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(loginPageId); } else if (_services.PublicAccessService.HasAccess(request.PublishedContent.Id, _services.ContentService, GetRolesForLogin(membershipHelper.CurrentUserName)) == false) { _logger.Debug(() => $"{tracePrefix}Current member has not access, redirect to error page"); var errorPageId = publicAccessAttempt.Result.NoAccessNodeId; if (errorPageId != request.PublishedContent.Id) - request.PublishedContent = request.UmbracoContext.PublishedShapshot.Content.GetById(errorPageId); + request.PublishedContent = request.UmbracoContext.PublishedSnapshot.Content.GetById(errorPageId); } else { diff --git a/src/Umbraco.Web/Security/MembershipHelper.cs b/src/Umbraco.Web/Security/MembershipHelper.cs index 5e9a4efc41..9b7ce72817 100644 --- a/src/Umbraco.Web/Security/MembershipHelper.cs +++ b/src/Umbraco.Web/Security/MembershipHelper.cs @@ -94,7 +94,7 @@ namespace Umbraco.Web.Security _umbracoContext = umbracoContext; _membershipProvider = membershipProvider; _roleProvider = roleProvider; - _memberCache = umbracoContext.PublishedShapshot.Members; + _memberCache = umbracoContext.PublishedSnapshot.Members; // helpers are *not* instanciated by the container so we have to // get our dependencies injected manually, through properties. diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 44bc3ec324..1339166185 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -342,6 +342,7 @@ + @@ -351,13 +352,13 @@ + - @@ -371,7 +372,6 @@ - @@ -389,7 +389,7 @@ - + diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index ef684a21ba..c58ff40575 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web public class UmbracoContext : DisposableObject, IDisposeOnRequestEnd { private readonly IGlobalSettings _globalSettings; - private readonly Lazy _publishedSnapshot; + private readonly Lazy _publishedSnapshot; private DomainHelper _domainHelper; private string _previewToken; private bool? _previewing; @@ -125,7 +125,7 @@ namespace Umbraco.Web Security = webSecurity; // beware - we cannot expect a current user here, so detecting preview mode must be a lazy thing - _publishedSnapshot = new Lazy(() => publishedSnapshotService.CreatePublishedSnapshot(PreviewToken)); + _publishedSnapshot = new Lazy(() => publishedSnapshotService.CreatePublishedSnapshot(PreviewToken)); // set the urls... // NOTE: The request will not be available during app startup so we can only set this to an absolute URL of localhost, this @@ -178,7 +178,7 @@ namespace Umbraco.Web /// /// Gets the published snapshot. /// - public IPublishedShapshot PublishedShapshot => _publishedSnapshot.Value; + public IPublishedSnapshot PublishedSnapshot => _publishedSnapshot.Value; // for unit tests internal bool HasPublishedSnapshot => _publishedSnapshot.IsValueCreated; @@ -186,12 +186,12 @@ namespace Umbraco.Web /// /// Gets the published content cache. /// - public IPublishedContentCache ContentCache => PublishedShapshot.Content; + public IPublishedContentCache ContentCache => PublishedSnapshot.Content; /// /// Gets the published media cache. /// - public IPublishedMediaCache MediaCache => PublishedShapshot.Media; + public IPublishedMediaCache MediaCache => PublishedSnapshot.Media; /// /// Boolean value indicating whether the current request is a front-end umbraco request @@ -227,7 +227,7 @@ namespace Umbraco.Web internal DomainHelper GetDomainHelper(ISiteDomainHelper siteDomainHelper) { if (_domainHelper == null) - _domainHelper = new DomainHelper(PublishedShapshot.Domains, siteDomainHelper); + _domainHelper = new DomainHelper(PublishedSnapshot.Domains, siteDomainHelper); return _domainHelper; } @@ -314,7 +314,7 @@ namespace Umbraco.Web internal IDisposable ForcedPreview(bool preview) { InPreviewMode = preview; - return PublishedShapshot.ForcedPreview(preview, orig => InPreviewMode = orig); + return PublishedSnapshot.ForcedPreview(preview, orig => InPreviewMode = orig); } private HttpRequestBase GetRequestFromContext() From c19dbeda2320532be3ecaed1849228e6a84dbc0b Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 13:27:15 +1000 Subject: [PATCH 35/58] Adds a couple of tests which yielded some other issues with getting urls by culture, those are now fixed --- .../Published/ConvertersTests.cs | 7 +- .../Published/PublishedSnapshotTestObjects.cs | 64 +-------- src/Umbraco.Tests/Routing/UrlProviderTests.cs | 126 ++++++++++++++++-- .../TestHelpers/Stubs/TestPublishedContent.cs | 66 +++++++++ .../TestHelpers/TestWithDatabaseBase.cs | 3 +- src/Umbraco.Tests/Umbraco.Tests.csproj | 1 + .../Mapping/RedirectUrlMapperProfile.cs | 10 +- .../PublishedCache/NuCache/ContentCache.cs | 4 +- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 13 +- src/Umbraco.Web/Routing/DomainHelper.cs | 24 ++-- src/Umbraco.Web/Routing/UrlProvider.cs | 4 +- 11 files changed, 226 insertions(+), 96 deletions(-) create mode 100644 src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedContent.cs diff --git a/src/Umbraco.Tests/Published/ConvertersTests.cs b/src/Umbraco.Tests/Published/ConvertersTests.cs index 0c47a551bc..25933fdd9d 100644 --- a/src/Umbraco.Tests/Published/ConvertersTests.cs +++ b/src/Umbraco.Tests/Published/ConvertersTests.cs @@ -11,6 +11,7 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Web; using Umbraco.Web.PublishedCache; @@ -99,7 +100,7 @@ namespace Umbraco.Tests.Published var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary { { "prop1", "1234" } }, false); var cntType1 = contentTypeFactory.CreateContentType(1001, "cnt1", Array.Empty()); - var cnt1 = new PublishedSnapshotTestObjects.TestPublishedContent(cntType1, 1234, Guid.NewGuid(), new Dictionary(), false); + var cnt1 = new TestPublishedContent(cntType1, 1234, Guid.NewGuid(), new Dictionary(), false); cacheContent[cnt1.Id] = cnt1; Assert.AreSame(cnt1, element1.Value("prop1")); @@ -200,8 +201,8 @@ namespace Umbraco.Tests.Published var element1 = new PublishedElement(elementType1, Guid.NewGuid(), new Dictionary { { "prop1", "val1" } }, false); var element2 = new PublishedElement(elementType2, Guid.NewGuid(), new Dictionary { { "prop2", "1003" } }, false); - var cnt1 = new PublishedSnapshotTestObjects.TestPublishedContent(contentType1, 1003, Guid.NewGuid(), new Dictionary { { "prop1", "val1" } }, false); - var cnt2 = new PublishedSnapshotTestObjects.TestPublishedContent(contentType2, 1004, Guid.NewGuid(), new Dictionary { { "prop2", "1003" } }, false); + var cnt1 = new TestPublishedContent(contentType1, 1003, Guid.NewGuid(), new Dictionary { { "prop1", "val1" } }, false); + var cnt2 = new TestPublishedContent(contentType2, 1004, Guid.NewGuid(), new Dictionary { { "prop2", "1003" } }, false); cacheContent[cnt1.Id] = cnt1.CreateModel(); cacheContent[cnt2.Id] = cnt2.CreateModel(); diff --git a/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs b/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs index acfc12d408..fcb462e5c5 100644 --- a/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs +++ b/src/Umbraco.Tests/Published/PublishedSnapshotTestObjects.cs @@ -8,8 +8,6 @@ namespace Umbraco.Tests.Published { public class PublishedSnapshotTestObjects { - #region Published models - [PublishedModel("element1")] public class TestElementModel1 : PublishedElementModel { @@ -49,66 +47,6 @@ namespace Umbraco.Tests.Published public IEnumerable Prop2 => this.Value>("prop2"); } - - #endregion - - #region Support classes - - internal class TestPublishedContent : PublishedElement, IPublishedContent - { - public TestPublishedContent(PublishedContentType contentType, int id, Guid key, Dictionary values, bool previewing) - : base(contentType, key, values, previewing) - { - Id = id; - } - - public int Id { get; } - public int TemplateId { get; set; } - public int SortOrder { get; set; } - public string Name { get; set; } - public IReadOnlyDictionary CultureNames => throw new NotSupportedException(); - public string UrlName { get; set; } - public string DocumentTypeAlias => ContentType.Alias; - public int DocumentTypeId { get; set; } - public string WriterName { get; set; } - public string CreatorName { get; set; } - public int WriterId { get; set; } - public int CreatorId { get; set; } - public string Path { get; set; } - public DateTime CreateDate { get; set; } - public DateTime UpdateDate { get; set; } - public Guid Version { get; set; } - public int Level { get; set; } - public string Url { get; set; } - public PublishedItemType ItemType => ContentType.ItemType; - public bool IsDraft { get; set; } - public IPublishedContent Parent { get; set; } - public IEnumerable Children { get; set; } - - // copied from PublishedContentBase - public IPublishedProperty GetProperty(string alias, bool recurse) - { - var property = GetProperty(alias); - if (recurse == false) return property; - - IPublishedContent content = this; - var firstNonNullProperty = property; - while (content != null && (property == null || property.HasValue() == false)) - { - content = content.Parent; - property = content?.GetProperty(alias); - if (firstNonNullProperty == null && property != null) firstNonNullProperty = property; - } - - // if we find a content with the property with a value, return that property - // if we find no content with the property, return null - // if we find a content with the property without a value, return that property - // have to save that first property while we look further up, hence firstNonNullProperty - - return property != null && property.HasValue() ? property : firstNonNullProperty; - } - } - - #endregion + } } diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs index 818e1f6817..070c68468a 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -1,9 +1,13 @@ using System; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Tests.Testing; using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.XmlPublishedCache; @@ -44,11 +48,11 @@ namespace Umbraco.Tests.Routing globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new [] + var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); - + }, globalSettings: globalSettings.Object); + var requestHandlerMock = Mock.Get(_umbracoSettings.RequestHandler); requestHandlerMock.Setup(x => x.AddTrailingSlash).Returns(false);// (cached routes have none) @@ -110,7 +114,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); + }, globalSettings: globalSettings.Object); var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); @@ -140,7 +144,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); + }, globalSettings: globalSettings.Object); var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); @@ -149,14 +153,118 @@ namespace Umbraco.Tests.Routing Assert.AreEqual(niceUrlMatch, result); } + /// + /// This tests DefaultUrlProvider.GetUrl with a specific culture when the current URL is the culture specific domain + /// [Test] - public void Get_Nice_Url_Relative_Or_Absolute() + public void Get_Url_For_Culture_Variant_With_Current_Url() + { + const string currentUri = "http://example.com/fr/test"; + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var publishedContentCache = new Mock(); + publishedContentCache.Setup(x => x.GetRouteById(1234, "fr-FR")) + .Returns("9876/home/test-fr"); //prefix with the root id node with the domain assigned as per the umbraco standard + + var domainCache = new Mock(); + domainCache.Setup(x => x.GetAssigned(It.IsAny(), false)) + .Returns((int contentId, bool includeWildcards) => + { + if (contentId != 9876) return Enumerable.Empty(); + return new[] + { + new Domain(2, "example.com/en", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default + new Domain(3, "example.com/fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + }; + }); + + var snapshot = Mock.Of(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object); + + var snapshotService = new Mock(); + snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())) + .Returns(snapshot); + + var umbracoContext = GetUmbracoContext(currentUri, umbracoSettings: _umbracoSettings, + urlProviders: new[] { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, + globalSettings: globalSettings.Object, + snapshotService: snapshotService.Object); + + + var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR"); + + //the current uri is the culture specific domain we want, so the result is a relative path since we are on the culture specific domain + Assert.AreEqual("/fr/home/test-fr/", url); + } + + /// + /// This tests DefaultUrlProvider.GetUrl with a specific culture when the current URL is not the culture specific domain + /// + [Test] + public void Get_Url_For_Culture_Variant_Non_Current_Url() + { + const string currentUri = "http://example.com/en/test"; + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var publishedContentCache = new Mock(); + publishedContentCache.Setup(x => x.GetRouteById(1234, "fr-FR")) + .Returns("9876/home/test-fr"); //prefix with the root id node with the domain assigned as per the umbraco standard + + var domainCache = new Mock(); + domainCache.Setup(x => x.GetAssigned(It.IsAny(), false)) + .Returns((int contentId, bool includeWildcards) => + { + if (contentId != 9876) return Enumerable.Empty(); + return new[] + { + new Domain(2, "example.com/en", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default + new Domain(3, "example.com/fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + }; + }); + + var snapshot = Mock.Of(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object); + + var snapshotService = new Mock(); + snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())) + .Returns(snapshot); + + var umbracoContext = GetUmbracoContext(currentUri, umbracoSettings: _umbracoSettings, + urlProviders: new[] { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, + globalSettings: globalSettings.Object, + snapshotService: snapshotService.Object); + + + var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR"); + + //the current uri is not the culture specific domain we want, so the result is an absolute path to the culture specific domain + Assert.AreEqual("http://example.com/fr/home/test-fr/", url); + } + + [Test] + public void Get_Url_Relative_Or_Absolute() { var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettings.Object); - + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); @@ -164,7 +272,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, umbracoSettings: _umbracoSettings, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); + }, globalSettings: globalSettings.Object); Assert.AreEqual("/home/sub1/custom-sub-1/", umbracoContext.UrlProvider.GetUrl(1177)); @@ -187,7 +295,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext("http://example.com/test", 1111, urlProviders: new[] { new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) - }, globalSettings:globalSettings.Object); + }, globalSettings: globalSettings.Object); //mock the Umbraco settings that we need var requestMock = Mock.Get(_umbracoSettings.RequestHandler); diff --git a/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedContent.cs b/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedContent.cs new file mode 100644 index 0000000000..7d9bbec855 --- /dev/null +++ b/src/Umbraco.Tests/TestHelpers/Stubs/TestPublishedContent.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Umbraco.Core.Models.PublishedContent; +using Umbraco.Web.PublishedCache; + +namespace Umbraco.Tests.TestHelpers.Stubs +{ + internal class TestPublishedContent : PublishedElement, IPublishedContent + { + public TestPublishedContent(PublishedContentType contentType, int id, Guid key, Dictionary values, bool previewing, Dictionary cultureNames = null) + : base(contentType, key, values, previewing) + { + Id = id; + CultureNames = cultureNames; + } + + public int Id { get; } + public int TemplateId { get; set; } + public int SortOrder { get; set; } + public string Name { get; set; } + public IReadOnlyDictionary CultureNames { get; set; } + public string UrlName { get; set; } + public string DocumentTypeAlias => ContentType.Alias; + public int DocumentTypeId { get; set; } + public string WriterName { get; set; } + public string CreatorName { get; set; } + public int WriterId { get; set; } + public int CreatorId { get; set; } + public string Path { get; set; } + public DateTime CreateDate { get; set; } + public DateTime UpdateDate { get; set; } + public Guid Version { get; set; } + public int Level { get; set; } + public string Url { get; set; } + public PublishedItemType ItemType => ContentType.ItemType; + public bool IsDraft { get; set; } + public IPublishedContent Parent { get; set; } + public IEnumerable Children { get; set; } + + // copied from PublishedContentBase + public IPublishedProperty GetProperty(string alias, bool recurse) + { + var property = GetProperty(alias); + if (recurse == false) return property; + + IPublishedContent content = this; + var firstNonNullProperty = property; + while (content != null && (property == null || property.HasValue() == false)) + { + content = content.Parent; + property = content?.GetProperty(alias); + if (firstNonNullProperty == null && property != null) firstNonNullProperty = property; + } + + // if we find a content with the property with a value, return that property + // if we find no content with the property, return null + // if we find a content with the property without a value, return that property + // have to save that first property while we look further up, hence firstNonNullProperty + + return property != null && property.HasValue() ? property : firstNonNullProperty; + } + } +} diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 80a4da3fb5..070166eaff 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -366,7 +366,8 @@ namespace Umbraco.Tests.TestHelpers var umbracoContext = new UmbracoContext( httpContext, service, - new WebSecurity(httpContext, Container.GetInstance(), Container.GetInstance()), + new WebSecurity(httpContext, Container.GetInstance(), + Container.GetInstance()), umbracoSettings ?? Container.GetInstance(), urlProviders ?? Enumerable.Empty(), globalSettings ?? Container.GetInstance(), diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 655dac8796..eaec8a24ff 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -178,6 +178,7 @@ + diff --git a/src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs index e92e72db77..33e2164a21 100644 --- a/src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs @@ -2,15 +2,23 @@ using Umbraco.Core.Models; using Umbraco.Web.Composing; using Umbraco.Web.Models.ContentEditing; +using Umbraco.Web.Routing; namespace Umbraco.Web.Models.Mapping { internal class RedirectUrlMapperProfile : Profile { + private readonly UrlProvider _urlProvider; + + public RedirectUrlMapperProfile(UrlProvider urlProvider) + { + _urlProvider = urlProvider; + } + public RedirectUrlMapperProfile() { CreateMap() - .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url))) + .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => _urlProvider.GetUrlFromRoute(item.ContentId, item.Url, null))) .ForMember(x => x.DestinationUrl, expression => expression.Ignore()) .ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key)); } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index fc95557dd1..37b8e97a28 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -163,7 +163,9 @@ namespace Umbraco.Web.PublishedCache.NuCache // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc - var route = (n?.Id.ToString(CultureInfo.InvariantCulture) ?? "") + path; + //prefix the root node id containing the domain if it exists (this is a standard way of creating route paths) + //and is done so that we know the ID of the domain node for the path + var route = (n?.Id.ToString(CultureInfo.InvariantCulture) ?? "") + path; return route; } diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 788a7a809b..0ea0c950da 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.Routing #region GetUrl /// - /// Gets the nice url of a published content. + /// Gets the url of a published content. /// /// The Umbraco context. /// The published content id. @@ -51,10 +51,10 @@ namespace Umbraco.Web.Routing // will not use cache if previewing var route = umbracoContext.ContentCache.GetRouteById(id, culture); - return GetUrlFromRoute(route, umbracoContext, id, current, mode); + return GetUrlFromRoute(route, umbracoContext, id, current, mode, culture); } - internal string GetUrlFromRoute(string route, UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode) + internal string GetUrlFromRoute(string route, UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture) { if (string.IsNullOrWhiteSpace(route)) { @@ -71,7 +71,7 @@ namespace Umbraco.Web.Routing var path = pos == 0 ? route : route.Substring(pos); var domainUri = pos == 0 ? null - : domainHelper.DomainForNode(int.Parse(route.Substring(0, pos)), current); + : domainHelper.DomainForNode(int.Parse(route.Substring(0, pos)), current, culture); // assemble the url from domainUri (maybe null) and path return AssembleUrl(domainUri, path, current, mode).ToString(); @@ -119,8 +119,7 @@ namespace Umbraco.Web.Routing var route = umbracoContext.ContentCache.GetRouteById(id, d?.Culture?.Name); if (route == null) continue; - //need to strip off the leading ID for the route - //TODO: Is there a nicer way to deal with this? + //need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned) var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); @@ -170,7 +169,7 @@ namespace Umbraco.Web.Routing { if (mode == UrlProviderMode.Auto) { - if (current != null && domainUri.Uri.GetLeftPart(UriPartial.Authority) == current.GetLeftPart(UriPartial.Authority)) + if (current != null && current.GetLeftPart(UriPartial.Path).InvariantStartsWith(domainUri.Uri.GetLeftPart(UriPartial.Path))) mode = UrlProviderMode.Relative; else mode = UrlProviderMode.Absolute; diff --git a/src/Umbraco.Web/Routing/DomainHelper.cs b/src/Umbraco.Web/Routing/DomainHelper.cs index ba7b59323b..db051c20c5 100644 --- a/src/Umbraco.Web/Routing/DomainHelper.cs +++ b/src/Umbraco.Web/Routing/DomainHelper.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web.Routing /// The domain and its uri, if any, that best matches the specified uri, else null. /// If at least a domain is set on the node then the method returns the domain that /// best matches the specified uri, else it returns null. - internal DomainAndUri DomainForNode(int nodeId, Uri current) + internal DomainAndUri DomainForNode(int nodeId, Uri current, string culture = null) { // be safe if (nodeId <= 0) @@ -45,7 +45,7 @@ namespace Umbraco.Web.Routing return null; // else filter - var domainAndUri = DomainForUri(domains, current, domainAndUris => _siteDomainHelper.MapDomain(current, domainAndUris)); + var domainAndUri = DomainForUri(domains, current, culture, domainAndUris => _siteDomainHelper.MapDomain(current, domainAndUris)); if (domainAndUri == null) throw new Exception("DomainForUri returned null."); @@ -108,14 +108,13 @@ namespace Umbraco.Web.Routing /// the right one, unless it is null, in which case the method returns null. /// The filter, if any, will be called only with a non-empty argument, and _must_ return something. /// - internal static DomainAndUri DomainForUri(IEnumerable domains, Uri current, Func filter = null) + internal static DomainAndUri DomainForUri(IEnumerable domains, Uri current, string culture = null, Func filter = null) { // sanitize the list to have proper uris for comparison (scheme, path end with /) // we need to end with / because example.com/foo cannot match example.com/foobar // we need to order so example.com/foo matches before example.com/ var domainsAndUris = domains .Where(d => d.IsWildcard == false) - //.Select(SanitizeForBackwardCompatibility) .Select(d => new DomainAndUri(d, current)) .OrderByDescending(d => d.Uri.ToString()) .ToArray(); @@ -126,8 +125,12 @@ namespace Umbraco.Web.Routing DomainAndUri domainAndUri; if (current == null) { - //get the default domain (there should be one) - domainAndUri = domainsAndUris.FirstOrDefault(x => x.IsDefault); + //get the default domain or the one matching the culture if specified + domainAndUri = domainsAndUris.FirstOrDefault(x => culture.IsNullOrWhiteSpace() ? x.IsDefault : x.Culture.Name.InvariantEquals(culture)); + + if (domainAndUri == null && !culture.IsNullOrWhiteSpace()) + throw new InvalidOperationException($"No domain was found by the specified culture '{culture}'"); + if (domainAndUri == null) domainAndUri = domainsAndUris.First(); // take the first one by default (what else can we do?) } @@ -138,13 +141,17 @@ namespace Umbraco.Web.Routing var currentWithSlash = current.EndPathWithSlash(); domainAndUri = domainsAndUris .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash)); - if (domainAndUri != null) return domainAndUri; + //is culture specified? if so this will need to match too + if (domainAndUri != null && (culture.IsNullOrWhiteSpace() || domainAndUri.Culture.Name.InvariantEquals(culture))) + return domainAndUri; // if none matches, try again without the port // ie current is www.example.com:1234/foo/bar, look for domain www.example.com domainAndUri = domainsAndUris .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash.WithoutPort())); - if (domainAndUri != null) return domainAndUri; + //is culture specified? if so this will need to match too + if (domainAndUri != null && (culture.IsNullOrWhiteSpace() || domainAndUri.Culture.Name.InvariantEquals(culture))) + return domainAndUri; // if none matches, then try to run the filter to pick a domain if (filter != null) @@ -170,7 +177,6 @@ namespace Umbraco.Web.Routing { return domains .Where(d => d.IsWildcard == false) - //.Select(SanitizeForBackwardCompatibility) .Select(d => new DomainAndUri(d, current)) .OrderByDescending(d => d.Uri.ToString()); } diff --git a/src/Umbraco.Web/Routing/UrlProvider.cs b/src/Umbraco.Web/Routing/UrlProvider.cs index 422fb4d4e7..98bd1b182d 100644 --- a/src/Umbraco.Web/Routing/UrlProvider.cs +++ b/src/Umbraco.Web/Routing/UrlProvider.cs @@ -216,12 +216,12 @@ namespace Umbraco.Web.Routing return url ?? "#"; // legacy wants this } - internal string GetUrlFromRoute(int id, string route) + internal string GetUrlFromRoute(int id, string route, string culture) { var provider = _urlProviders.OfType().FirstOrDefault(); var url = provider == null ? route // what else? - : provider.GetUrlFromRoute(route, UmbracoContext.Current, id, _umbracoContext.CleanedUmbracoUrl, Mode); + : provider.GetUrlFromRoute(route, UmbracoContext.Current, id, _umbracoContext.CleanedUmbracoUrl, Mode, culture); return url ?? "#"; } From 335cf656632dade7b0124691a31b04eec31d7e96 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 14:01:29 +1000 Subject: [PATCH 36/58] fixes more of my test logic --- src/Umbraco.Tests/Routing/UrlProviderTests.cs | 17 ++++++------ src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 5 ++-- src/Umbraco.Web/Routing/DomainHelper.cs | 27 ++++++++++++------- 3 files changed, 29 insertions(+), 20 deletions(-) diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs index 070c68468a..038211b86a 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -159,7 +159,7 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_For_Culture_Variant_With_Current_Url() { - const string currentUri = "http://example.com/fr/test"; + const string currentUri = "http://example.fr/test"; var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); @@ -180,8 +180,8 @@ namespace Umbraco.Tests.Routing if (contentId != 9876) return Enumerable.Empty(); return new[] { - new Domain(2, "example.com/en", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default - new Domain(3, "example.com/fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default + new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) }; }); @@ -201,8 +201,7 @@ namespace Umbraco.Tests.Routing var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR"); - //the current uri is the culture specific domain we want, so the result is a relative path since we are on the culture specific domain - Assert.AreEqual("/fr/home/test-fr/", url); + Assert.AreEqual("/home/test-fr/", url); } /// @@ -211,7 +210,7 @@ namespace Umbraco.Tests.Routing [Test] public void Get_Url_For_Culture_Variant_Non_Current_Url() { - const string currentUri = "http://example.com/en/test"; + const string currentUri = "http://example.us/test"; var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); @@ -232,8 +231,8 @@ namespace Umbraco.Tests.Routing if (contentId != 9876) return Enumerable.Empty(); return new[] { - new Domain(2, "example.com/en", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default - new Domain(3, "example.com/fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default + new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) }; }); @@ -254,7 +253,7 @@ namespace Umbraco.Tests.Routing var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR"); //the current uri is not the culture specific domain we want, so the result is an absolute path to the culture specific domain - Assert.AreEqual("http://example.com/fr/home/test-fr/", url); + Assert.AreEqual("http://example.fr/home/test-fr/", url); } [Test] diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 0ea0c950da..6a01250221 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -168,8 +168,9 @@ namespace Umbraco.Web.Routing else // a domain was found { if (mode == UrlProviderMode.Auto) - { - if (current != null && current.GetLeftPart(UriPartial.Path).InvariantStartsWith(domainUri.Uri.GetLeftPart(UriPartial.Path))) + { + //this check is a little tricky, we can't just compare domains + if (current != null && domainUri.Uri.GetLeftPart(UriPartial.Authority) == current.GetLeftPart(UriPartial.Authority)) mode = UrlProviderMode.Relative; else mode = UrlProviderMode.Absolute; diff --git a/src/Umbraco.Web/Routing/DomainHelper.cs b/src/Umbraco.Web/Routing/DomainHelper.cs index db051c20c5..76a0845113 100644 --- a/src/Umbraco.Web/Routing/DomainHelper.cs +++ b/src/Umbraco.Web/Routing/DomainHelper.cs @@ -125,6 +125,8 @@ namespace Umbraco.Web.Routing DomainAndUri domainAndUri; if (current == null) { + //match either by culture (if specified) or default + //get the default domain or the one matching the culture if specified domainAndUri = domainsAndUris.FirstOrDefault(x => culture.IsNullOrWhiteSpace() ? x.IsDefault : x.Culture.Name.InvariantEquals(culture)); @@ -133,25 +135,32 @@ namespace Umbraco.Web.Routing if (domainAndUri == null) domainAndUri = domainsAndUris.First(); // take the first one by default (what else can we do?) + } + else if (!culture.IsNullOrWhiteSpace()) + { + //match by culture + + domainAndUri = domainsAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(culture)); + if (domainAndUri == null) + throw new InvalidOperationException($"No domain was found by the specified culture '{culture}'"); + return domainAndUri; } else - { + { + //try to match by current, else filter + // look for the first domain that would be the base of the current url // ie current is www.example.com/foo/bar, look for domain www.example.com var currentWithSlash = current.EndPathWithSlash(); domainAndUri = domainsAndUris - .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash)); - //is culture specified? if so this will need to match too - if (domainAndUri != null && (culture.IsNullOrWhiteSpace() || domainAndUri.Culture.Name.InvariantEquals(culture))) - return domainAndUri; + .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash)); + if (domainAndUri != null) return domainAndUri; // if none matches, try again without the port // ie current is www.example.com:1234/foo/bar, look for domain www.example.com domainAndUri = domainsAndUris - .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash.WithoutPort())); - //is culture specified? if so this will need to match too - if (domainAndUri != null && (culture.IsNullOrWhiteSpace() || domainAndUri.Culture.Name.InvariantEquals(culture))) - return domainAndUri; + .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash.WithoutPort())); + if (domainAndUri != null) return domainAndUri; // if none matches, then try to run the filter to pick a domain if (filter != null) From f6984438a01fb8a25b95c2d7b13e3093d80461ae Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 15:26:50 +1000 Subject: [PATCH 37/58] Fixes cases where there are no domains assigned, ensures there can't be duplicate URLs returned to the UI --- .../PublishedCache/NuCache/ContentCache.cs | 6 ++-- src/Umbraco.Web/Routing/AliasUrlProvider.cs | 9 ++++-- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 32 ++++++++++--------- .../Routing/UrlProviderExtensions.cs | 9 ++++-- 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index 37b8e97a28..c7661a3f28 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -104,8 +104,8 @@ namespace Umbraco.Web.PublishedCache.NuCache // hideTopLevelNode = support legacy stuff, look for /*/path/to/node // else normal, look for /path/to/node content = hideTopLevelNode.Value - ? GetAtRoot(preview).SelectMany(x => x.Children).FirstOrDefault(x => x.UrlName == parts[0]) - : GetAtRoot(preview).FirstOrDefault(x => x.UrlName == parts[0]); + ? GetAtRoot(preview).SelectMany(x => x.Children).FirstOrDefault(x => x.GetUrlName(_localizationService, culture) == parts[0]) + : GetAtRoot(preview).FirstOrDefault(x => x.GetUrlName(_localizationService, culture) == parts[0]); content = FollowRoute(content, parts, 1, culture); } @@ -114,7 +114,7 @@ namespace Umbraco.Web.PublishedCache.NuCache // have to look for /foo (see note in ApplyHideTopLevelNodeFromPath). if (content == null && hideTopLevelNode.Value && parts.Length == 1) { - content = GetAtRoot(preview).FirstOrDefault(x => x.UrlName == parts[0]); + content = GetAtRoot(preview).FirstOrDefault(x => x.GetUrlName(_localizationService, culture) == parts[0]); } return content; diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index 5e3f8ea919..4b7cb48add 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -90,8 +90,12 @@ namespace Umbraco.Web.Routing if (domainUris == null) { - var path = "/" + node.Value(Constants.Conventions.Content.UrlAlias); - var uri = new Uri(path, UriKind.Relative); + var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias); + if (string.IsNullOrWhiteSpace(umbracoUrlName)) + return Enumerable.Empty(); + + var path = "/" + umbracoUrlName; + var uri = new Uri(path, UriKind.Relative); return new[] { UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString() }; } else @@ -107,7 +111,6 @@ namespace Umbraco.Web.Routing result.Add(UriUtility.UriFromUmbraco(uri, _globalSettings, _requestConfig).ToString()); } } - return result; } } diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 6a01250221..e09f343555 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -94,23 +94,25 @@ namespace Umbraco.Web.Routing /// public virtual IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, Uri current) { - var node = umbracoContext.ContentCache.GetById(id); + //get the invariant route for this item, this will give us the Id of it's domain node if one is assigned + var invariantRoute = umbracoContext.ContentCache.GetRouteById(id); + + if (string.IsNullOrWhiteSpace(invariantRoute)) + { + _logger.Debug(() => $"Couldn't find any page with nodeId={id}. This is most likely caused by the page not being published."); + return null; + } + var domainHelper = umbracoContext.GetDomainHelper(_siteDomainHelper); - var n = node; - var domainUris = domainHelper.DomainsForNode(n.Id, current, false); - while (domainUris == null && n != null) // n is null at root - { - // move to parent node - n = n.Parent; - domainUris = n == null ? null : domainHelper.DomainsForNode(n.Id, current); - } + // extract domainUri and path + // route is / or / + var pos = invariantRoute.IndexOf('/'); + var path = pos == 0 ? invariantRoute : invariantRoute.Substring(pos); + var domainUris = pos == 0 ? null : domainHelper.DomainsForNode(int.Parse(invariantRoute.Substring(0, pos)), current); - if (domainUris == null) - { - //there are no domains, exit + if (domainUris ==null) return Enumerable.Empty(); - } var result = new List(); foreach (var d in domainUris) @@ -120,8 +122,8 @@ namespace Umbraco.Web.Routing if (route == null) continue; //need to strip off the leading ID for the route if it exists (occurs if the route is for a node with a domain assigned) - var pos = route.IndexOf('/'); - var path = pos == 0 ? route : route.Substring(pos); + pos = route.IndexOf('/'); + path = pos == 0 ? route : route.Substring(pos); var uri = new Uri(CombinePaths(d.Uri.GetLeftPart(UriPartial.Path), path)); uri = UriUtility.UriFromUmbraco(uri, _globalSettings, _requestSettings); diff --git a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs index a71bb51ddc..f13e02381f 100644 --- a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs +++ b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs @@ -29,7 +29,7 @@ namespace Umbraco.Web.Routing if (contentService == null) throw new ArgumentNullException(nameof(contentService)); if (logger == null) throw new ArgumentNullException(nameof(logger)); - var urls = new List(); + var urls = new HashSet(); if (content.Published == false) { @@ -104,8 +104,11 @@ namespace Umbraco.Web.Routing } else { - urls.Add(url); - urls.AddRange(urlProvider.GetOtherUrls(content.Id)); + urls.Add(url); + foreach(var otherUrl in urlProvider.GetOtherUrls(content.Id)) + { + urls.Add(otherUrl); + } } } return urls; From 5b555d35d3bf33b5e642e714e46007f3820669f4 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 27 Apr 2018 15:35:11 +1000 Subject: [PATCH 38/58] adds test --- src/Umbraco.Tests/Routing/UrlProviderTests.cs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs index 038211b86a..3b4dd5d069 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -153,6 +153,46 @@ namespace Umbraco.Tests.Routing Assert.AreEqual(niceUrlMatch, result); } + [Test] + public void Get_Url_For_Culture_Variant_Without_Domains_Non_Current_Url() + { + const string currentUri = "http://example.us/test"; + + var globalSettings = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container + globalSettings.Setup(x => x.UseDirectoryUrls).Returns(true); + globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); + SettingsForTests.ConfigureSettings(globalSettings.Object); + + var requestMock = Mock.Get(_umbracoSettings.RequestHandler); + requestMock.Setup(x => x.UseDomainPrefixes).Returns(false); + + var publishedContentCache = new Mock(); + publishedContentCache.Setup(x => x.GetRouteById(1234, "fr-FR")) + .Returns("9876/home/test-fr"); //prefix with the root id node with the domain assigned as per the umbraco standard + + var domainCache = new Mock(); + domainCache.Setup(x => x.GetAssigned(It.IsAny(), false)) + .Returns((int contentId, bool includeWildcards) => Enumerable.Empty()); + + var snapshot = Mock.Of(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object); + + var snapshotService = new Mock(); + snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())) + .Returns(snapshot); + + var umbracoContext = GetUmbracoContext(currentUri, umbracoSettings: _umbracoSettings, + urlProviders: new[] { + new DefaultUrlProvider(_umbracoSettings.RequestHandler, Logger, globalSettings.Object, new SiteDomainHelper()) + }, + globalSettings: globalSettings.Object, + snapshotService: snapshotService.Object); + + //even though we are asking for a specific culture URL, there are no domains assigned so all that can be returned is a normal relative url. + var url = umbracoContext.UrlProvider.GetUrl(1234, "fr-FR"); + + Assert.AreEqual("/home/test-fr/", url); + } + /// /// This tests DefaultUrlProvider.GetUrl with a specific culture when the current URL is the culture specific domain /// From dbad0d261e4b471e82da35949a6393d0b883e204 Mon Sep 17 00:00:00 2001 From: Simon Dingley Date: Fri, 27 Apr 2018 16:18:25 +0100 Subject: [PATCH 39/58] Fixes U4-8516 Copied node now sets the current user as the creator of the new node. --- src/Umbraco.Web/Editors/ContentController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index da5e0c3a3b..84acff37f8 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -565,7 +565,7 @@ namespace Umbraco.Web.Editors { var toCopy = ValidateMoveOrCopy(copy); - var c = Services.ContentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive); + var c = Services.ContentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, Security.CurrentUser.Id); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(c.Path, Encoding.UTF8, "application/json"); From 9407f755221894ac662fc40657dcd687279ce0f6 Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 27 Apr 2018 13:20:22 +0200 Subject: [PATCH 40/58] Fix importing test --- .../Importing/StandardMvc-Package.xml | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Umbraco.Tests/Services/Importing/StandardMvc-Package.xml b/src/Umbraco.Tests/Services/Importing/StandardMvc-Package.xml index 9a776805e9..2b2c8da067 100644 --- a/src/Umbraco.Tests/Services/Importing/StandardMvc-Package.xml +++ b/src/Umbraco.Tests/Services/Importing/StandardMvc-Package.xml @@ -1099,7 +1099,7 @@ Google Maps - A map macro that you can use within Rich Text Areas Articles SW_Master - ClientAreas SW_Master - x.IsVisible() && x.TemplateId > 0 && Umbraco.MemberHasAccess(x.Id, x.Path)); @@ -1238,7 +1238,7 @@ Google Maps - A map macro that you can use within Rich Text Areas Contact SW_Master - Home SW_Master - Login SW_Master - Search SW_Master - Sitemap SW_Master - StandardPage SW_Master - SW_Master SW_Master - /usercontrols/StandardWebsiteInstall.ascx - \ No newline at end of file + From dbf1b1e0d4601d9994472d56e47595b766710c46 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 26 Apr 2018 16:03:08 +0200 Subject: [PATCH 41/58] Refactor DomainHelper --- src/Umbraco.Core/Models/Content.cs | 6 +- src/Umbraco.Core/Models/DomainExtensions.cs | 22 -- .../Repositories/ILanguageRepository.cs | 29 +++ .../Implement/LanguageRepository.cs | 34 +++ .../Services/ILocalizationService.cs | 31 ++- .../Services/Implement/LocalizationService.cs | 27 +++ .../Services/LocalizationServiceExtensions.cs | 36 --- src/Umbraco.Core/StringExtensions.cs | 6 + src/Umbraco.Core/Umbraco.Core.csproj | 2 - .../Routing/ContentFinderByUrlTests.cs | 4 +- .../Routing/SiteDomainHelperTests.cs | 111 +++++----- src/Umbraco.Tests/Routing/UrlProviderTests.cs | 10 +- src/Umbraco.Web/Editors/ContentController.cs | 2 +- .../PublishedCache/IDomainCache.cs | 1 + .../PublishedCache/NuCache/DomainCache.cs | 5 +- .../NuCache/PublishedSnapshotService.cs | 22 +- .../XmlPublishedCache/DomainCache.cs | 10 +- src/Umbraco.Web/PublishedContentExtensions.cs | 98 ++++---- src/Umbraco.Web/Routing/DefaultUrlProvider.cs | 4 +- src/Umbraco.Web/Routing/Domain.cs | 9 +- src/Umbraco.Web/Routing/DomainHelper.cs | 209 +++++++++++------- src/Umbraco.Web/Routing/ISiteDomainHelper.cs | 22 +- src/Umbraco.Web/Routing/IUrlProvider.cs | 1 + src/Umbraco.Web/Routing/PublishedRouter.cs | 9 +- src/Umbraco.Web/Routing/SiteDomainHelper.cs | 118 ++++------ src/Umbraco.Web/Routing/UrlProvider.cs | 2 +- .../Trees/ContentTreeControllerBase.cs | 4 +- src/Umbraco.Web/UmbracoContext.cs | 34 ++- 28 files changed, 493 insertions(+), 375 deletions(-) delete mode 100644 src/Umbraco.Core/Models/DomainExtensions.cs delete mode 100644 src/Umbraco.Core/Services/LocalizationServiceExtensions.cs diff --git a/src/Umbraco.Core/Models/Content.cs b/src/Umbraco.Core/Models/Content.cs index 6b8732e70c..8bfb5718a2 100644 --- a/src/Umbraco.Core/Models/Content.cs +++ b/src/Umbraco.Core/Models/Content.cs @@ -271,7 +271,7 @@ namespace Umbraco.Core.Models } /// - public IEnumerable PublishedCultures => _publishInfos?.Keys; + public IEnumerable PublishedCultures => _publishInfos?.Keys ?? Enumerable.Empty(); /// public bool IsCultureEdited(string culture) @@ -350,8 +350,8 @@ namespace Umbraco.Core.Models { var name = GetName(culture); if (string.IsNullOrWhiteSpace(name)) - return false; //fixme this should return an attempt with error results - + return false; //fixme this should return an attempt with error results + SetPublishInfos(culture, name, DateTime.Now); } diff --git a/src/Umbraco.Core/Models/DomainExtensions.cs b/src/Umbraco.Core/Models/DomainExtensions.cs deleted file mode 100644 index 616685b6b9..0000000000 --- a/src/Umbraco.Core/Models/DomainExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Umbraco.Core.Services; - -namespace Umbraco.Core.Models -{ - public static class DomainExtensions - { - /// - /// Returns ture if the has a culture code equal to the default language specified - /// - /// - /// - /// - public static bool IsDefaultDomain(this IDomain domain, ILocalizationService localizationService) - { - var defaultLang = localizationService.GetDefaultVariantLanguage(); - if (defaultLang == null) - return false; //if for some reason a null value is returned (i.e. no languages or based on mock unit test data), then assume false - - return domain.LanguageIsoCode == defaultLang.CultureName; - } - } -} diff --git a/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs index 5831fcc7e4..b86898f97a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ILanguageRepository.cs @@ -6,7 +6,36 @@ namespace Umbraco.Core.Persistence.Repositories { ILanguage GetByIsoCode(string isoCode); + /// + /// Gets a language identifier from its ISO code. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// int? GetIdByIsoCode(string isoCode); + + /// + /// Gets a language ISO code from its identifier. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// string GetIsoCodeById(int? id); + + /// + /// Gets the default language ISO code. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// + string GetDefaultIsoCode(); + + /// + /// Gets the default language identifier. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// + int? GetDefaultId(); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs index 44a1ff6eeb..8e42ee460b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs @@ -242,5 +242,39 @@ namespace Umbraco.Core.Persistence.Repositories.Implement throw new ArgumentException($"Id {id} does not correspond to an existing language.", nameof(id)); return null; } + + public string GetDefaultIsoCode() + { + return GetDefault()?.IsoCode; + } + + public int? GetDefaultId() + { + return GetDefault()?.Id; + } + + // do NOT leak that language, it's not deep-cloned! + private ILanguage GetDefault() + { + // FIXME + var temp = SqlContext.Sql(); + if (temp == null) return null; + + // get all cached, non-cloned + var all = TypedCachePolicy.GetAllCached(PerformGetAll); + + ILanguage first = null; + foreach (var language in all) + { + // if one language is default, return + if (language.IsDefaultVariantLanguage) + return language; + // keep track of language with lowest id + if (first == null || language.Id < first.Id) + first = language; + } + + return first; + } } } diff --git a/src/Umbraco.Core/Services/ILocalizationService.cs b/src/Umbraco.Core/Services/ILocalizationService.cs index d6eb3f24b4..aedf84f804 100644 --- a/src/Umbraco.Core/Services/ILocalizationService.cs +++ b/src/Umbraco.Core/Services/ILocalizationService.cs @@ -111,10 +111,37 @@ namespace Umbraco.Core.Services ILanguage GetLanguageByIsoCode(string isoCode); /// - /// Gets a language identifier by its iso code. + /// Gets a language identifier from its ISO code. /// - int? GetLanguageIdByIsoCode(string isoCode); + /// + /// This can be optimized and bypass all deep cloning. + /// + int? GetLanguageIdByIsoCode(string isoCode); + /// + /// Gets a language ISO code from its identifier. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// + string GetLanguageIsoCodeById(int id); + + /// + /// Gets the default language ISO code. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// + string GetDefaultLanguageIsoCode(); + + /// + /// Gets the default language identifier. + /// + /// + /// This can be optimized and bypass all deep cloning. + /// + int? GetDefaultLanguageId(); + /// /// Gets all available languages /// diff --git a/src/Umbraco.Core/Services/Implement/LocalizationService.cs b/src/Umbraco.Core/Services/Implement/LocalizationService.cs index 976c65e3e8..663ecf586c 100644 --- a/src/Umbraco.Core/Services/Implement/LocalizationService.cs +++ b/src/Umbraco.Core/Services/Implement/LocalizationService.cs @@ -312,6 +312,33 @@ namespace Umbraco.Core.Services.Implement } } + /// + public string GetLanguageIsoCodeById(int id) + { + using (ScopeProvider.CreateScope(autoComplete: true)) + { + return _languageRepository.GetIsoCodeById(id); + } + } + + /// + public string GetDefaultLanguageIsoCode() + { + using (ScopeProvider.CreateScope(autoComplete: true)) + { + return _languageRepository.GetDefaultIsoCode(); + } + } + + /// + public int? GetDefaultLanguageId() + { + using (ScopeProvider.CreateScope(autoComplete: true)) + { + return _languageRepository.GetDefaultId(); + } + } + /// /// Gets all available languages /// diff --git a/src/Umbraco.Core/Services/LocalizationServiceExtensions.cs b/src/Umbraco.Core/Services/LocalizationServiceExtensions.cs deleted file mode 100644 index a597b64f3b..0000000000 --- a/src/Umbraco.Core/Services/LocalizationServiceExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Linq; -using Umbraco.Core.Models; - -namespace Umbraco.Core.Services -{ - public static class LocalizationServiceExtensions - { - /// - /// Returns the configured default variant language - /// - /// - /// - public static ILanguage GetDefaultVariantLanguage(this ILocalizationService service) - { - var langs = service.GetAllLanguages().OrderBy(x => x.Id).ToList(); - - if (langs.Count == 0) return null; - - //if there's only one language, by default it is the default - if (langs.Count == 1) - { - langs[0].IsDefaultVariantLanguage = true; - langs[0].Mandatory = true; - return langs[0]; - } - - var foundDefault = langs.FirstOrDefault(x => x.IsDefaultVariantLanguage); - if (foundDefault != null) return foundDefault; - - //if no language has the default flag, then the defaul language is the one with the lowest id - langs[0].IsDefaultVariantLanguage = true; - langs[0].Mandatory = true; - return langs[0]; - } - } -} diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 0985e0521c..afdb4c3646 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -1487,5 +1487,11 @@ namespace Umbraco.Core guid[left] = guid[right]; guid[right] = temp; } + + /// + /// Turns an null-or-whitespace string into a null string. + /// + public static string NullEmpty(this string text) + => string.IsNullOrWhiteSpace(text) ? null : text; } } diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 4d30318a15..2a4a79180b 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -351,7 +351,6 @@ - @@ -1420,7 +1419,6 @@ - diff --git a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs index 108abfe446..8b591dfb84 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs @@ -124,7 +124,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/")); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/")); var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); @@ -154,7 +154,7 @@ namespace Umbraco.Tests.Routing var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); - frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false, true), new Uri("http://mysite/æøå")); + frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå")); var lookup = new ContentFinderByUrl(Logger); var result = lookup.TryFindContent(frequest); diff --git a/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs b/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs index fea8948b8e..d9760f58c1 100644 --- a/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs +++ b/src/Umbraco.Tests/Routing/SiteDomainHelperTests.cs @@ -21,6 +21,9 @@ namespace Umbraco.Tests.Routing SiteDomainHelper.Clear(); // assuming this works! } + private static CultureInfo CultureFr = CultureInfo.GetCultureInfo("fr-fr"); + private static CultureInfo CultureUk = CultureInfo.GetCultureInfo("en-uk"); + [Test] public void AddSites() { @@ -188,38 +191,38 @@ namespace Umbraco.Tests.Routing var current = new Uri("https://www.domain1.com/foo/bar"); var domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, true), - new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, false), + new Domain(1, "domain2.com", -1, CultureFr, false), + new Domain(1, "domain1.com", -1, CultureUk, false), }); - var output = helper.MapDomain(current, domainAndUris).Uri.ToString(); + var output = helper.MapDomain(domainAndUris, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); // will pick it all right current = new Uri("https://domain1.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), - new Domain(1, "https://domain2.com", -1, CultureInfo.CurrentCulture, false, false) + new Domain(1, "https://domain1.com", -1, CultureFr, false), + new Domain(1, "https://domain2.com", -1, CultureUk, false) }); - output = helper.MapDomain(current, domainAndUris).Uri.ToString(); + output = helper.MapDomain(domainAndUris, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); current = new Uri("https://domain1.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), - new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false, false) + new Domain(1, "https://domain1.com", -1, CultureFr, false), + new Domain(1, "https://domain4.com", -1, CultureUk, false) }); - output = helper.MapDomain(current, domainAndUris).Uri.ToString(); + output = helper.MapDomain(domainAndUris, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain1.com/", output); current = new Uri("https://domain4.com/foo/bar"); domainAndUris = DomainAndUris(current, new[] { - new Domain(1, "https://domain1.com", -1, CultureInfo.CurrentCulture, false, true), - new Domain(1, "https://domain4.com", -1, CultureInfo.CurrentCulture, false, false) + new Domain(1, "https://domain1.com", -1, CultureFr, false), + new Domain(1, "https://domain4.com", -1, CultureUk, false) }); - output = helper.MapDomain(current, domainAndUris).Uri.ToString(); + output = helper.MapDomain(domainAndUris, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("https://domain4.com/", output); } @@ -241,22 +244,22 @@ namespace Umbraco.Tests.Routing // so we'll get current // var current = new Uri("http://domain1.com/foo/bar"); - var output = helper.MapDomain(current, new[] + var output = helper.MapDomain(new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), - }).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureFr, false), current), + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureUk, false), current), + }, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.com/", output); // current is a site1 uri, domains do not contain current // so we'll get the corresponding site1 domain // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomain(current, new[] + output = helper.MapDomain(new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), - new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false, false), current) - }).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureFr, false), current), + new DomainAndUri(new Domain(1, "domain2.net", -1, CultureUk, false), current) + }, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); // current is a site1 uri, domains do not contain current @@ -264,11 +267,11 @@ namespace Umbraco.Tests.Routing // order does not matter // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomain(current, new[] + output = helper.MapDomain(new[] { - new DomainAndUri(new Domain(1, "domain2.net", -1, CultureInfo.CurrentCulture, false, true), current), - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, false), current) - }).Uri.ToString(); + new DomainAndUri(new Domain(1, "domain2.net", -1, CultureFr, false), current), + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureUk, false), current) + }, current, CultureFr.Name, CultureFr.Name).Uri.ToString(); Assert.AreEqual("http://domain1.net/", output); } @@ -291,14 +294,14 @@ namespace Umbraco.Tests.Routing // current is a site1 uri, domains contains current // var current = new Uri("http://domain1.com/foo/bar"); - var output = helper.MapDomains(current, new[] + var output = helper.MapDomains(new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) - }, true).ToArray(); + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureFr, false), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureUk, false), current), // yes: same site (though bogus setup) + }, current, true, CultureFr.Name, CultureFr.Name).ToArray(); Assert.AreEqual(1, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); @@ -306,14 +309,14 @@ namespace Umbraco.Tests.Routing // current is a site1 uri, domains does not contain current // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(current, new[] + output = helper.MapDomains(new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) - }, true).ToArray(); + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureFr, false), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureUk, false), current), // yes: same site (though bogus setup) + }, current, true, CultureFr.Name, CultureFr.Name).ToArray(); Assert.AreEqual(1, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); @@ -324,15 +327,15 @@ namespace Umbraco.Tests.Routing // current is a site1 uri, domains contains current // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(current, new[] + output = helper.MapDomains(new[] { - new DomainAndUri(new Domain(1, "domain1.com", -1, CultureInfo.CurrentCulture, false, true), current), // no: current + what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) - }, true).ToArray(); + new DomainAndUri(new Domain(1, "domain1.com", -1, CultureFr, false), current), // no: current + what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureUk, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, CultureUk, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureUk, false), current), // yes: same site (though bogus setup) + }, current, true, CultureFr.Name, CultureFr.Name).ToArray(); Assert.AreEqual(3, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); @@ -342,15 +345,15 @@ namespace Umbraco.Tests.Routing // current is a site1 uri, domains does not contain current // current = new Uri("http://domain1.com/foo/bar"); - output = helper.MapDomains(current, new[] + output = helper.MapDomains(new[] { - new DomainAndUri(new Domain(1, "domain1.net", -1, CultureInfo.CurrentCulture, false, true), current), // no: what MapDomain would pick - new DomainAndUri(new Domain(1, "domain2.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain3.com", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain3.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: bound site - new DomainAndUri(new Domain(1, "domain4.com", -1, CultureInfo.CurrentCulture, false, false), current), // no: not same site - new DomainAndUri(new Domain(1, "domain1.org", -1, CultureInfo.CurrentCulture, false, false), current), // yes: same site (though bogus setup) - }, true).ToArray(); + new DomainAndUri(new Domain(1, "domain1.net", -1, CultureFr, false), current), // no: what MapDomain would pick + new DomainAndUri(new Domain(1, "domain2.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain3.com", -1, CultureUk, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain3.org", -1, CultureUk, false), current), // yes: bound site + new DomainAndUri(new Domain(1, "domain4.com", -1, CultureUk, false), current), // no: not same site + new DomainAndUri(new Domain(1, "domain1.org", -1, CultureUk, false), current), // yes: same site (though bogus setup) + }, current, true, CultureFr.Name, CultureFr.Name).ToArray(); Assert.AreEqual(3, output.Count()); Assert.Contains("http://domain1.org/", output.Select(d => d.Uri.ToString()).ToArray()); diff --git a/src/Umbraco.Tests/Routing/UrlProviderTests.cs b/src/Umbraco.Tests/Routing/UrlProviderTests.cs index 3b4dd5d069..185812002d 100644 --- a/src/Umbraco.Tests/Routing/UrlProviderTests.cs +++ b/src/Umbraco.Tests/Routing/UrlProviderTests.cs @@ -220,10 +220,11 @@ namespace Umbraco.Tests.Routing if (contentId != 9876) return Enumerable.Empty(); return new[] { - new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default - new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false), //default + new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false) }; }); + domainCache.Setup(x => x.DefaultCulture).Returns(CultureInfo.GetCultureInfo("en-US").Name); var snapshot = Mock.Of(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object); @@ -271,10 +272,11 @@ namespace Umbraco.Tests.Routing if (contentId != 9876) return Enumerable.Empty(); return new[] { - new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false, true), //default - new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false, true) + new Domain(2, "example.us", 9876, CultureInfo.GetCultureInfo("en-US"), false), //default + new Domain(3, "example.fr", 9876, CultureInfo.GetCultureInfo("fr-FR"), false) }; }); + domainCache.Setup(x => x.DefaultCulture).Returns(CultureInfo.GetCultureInfo("en-US").Name); var snapshot = Mock.Of(x => x.Content == publishedContentCache.Object && x.Domains == domainCache.Object); diff --git a/src/Umbraco.Web/Editors/ContentController.cs b/src/Umbraco.Web/Editors/ContentController.cs index ffaffa05f4..f1528c7fe6 100644 --- a/src/Umbraco.Web/Editors/ContentController.cs +++ b/src/Umbraco.Web/Editors/ContentController.cs @@ -1191,7 +1191,7 @@ namespace Umbraco.Web.Editors //sent up, then it means that the user is editing the default variant language. if (culture == null && content.HasPropertyTypeVaryingByCulture()) { - culture = Services.LocalizationService.GetDefaultVariantLanguage().IsoCode; + culture = Services.LocalizationService.GetDefaultLanguageIsoCode(); } var display = ContextMapper.Map(content, UmbracoContext, diff --git a/src/Umbraco.Web/PublishedCache/IDomainCache.cs b/src/Umbraco.Web/PublishedCache/IDomainCache.cs index 113533f500..bace337862 100644 --- a/src/Umbraco.Web/PublishedCache/IDomainCache.cs +++ b/src/Umbraco.Web/PublishedCache/IDomainCache.cs @@ -7,5 +7,6 @@ namespace Umbraco.Web.PublishedCache { IEnumerable GetAll(bool includeWildcards); IEnumerable GetAssigned(int contentId, bool includeWildcards); + string DefaultCulture { get; } } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DomainCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/DomainCache.cs index 3b2165c00a..896a04a0b3 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DomainCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DomainCache.cs @@ -8,9 +8,10 @@ namespace Umbraco.Web.PublishedCache.NuCache { private readonly SnapDictionary.Snapshot _snapshot; - public DomainCache(SnapDictionary.Snapshot snapshot) + public DomainCache(SnapDictionary.Snapshot snapshot, string defaultCulture) { _snapshot = snapshot; + DefaultCulture = defaultCulture; // capture - fast } public IEnumerable GetAll(bool includeWildcards) @@ -30,5 +31,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (includeWildcards == false) list = list.Where(x => x.IsWildcard == false); return list; } + + public string DefaultCulture { get; } } } diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index e611a738e5..923502bea2 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -487,7 +487,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var domains = _serviceContext.DomainService.GetAll(true); foreach (var domain in domains .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_serviceContext.LocalizationService)))) + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard))) { _domainStore.Set(domain.Id, domain); } @@ -831,7 +831,7 @@ namespace Umbraco.Web.PublishedCache.NuCache if (domain.RootContentId.HasValue == false) continue; // anomaly if (domain.LanguageIsoCode.IsNullOrWhiteSpace()) continue; // anomaly var culture = CultureInfo.GetCultureInfo(domain.LanguageIsoCode); - _domainStore.Set(domain.Id, new Domain(domain.Id, domain.DomainName, domain.RootContentId.Value, culture, domain.IsWildcard, domain.IsDefaultDomain(_serviceContext.LocalizationService))); + _domainStore.Set(domain.Id, new Domain(domain.Id, domain.DomainName, domain.RootContentId.Value, culture, domain.IsWildcard)); break; } } @@ -1014,7 +1014,8 @@ namespace Umbraco.Web.PublishedCache.NuCache var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); - var domainCache = new DomainCache(domainSnap); + var defaultCulture = _serviceContext.LocalizationService.GetDefaultLanguageIsoCode(); // capture - fast + var domainCache = new DomainCache(domainSnap, defaultCulture); var domainHelper = new DomainHelper(domainCache, _siteDomainHelper); return new PublishedSnapshot.PublishedSnapshotElements @@ -1214,12 +1215,17 @@ namespace Umbraco.Web.PublishedCache.NuCache } var cultureData = new Dictionary(); - if (content.Names != null) + + // fixme refactor!!! + var names = content is IContent document + ? (published + ? document.PublishNames + : document.Names) + : content.Names; + + foreach (var (culture, name) in names) { - foreach (var name in content.Names) - { - cultureData[name.Key] = new CultureVariation { Name = name.Value }; - } + cultureData[culture] = new CultureVariation { Name = name }; } //the dictionary that will be serialized diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs index 051c333762..64c1d80852 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs @@ -4,33 +4,33 @@ using System.Linq; using Umbraco.Web.Routing; using Umbraco.Core; using Umbraco.Core.Services; -using Umbraco.Core.Models; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class DomainCache : IDomainCache { private readonly IDomainService _domainService; - private readonly ILocalizationService _localizationService; public DomainCache(IDomainService domainService, ILocalizationService localizationService) { _domainService = domainService; - _localizationService = localizationService; + DefaultCulture = localizationService.GetDefaultLanguageIsoCode(); // capture - fast } public IEnumerable GetAll(bool includeWildcards) { return _domainService.GetAll(includeWildcards) .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_localizationService))); + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard)); } public IEnumerable GetAssigned(int contentId, bool includeWildcards) { return _domainService.GetAssignedDomains(contentId, includeWildcards) .Where(x => x.RootContentId.HasValue && x.LanguageIsoCode.IsNullOrWhiteSpace() == false) - .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard, x.IsDefaultDomain(_localizationService))); + .Select(x => new Domain(x.Id, x.DomainName, x.RootContentId.Value, CultureInfo.GetCultureInfo(x.LanguageIsoCode), x.IsWildcard)); } + + public string DefaultCulture { get; } } } diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index d11a168b88..ace05c33f5 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -222,8 +222,8 @@ namespace Umbraco.Web #region Search public static IEnumerable Search(this IPublishedContent content, string term, bool useWildCards = true, string indexName = null) - { - //TODO: we should pass in the IExamineManager? + { + //TODO: we should pass in the IExamineManager? var searcher = string.IsNullOrEmpty(indexName) ? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer) @@ -249,7 +249,7 @@ namespace Umbraco.Web public static IEnumerable SearchChildren(this IPublishedContent content, string term, bool useWildCards = true, string indexName = null) { - //TODO: we should pass in the IExamineManager? + //TODO: we should pass in the IExamineManager? var searcher = string.IsNullOrEmpty(indexName) ? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer) @@ -270,10 +270,10 @@ namespace Umbraco.Web public static IEnumerable Search(this IPublishedContent content, Examine.SearchCriteria.ISearchCriteria criteria, Examine.ISearcher searchProvider = null) { - //TODO: we should pass in the IExamineManager? + //TODO: we should pass in the IExamineManager? + + var s = searchProvider ?? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer); - var s = searchProvider ?? Examine.ExamineManager.Instance.GetSearcher(Constants.Examine.ExternalIndexer); - var results = s.Search(criteria); return results.ToPublishedSearchResults(UmbracoContext.Current.ContentCache); } @@ -1116,12 +1116,12 @@ namespace Umbraco.Web return new DataTable(); //no children found //use new utility class to create table so that we don't have to maintain code in many places, just one - var dt = Core.DataTableExtensions.GenerateDataTable( - //pass in the alias of the first child node since this is the node type we're rendering headers for - firstNode.DocumentTypeAlias, - //pass in the callback to extract the Dictionary of all defined aliases to their names - alias => GetPropertyAliasesAndNames(services, alias), - //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. + var dt = Core.DataTableExtensions.GenerateDataTable( + //pass in the alias of the first child node since this is the node type we're rendering headers for + firstNode.DocumentTypeAlias, + //pass in the callback to extract the Dictionary of all defined aliases to their names + alias => GetPropertyAliasesAndNames(services, alias), + //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. () => { //create all row data @@ -1222,51 +1222,51 @@ namespace Umbraco.Web private static Dictionary GetAliasesAndNames(IContentTypeBase contentType) { return contentType.PropertyTypes.ToDictionary(x => x.Alias, x => x.Name); - } - + } + #endregion - + #region Culture - - //TODO: Not used - ///// - ///// Gets the culture that would be selected to render a specified content, - ///// within the context of a specified current request. - ///// - ///// The content. - ///// The request Uri. - ///// The culture that would be selected to render the content. - //public static CultureInfo GetCulture(this IPublishedContent content, Uri current = null) - //{ - // return Models.ContentExtensions.GetCulture(UmbracoContext.Current, - // Current.Services.DomainService, - // Current.Services.LocalizationService, - // Current.Services.ContentService, - // content.Id, content.Path, - // current); - //} - + + //TODO: Not used + ///// + ///// Gets the culture that would be selected to render a specified content, + ///// within the context of a specified current request. + ///// + ///// The content. + ///// The request Uri. + ///// The culture that would be selected to render the content. + //public static CultureInfo GetCulture(this IPublishedContent content, Uri current = null) + //{ + // return Models.ContentExtensions.GetCulture(UmbracoContext.Current, + // Current.Services.DomainService, + // Current.Services.LocalizationService, + // Current.Services.ContentService, + // content.Id, content.Path, + // current); + //} + /// /// Return the URL name for the based on the culture specified or default culture defined /// /// /// /// - /// - public static string GetUrlName(this IPublishedContent content, ILocalizationService localizationService, string culture = null) - { - if (content.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) - { - var cultureCode = culture ?? localizationService.GetDefaultVariantLanguage()?.IsoCode; - if (cultureCode != null && content.CultureNames.TryGetValue(cultureCode, out var cultureName)) - { - return cultureName.UrlName; - } - } - - //if we get here, the content type is invariant or we don't have access to a usable culture code - return content.UrlName; - } + /// + public static string GetUrlName(this IPublishedContent content, ILocalizationService localizationService, string culture = null) + { + if (content.ContentType.Variations.HasFlag(ContentVariation.CultureNeutral)) + { + var cultureCode = culture ?? localizationService.GetDefaultLanguageIsoCode(); + if (cultureCode != null && content.CultureNames.TryGetValue(cultureCode, out var cultureName)) + { + return cultureName.UrlName; + } + } + + //if we get here, the content type is invariant or we don't have access to a usable culture code + return content.UrlName; + } #endregion } diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index e09f343555..37d38d521e 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -38,6 +38,7 @@ namespace Umbraco.Web.Routing /// The published content id. /// The current absolute url. /// The url mode. + /// The culture. /// The url for the published content. /// /// The url is absolute or relative depending on mode and on current. @@ -45,8 +46,7 @@ namespace Umbraco.Web.Routing /// public virtual string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null) { - if (!current.IsAbsoluteUri) - throw new ArgumentException("Current url must be absolute.", "current"); + if (!current.IsAbsoluteUri) throw new ArgumentException("Current url must be absolute.", nameof(current)); // will not use cache if previewing var route = umbracoContext.ContentCache.GetRouteById(id, culture); diff --git a/src/Umbraco.Web/Routing/Domain.cs b/src/Umbraco.Web/Routing/Domain.cs index 03048f0dd5..b9116c6b51 100644 --- a/src/Umbraco.Web/Routing/Domain.cs +++ b/src/Umbraco.Web/Routing/Domain.cs @@ -15,14 +15,13 @@ namespace Umbraco.Web.Routing /// The identifier of the content which supports the domain. /// The culture of the domain. /// A value indicating whether the domain is a wildcard domain. - public Domain(int id, string name, int contentId, CultureInfo culture, bool isWildcard, bool isDefault) + public Domain(int id, string name, int contentId, CultureInfo culture, bool isWildcard) { Id = id; Name = name; ContentId = contentId; Culture = culture; IsWildcard = isWildcard; - IsDefault = isDefault; } /// @@ -36,7 +35,6 @@ namespace Umbraco.Web.Routing ContentId = domain.ContentId; Culture = domain.Culture; IsWildcard = domain.IsWildcard; - IsDefault = domain.IsDefault; } /// @@ -63,10 +61,5 @@ namespace Umbraco.Web.Routing /// Gets a value indicating whether the domain is a wildcard domain. /// public bool IsWildcard { get; } - - /// - /// Gets a value indicating if this is the default domain for the website. - /// - public bool IsDefault { get; } } } diff --git a/src/Umbraco.Web/Routing/DomainHelper.cs b/src/Umbraco.Web/Routing/DomainHelper.cs index 76a0845113..3d6d435179 100644 --- a/src/Umbraco.Web/Routing/DomainHelper.cs +++ b/src/Umbraco.Web/Routing/DomainHelper.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Umbraco.Core; -using Umbraco.Web.Composing; using Umbraco.Web.PublishedCache; // published snapshot namespace Umbraco.Web.Routing @@ -12,13 +11,13 @@ namespace Umbraco.Web.Routing /// public class DomainHelper { - private readonly IDomainCache _domainCache; - private readonly ISiteDomainHelper _siteDomainHelper; - + private readonly IDomainCache _domainCache; + private readonly ISiteDomainHelper _siteDomainHelper; + public DomainHelper(IDomainCache domainCache, ISiteDomainHelper siteDomainHelper) { - _domainCache = domainCache; - _siteDomainHelper = siteDomainHelper; + _domainCache = domainCache; + _siteDomainHelper = siteDomainHelper; } #region Domain for Node @@ -28,9 +27,14 @@ namespace Umbraco.Web.Routing /// /// The node identifier. /// The uri, or null. - /// The domain and its uri, if any, that best matches the specified uri, else null. - /// If at least a domain is set on the node then the method returns the domain that - /// best matches the specified uri, else it returns null. + /// The culture, or null. + /// The domain and its uri, if any, that best matches the specified uri and culture, else null. + /// + /// f at least a domain is set on the node then the method returns the domain that + /// best matches the specified uri and culture, else it returns null. + /// If culture is null, uses the default culture for the installation instead. + /// fixme not exactly - if culture is !null, we MUST have a value for THAT culture, else we use default as hint + /// internal DomainAndUri DomainForNode(int nodeId, Uri current, string culture = null) { // be safe @@ -44,8 +48,9 @@ namespace Umbraco.Web.Routing if (domains.Length == 0) return null; - // else filter - var domainAndUri = DomainForUri(domains, current, culture, domainAndUris => _siteDomainHelper.MapDomain(current, domainAndUris)); + // else filter + var domainAndUri = SelectDomain(domains, current, culture, _domainCache.DefaultCulture, + (cdomainAndUris, ccurrent, cculture, cdefaultCulture) => _siteDomainHelper.MapDomain(cdomainAndUris, ccurrent, cculture, cdefaultCulture)); if (domainAndUri == null) throw new Exception("DomainForUri returned null."); @@ -86,107 +91,163 @@ namespace Umbraco.Web.Routing return null; // get the domains and their uris - var domainAndUris = DomainsForUri(domains, current).ToArray(); + var domainAndUris = SelectDomains(domains, current).ToArray(); // filter - return _siteDomainHelper.MapDomains(current, domainAndUris, excludeDefault).ToArray(); + return _siteDomainHelper.MapDomains(domainAndUris, current, excludeDefault, null, _domainCache.DefaultCulture).ToArray(); } #endregion - #region Domain for Uri + #region Selects Domain(s) /// - /// Finds the domain that best matches a specified uri, into a group of domains. + /// Selects the domain that best matches a specified uri and cultures, from a set of domains. /// /// The group of domains. - /// The uri, or null. - /// A function to filter the list of domains, if more than one applies, or null. - /// The domain and its normalized uri, that best matches the specified uri. + /// An optional uri. + /// An optional culture. + /// An optional default culture. + /// An optional function to filter the list of domains, if more than one applies. + /// The domain and its normalized uri, that best matches the specified uri and cultures. /// + /// fixme - must document and explain this all + /// If is null, pick the first domain that matches , + /// else the first that matches , else the first one (ordered by id), else null. + /// If is not null, look for domains that would be a base uri of the current uri, /// If more than one domain matches, then the function is used to pick /// the right one, unless it is null, in which case the method returns null. /// The filter, if any, will be called only with a non-empty argument, and _must_ return something. /// - internal static DomainAndUri DomainForUri(IEnumerable domains, Uri current, string culture = null, Func filter = null) + internal static DomainAndUri SelectDomain(IEnumerable domains, Uri uri, string culture = null, string defaultCulture = null, Func, Uri, string, string, DomainAndUri> filter = null) { // sanitize the list to have proper uris for comparison (scheme, path end with /) // we need to end with / because example.com/foo cannot match example.com/foobar // we need to order so example.com/foo matches before example.com/ var domainsAndUris = domains .Where(d => d.IsWildcard == false) - .Select(d => new DomainAndUri(d, current)) + .Select(d => new DomainAndUri(d, uri)) .OrderByDescending(d => d.Uri.ToString()) - .ToArray(); + .ToList(); - if (domainsAndUris.Length == 0) + // nothing = no magic, return null + if (domainsAndUris.Count == 0) return null; - DomainAndUri domainAndUri; - if (current == null) - { - //match either by culture (if specified) or default - - //get the default domain or the one matching the culture if specified - domainAndUri = domainsAndUris.FirstOrDefault(x => culture.IsNullOrWhiteSpace() ? x.IsDefault : x.Culture.Name.InvariantEquals(culture)); - - if (domainAndUri == null && !culture.IsNullOrWhiteSpace()) - throw new InvalidOperationException($"No domain was found by the specified culture '{culture}'"); - - if (domainAndUri == null) - domainAndUri = domainsAndUris.First(); // take the first one by default (what else can we do?) - } - else if (!culture.IsNullOrWhiteSpace()) - { - //match by culture - - domainAndUri = domainsAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(culture)); - if (domainAndUri == null) - throw new InvalidOperationException($"No domain was found by the specified culture '{culture}'"); - return domainAndUri; + // sanitize cultures + culture = culture.NullEmpty(); + defaultCulture = defaultCulture.NullEmpty(); + + if (uri == null) + { + // no uri - will only rely on culture + return GetByCulture(domainsAndUris, culture, defaultCulture); } - else - { - //try to match by current, else filter - // look for the first domain that would be the base of the current url - // ie current is www.example.com/foo/bar, look for domain www.example.com - var currentWithSlash = current.EndPathWithSlash(); - domainAndUri = domainsAndUris - .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash)); - if (domainAndUri != null) return domainAndUri; + // else we have a uri, + // try to match that uri, else filter - // if none matches, try again without the port - // ie current is www.example.com:1234/foo/bar, look for domain www.example.com - domainAndUri = domainsAndUris - .FirstOrDefault(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash.WithoutPort())); + // pick domains for cultures + var cultureDomains = SelectByCulture(domainsAndUris, culture, defaultCulture); + IReadOnlyCollection considerForBaseDomains = domainsAndUris; + if (cultureDomains != null) + { + if (cultureDomains.Count == 1) // only 1, return + return cultureDomains.First(); + + // else restrict to those domains, for base lookup + considerForBaseDomains = cultureDomains; + } + + // look for domains that would be the base of the uri + var baseDomains = SelectByBase(considerForBaseDomains, uri); + if (baseDomains.Count > 0) // found, return + return baseDomains.First(); + + // if nothing works, then try to run the filter to select a domain + // either restricting on cultureDomains, or on all domains + if (filter != null) + { + var domainAndUri = filter(cultureDomains ?? domainsAndUris, uri, culture, defaultCulture); + // if still nothing, pick the first one? + // no: move that constraint to the filter, but check + if (domainAndUri == null) + throw new InvalidOperationException("The filter returned null."); + return domainAndUri; + } + + return null; + } + + private static IReadOnlyCollection SelectByBase(IReadOnlyCollection domainsAndUris, Uri uri) + { + // look for domains that would be the base of the uri + // ie current is www.example.com/foo/bar, look for domain www.example.com + var currentWithSlash = uri.EndPathWithSlash(); + var baseDomains = domainsAndUris.Where(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash)).ToList(); + + // if none matches, try again without the port + // ie current is www.example.com:1234/foo/bar, look for domain www.example.com + if (baseDomains.Count == 0) + baseDomains = domainsAndUris.Where(d => d.Uri.EndPathWithSlash().IsBaseOf(currentWithSlash.WithoutPort())).ToList(); + + return baseDomains; + } + + private static IReadOnlyCollection SelectByCulture(IReadOnlyCollection domainsAndUris, string culture, string defaultCulture) + { + if (culture != null) // try the supplied culture + { + var cultureDomains = domainsAndUris.Where(x => x.Culture.Name.InvariantEquals(culture)).ToList(); + if (cultureDomains.Count > 0) return cultureDomains; + + // if a culture is supplied, we *want* a url for that culture, else fail + throw new InvalidOperationException($"Could not find a domain for culture \"{culture}\"."); + } + + if (defaultCulture != null) // try the defaultCulture culture + { + var cultureDomains = domainsAndUris.Where(x => x.Culture.Name.InvariantEquals(defaultCulture)).ToList(); + if (cultureDomains.Count > 0) return cultureDomains; + } + + return null; + } + + private static DomainAndUri GetByCulture(IReadOnlyCollection domainsAndUris, string culture, string defaultCulture) + { + DomainAndUri domainAndUri; + + if (culture != null) // try the supplied culture + { + domainAndUri = domainsAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(culture)); if (domainAndUri != null) return domainAndUri; - - // if none matches, then try to run the filter to pick a domain - if (filter != null) - { - domainAndUri = filter(domainsAndUris); - // if still nothing, pick the first one? - // no: move that constraint to the filter, but check - if (domainAndUri == null) - throw new InvalidOperationException("The filter returned null."); - } + + // if a culture is supplied, we *want* a url for that culture, else fail + throw new InvalidOperationException($"Could not find a domain for culture \"{culture}\"."); } - return domainAndUri; + if (defaultCulture != null) // try the defaultCulture culture + { + domainAndUri = domainsAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(defaultCulture)); + if (domainAndUri != null) return domainAndUri; + } + + return domainsAndUris.First(); // what else? } /// - /// Gets the domains that match a specified uri, into a group of domains. + /// Selects the domains that match a specified uri, from a set of domains. /// - /// The group of domains. - /// The uri, or null. + /// The domains. + /// The uri, or null. /// The domains and their normalized uris, that match the specified uri. - internal static IEnumerable DomainsForUri(IEnumerable domains, Uri current) - { + internal static IEnumerable SelectDomains(IEnumerable domains, Uri uri) + { + // fixme where are we matching ?!!? return domains .Where(d => d.IsWildcard == false) - .Select(d => new DomainAndUri(d, current)) + .Select(d => new DomainAndUri(d, uri)) .OrderByDescending(d => d.Uri.ToString()); } diff --git a/src/Umbraco.Web/Routing/ISiteDomainHelper.cs b/src/Umbraco.Web/Routing/ISiteDomainHelper.cs index 482cbba4a9..2ca8273f45 100644 --- a/src/Umbraco.Web/Routing/ISiteDomainHelper.cs +++ b/src/Umbraco.Web/Routing/ISiteDomainHelper.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Umbraco.Web.Routing { @@ -13,25 +11,35 @@ namespace Umbraco.Web.Routing /// /// Filters a list of DomainAndUri to pick one that best matches the current request. /// - /// The Uri of the current request. /// The list of DomainAndUri to filter. + /// The Uri of the current request. + /// A culture. + /// The default culture. /// The selected DomainAndUri. /// /// If the filter is invoked then is _not_ empty and /// is _not_ null, and could not be /// matched with anything in . + /// The may be null, but when non-null, it can be used + /// to help pick the best matches. /// The filter _must_ return something else an exception will be thrown. /// - DomainAndUri MapDomain(Uri current, DomainAndUri[] domainAndUris); + DomainAndUri MapDomain(IReadOnlyCollection domainAndUris, Uri current, string culture, string defaultCulture); /// /// Filters a list of DomainAndUri to pick those that best matches the current request. /// - /// The Uri of the current request. /// The list of DomainAndUri to filter. + /// The Uri of the current request. /// A value indicating whether to exclude the current/default domain. + /// A culture. + /// The default culture. /// The selected DomainAndUri items. - /// The filter must return something, even empty, else an exception will be thrown. - IEnumerable MapDomains(Uri current, DomainAndUri[] domainAndUris, bool excludeDefault); + /// + /// The filter must return something, even empty, else an exception will be thrown. + /// The may be null, but when non-null, it can be used + /// to help pick the best matches. + /// + IEnumerable MapDomains(IReadOnlyCollection domainAndUris, Uri current, bool excludeDefault, string culture, string defaultCulture); } } diff --git a/src/Umbraco.Web/Routing/IUrlProvider.cs b/src/Umbraco.Web/Routing/IUrlProvider.cs index e4c6e23022..031f4670b2 100644 --- a/src/Umbraco.Web/Routing/IUrlProvider.cs +++ b/src/Umbraco.Web/Routing/IUrlProvider.cs @@ -23,6 +23,7 @@ namespace Umbraco.Web.Routing /// If the provider is unable to provide a url, it should return null. /// string GetUrl(UmbracoContext umbracoContext, int id, Uri current, UrlProviderMode mode, string culture = null); + // FIXME WE HAVE TO DOCUMENT CULTURE FFS /// /// Gets the other urls of a published content. diff --git a/src/Umbraco.Web/Routing/PublishedRouter.cs b/src/Umbraco.Web/Routing/PublishedRouter.cs index 0b4fc89b6b..35e5ab1af4 100644 --- a/src/Umbraco.Web/Routing/PublishedRouter.cs +++ b/src/Umbraco.Web/Routing/PublishedRouter.cs @@ -265,8 +265,12 @@ namespace Umbraco.Web.Routing _logger.Debug(() => $"{tracePrefix}Uri=\"{request.Uri}\""); + var domainsCache = request.UmbracoContext.PublishedSnapshot.Domains; + var domains = domainsCache.GetAll(includeWildcards: false); + var defaultCulture = domainsCache.DefaultCulture; + // try to find a domain matching the current request - var domainAndUri = DomainHelper.DomainForUri(request.UmbracoContext.PublishedSnapshot.Domains.GetAll(false), request.Uri); + var domainAndUri = DomainHelper.SelectDomain(domains, request.Uri, defaultCulture: defaultCulture); // handle domain - always has a contentId and a culture if (domainAndUri != null) @@ -289,8 +293,7 @@ namespace Umbraco.Web.Routing // not matching any existing domain _logger.Debug(() => $"{tracePrefix}Matches no domain"); - var defaultLanguage = _services.LocalizationService.GetAllLanguages().FirstOrDefault(); - request.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.IsoCode); + request.Culture = defaultCulture == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultCulture); } _logger.Debug(() => $"{tracePrefix}Culture=\"{request.Culture.Name}\""); diff --git a/src/Umbraco.Web/Routing/SiteDomainHelper.cs b/src/Umbraco.Web/Routing/SiteDomainHelper.cs index deaa84b0e1..6e592c471d 100644 --- a/src/Umbraco.Web/Routing/SiteDomainHelper.cs +++ b/src/Umbraco.Web/Routing/SiteDomainHelper.cs @@ -11,7 +11,7 @@ namespace Umbraco.Web.Routing /// Provides utilities to handle site domains. /// public class SiteDomainHelper : ISiteDomainHelper - { + { #region Configure private static readonly ReaderWriterLockSlim ConfigLock = new ReaderWriterLockSlim(); @@ -20,31 +20,27 @@ namespace Umbraco.Web.Routing private static Dictionary> _qualifiedSites; // these are for unit tests *only* - internal static Dictionary Sites { get { return _sites; } } - internal static Dictionary> Bindings { get { return _bindings; } } + // ReSharper disable ConvertToAutoPropertyWithPrivateSetter + internal static Dictionary Sites => _sites; + internal static Dictionary> Bindings => _bindings; + // ReSharper restore ConvertToAutoPropertyWithPrivateSetter // these are for validation //private const string DomainValidationSource = @"^(\*|((?i:http[s]?://)?([-\w]+(\.[-\w]+)*)(:\d+)?(/[-\w]*)?))$"; private const string DomainValidationSource = @"^(((?i:http[s]?://)?([-\w]+(\.[-\w]+)*)(:\d+)?(/)?))$"; private static readonly Regex DomainValidation = new Regex(DomainValidationSource, RegexOptions.IgnoreCase | RegexOptions.Compiled); - /// + /// /// Returns a disposable object that represents safe write access to config. - /// + /// /// Should be used in a using(SiteDomainHelper.ConfigWriteLock) { ... } mode. - protected static IDisposable ConfigWriteLock - { - get { return new WriteLock(ConfigLock); } - } + protected static IDisposable ConfigWriteLock => new WriteLock(ConfigLock); /// /// Returns a disposable object that represents safe read access to config. /// /// Should be used in a using(SiteDomainHelper.ConfigWriteLock) { ... } mode. - protected static IDisposable ConfigReadLock - { - get { return new ReadLock(ConfigLock); } - } + protected static IDisposable ConfigReadLock => new ReadLock(ConfigLock); /// /// Clears the entire configuration. @@ -66,7 +62,7 @@ namespace Umbraco.Web.Routing return domains.Select(domain => { if (!DomainValidation.IsMatch(domain)) - throw new ArgumentOutOfRangeException("domains", string.Format("Invalid domain: \"{0}\"", domain)); + throw new ArgumentOutOfRangeException(nameof(domains), $"Invalid domain: \"{domain}\"."); return domain; }); } @@ -111,27 +107,27 @@ namespace Umbraco.Web.Routing { using (ConfigWriteLock) { - if (_sites != null && _sites.ContainsKey(key)) + if (_sites == null || !_sites.ContainsKey(key)) + return; + + _sites.Remove(key); + if (_sites.Count == 0) + _sites = null; + + if (_bindings != null && _bindings.ContainsKey(key)) { - _sites.Remove(key); - if (_sites.Count == 0) - _sites = null; - - if (_bindings != null && _bindings.ContainsKey(key)) + foreach (var b in _bindings[key]) { - foreach (var b in _bindings[key]) - { - _bindings[b].Remove(key); - if (_bindings[b].Count == 0) - _bindings.Remove(b); - } - _bindings.Remove(key); - if (_bindings.Count > 0) - _bindings = null; + _bindings[b].Remove(key); + if (_bindings[b].Count == 0) + _bindings.Remove(b); } - - _qualifiedSites = null; + _bindings.Remove(key); + if (_bindings.Count > 0) + _bindings = null; } + + _qualifiedSites = null; } } @@ -148,7 +144,7 @@ namespace Umbraco.Web.Routing using (ConfigWriteLock) { foreach (var key in keys.Where(key => !_sites.ContainsKey(key))) - throw new ArgumentException(string.Format("Not an existing site key: {0}", key), "keys"); + throw new ArgumentException($"Not an existing site key: {key}.", nameof(keys)); _bindings = _bindings ?? new Dictionary>(); @@ -173,36 +169,20 @@ namespace Umbraco.Web.Routing #region Map domains - /// - /// Filters a list of DomainAndUri to pick one that best matches the current request. - /// - /// The Uri of the current request. - /// The list of DomainAndUri to filter. - /// The selected DomainAndUri. - /// - /// If the filter is invoked then is _not_ empty and - /// is _not_ null, and could not be - /// matched with anything in . - /// The filter _must_ return something else an exception will be thrown. - /// - public virtual DomainAndUri MapDomain(Uri current, DomainAndUri[] domainAndUris) + /// + public virtual DomainAndUri MapDomain(IReadOnlyCollection domainAndUris, Uri current, string culture, string defaultCulture) { var currentAuthority = current.GetLeftPart(UriPartial.Authority); var qualifiedSites = GetQualifiedSites(current); - return MapDomain(domainAndUris, qualifiedSites, currentAuthority); + return MapDomain(domainAndUris, qualifiedSites, currentAuthority, culture, defaultCulture); } - /// - /// Filters a list of DomainAndUri to pick those that best matches the current request. - /// - /// The Uri of the current request. - /// The list of DomainAndUri to filter. - /// A value indicating whether to exclude the current/default domain. - /// The selected DomainAndUri items. - /// The filter must return something, even empty, else an exception will be thrown. - public virtual IEnumerable MapDomains(Uri current, DomainAndUri[] domainAndUris, bool excludeDefault) - { + /// + public virtual IEnumerable MapDomains(IReadOnlyCollection domainAndUris, Uri current, bool excludeDefault, string culture, string defaultCulture) + { + // fixme ignoring cultures entirely? + var currentAuthority = current.GetLeftPart(UriPartial.Authority); KeyValuePair[] candidateSites = null; IEnumerable ret = domainAndUris; @@ -225,7 +205,7 @@ namespace Umbraco.Web.Routing { // it is illegal to call MapDomain if domainAndUris is empty // also, domainAndUris should NOT contain current, hence the test on hinted - var mainDomain = MapDomain(domainAndUris, qualifiedSites, currentAuthority); // what GetUrl would get + var mainDomain = MapDomain(domainAndUris, qualifiedSites, currentAuthority, culture, defaultCulture); // what GetUrl would get ret = ret.Where(d => d != mainDomain); } } @@ -259,7 +239,7 @@ namespace Umbraco.Web.Routing var authority = d.Uri.GetLeftPart(UriPartial.Authority); return candidateSites.Any(site => site.Value.Contains(authority)); }); - } + } private static Dictionary GetQualifiedSites(Uri current) { @@ -294,21 +274,19 @@ namespace Umbraco.Web.Routing // therefore it is safe to return and exit the configuration lock } - private static DomainAndUri MapDomain(DomainAndUri[] domainAndUris, Dictionary qualifiedSites, string currentAuthority) + private static DomainAndUri MapDomain(IReadOnlyCollection domainAndUris, Dictionary qualifiedSites, string currentAuthority, string culture, string defaultCulture) { - if (domainAndUris == null) - throw new ArgumentNullException("domainAndUris"); - if (!domainAndUris.Any()) - throw new ArgumentException("Cannot be empty.", "domainAndUris"); + if (domainAndUris == null) throw new ArgumentNullException(nameof(domainAndUris)); + if (domainAndUris.Count == 0) throw new ArgumentException("Cannot be empty.", nameof(domainAndUris)); + + // fixme how shall we deal with cultures? // we do our best, but can't do the impossible + // get the "default" domain ie the first one for the culture, else the first one (exists, length > 0) if (qualifiedSites == null) - { - //fixme take the default - var defaultDomain = domainAndUris.FirstOrDefault(x => x.IsDefault); - if (defaultDomain == null) defaultDomain = domainAndUris.First(); //this shouldn't occur but just in case - return defaultDomain; - } + return domainAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(culture)) ?? + domainAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(defaultCulture)) ?? + domainAndUris.First(); // find a site that contains the current authority var currentSite = qualifiedSites.FirstOrDefault(site => site.Value.Contains(currentAuthority)); @@ -330,7 +308,7 @@ namespace Umbraco.Web.Routing .FirstOrDefault(domainAndUri => domainAndUri != null); // random, really - ret = ret ?? domainAndUris.First(); + ret = ret ?? domainAndUris.FirstOrDefault(x => x.Culture.Name.InvariantEquals(culture)) ?? domainAndUris.First(); return ret; } diff --git a/src/Umbraco.Web/Routing/UrlProvider.cs b/src/Umbraco.Web/Routing/UrlProvider.cs index 98bd1b182d..c23ff5fb86 100644 --- a/src/Umbraco.Web/Routing/UrlProvider.cs +++ b/src/Umbraco.Web/Routing/UrlProvider.cs @@ -209,7 +209,7 @@ namespace Umbraco.Web.Routing /// The url is absolute or relative depending on mode and on current. /// If the provider is unable to provide a url, it returns "#". /// - public string GetUrl(int id, Uri current, UrlProviderMode mode, string culture = null) + public string GetUrl(int id, Uri current, UrlProviderMode mode, string culture = null) // FIXME DOCUMENT { var url = _urlProviders.Select(provider => provider.GetUrl(_umbracoContext, id, current, mode, culture)) .FirstOrDefault(u => u != null); diff --git a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs index 96a1029f3c..4e7b78efe9 100644 --- a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs @@ -210,8 +210,8 @@ namespace Umbraco.Web.Trees result = Services.EntityService.GetChildren(entityId, UmbracoObjectType).ToArray(); } - //This should really never be null, but we'll error check anyways - int? currLangId = langId.HasValue ? langId.Value : Services.LocalizationService.GetDefaultVariantLanguage()?.Id; + //This should really never be null, but we'll error check anyways + var currLangId = langId ?? Services.LocalizationService.GetDefaultLanguageId(); //Try to see if there is a variant name for the current language for the item and set the name accordingly. //If any of this fails, the tree node name will remain the default invariant culture name. diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index c58ff40575..b86c8c29a6 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -39,16 +39,16 @@ namespace Umbraco.Web /// The "current" UmbracoContext. /// /// fixme - this needs to be clarified - /// + /// /// If is true then the "current" UmbracoContext is replaced /// with a new one even if there is one already. See . Has to do with /// creating a context at startup and not being able to access httpContext.Request at that time, so /// the OriginalRequestUrl remains unspecified until replaces the context. - /// + /// /// This *has* to be done differently! - /// + /// /// See http://issues.umbraco.org/issue/U4-1890, http://issues.umbraco.org/issue/U4-1717 - /// + /// /// // used by // UmbracoModule BeginRequest (since it's a request it has an UmbracoContext) @@ -215,21 +215,17 @@ namespace Umbraco.Web /// /// Creates and caches an instance of a DomainHelper - /// - /// - /// We keep creating new instances of DomainHelper, it would be better if we didn't have to do that so instead we can - /// have one attached to the UmbracoContext. This method accepts an external ISiteDomainHelper otherwise the UmbracoContext - /// ctor will have to have another parameter added only for this one method which is annoying and doesn't make a ton of sense - /// since the UmbracoContext itself doesn't use this. - /// - /// TODO The alternative is to have a IDomainHelperAccessor singleton which is cached per UmbracoContext - /// - internal DomainHelper GetDomainHelper(ISiteDomainHelper siteDomainHelper) - { - if (_domainHelper == null) - _domainHelper = new DomainHelper(PublishedSnapshot.Domains, siteDomainHelper); - return _domainHelper; - } + /// + /// + /// We keep creating new instances of DomainHelper, it would be better if we didn't have to do that so instead we can + /// have one attached to the UmbracoContext. This method accepts an external ISiteDomainHelper otherwise the UmbracoContext + /// ctor will have to have another parameter added only for this one method which is annoying and doesn't make a ton of sense + /// since the UmbracoContext itself doesn't use this. + /// + /// TODO The alternative is to have a IDomainHelperAccessor singleton which is cached per UmbracoContext + /// + internal DomainHelper GetDomainHelper(ISiteDomainHelper siteDomainHelper) + => _domainHelper ?? (_domainHelper = new DomainHelper(PublishedSnapshot.Domains, siteDomainHelper)); /// /// Gets a value indicating whether the request has debugging enabled From aa46e1e2826cad696ca4534eb090ab30b0f3a11b Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 27 Apr 2018 17:36:22 +0200 Subject: [PATCH 42/58] Test nullref on NPocoSqlExtensions --- src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs b/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs index 7b12e2e69d..60172ef687 100644 --- a/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs +++ b/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs @@ -544,6 +544,7 @@ namespace Umbraco.Core.Persistence /// The Sql statement. public static Sql SelectTop(this Sql sql, int count) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.SqlContext.SqlSyntax.SelectTop(sql, count); } @@ -554,6 +555,7 @@ namespace Umbraco.Core.Persistence /// The Sql statement. public static Sql SelectCount(this Sql sql) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Select("COUNT(*)"); } @@ -569,6 +571,7 @@ namespace Umbraco.Core.Persistence /// public static Sql SelectCount(this Sql sql, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); var columns = fields.Length == 0 ? sql.GetColumns(withAlias: false) : fields.Select(x => GetFieldName(x, sql.SqlContext.SqlSyntax)).ToArray(); @@ -582,6 +585,7 @@ namespace Umbraco.Core.Persistence /// The Sql statement. public static Sql SelectAll(this Sql sql) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Select("*"); } @@ -597,6 +601,7 @@ namespace Umbraco.Core.Persistence /// public static Sql Select(this Sql sql, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Select(sql.GetColumns(columnExpressions: fields)); } @@ -613,6 +618,7 @@ namespace Umbraco.Core.Persistence /// public static Sql Select(this Sql sql, string tableAlias, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Select(sql.GetColumns(tableAlias: tableAlias, columnExpressions: fields)); } @@ -628,6 +634,7 @@ namespace Umbraco.Core.Persistence /// public static Sql AndSelect(this Sql sql, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Append(", " + string.Join(", ", sql.GetColumns(columnExpressions: fields))); } @@ -645,6 +652,7 @@ namespace Umbraco.Core.Persistence /// public static Sql AndSelect(this Sql sql, string tableAlias, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return sql.Append(", " + string.Join(", ", sql.GetColumns(tableAlias: tableAlias, columnExpressions: fields))); } @@ -657,6 +665,8 @@ namespace Umbraco.Core.Persistence /// The Sql statement. public static Sql Select(this Sql sql, Func, SqlRef> reference) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); + sql.Select(sql.GetColumns()); reference?.Invoke(new SqlRef(sql, null)); @@ -675,6 +685,8 @@ namespace Umbraco.Core.Persistence /// is added, so that it is possible to add (e.g. calculated) columns to the referencing Dto. public static Sql Select(this Sql sql, Func, SqlRef> reference, Func, Sql> sqlexpr) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); + sql.Select(sql.GetColumns()); sql = sqlexpr(sql); @@ -789,6 +801,7 @@ namespace Umbraco.Core.Persistence /// public static string Columns(this Sql sql, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return string.Join(", ", sql.GetColumns(columnExpressions: fields, withAlias: false)); } @@ -805,6 +818,7 @@ namespace Umbraco.Core.Persistence /// public static string Columns(this Sql sql, string alias, params Expression>[] fields) { + if (sql == null) throw new ArgumentNullException(nameof(sql)); return string.Join(", ", sql.GetColumns(columnExpressions: fields, withAlias: false, tableAlias: alias)); } From 8f13fa3ae522d6dea645645a93a7ea0e3bfcc7bc Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 27 Apr 2018 17:36:50 +0200 Subject: [PATCH 43/58] ISystemDefaultCultureProvider --- .../Implement/LanguageRepository.cs | 4 ---- .../PublishedContentCacheTests.cs | 2 +- .../Scoping/ScopedNuCacheTests.cs | 4 +++- .../TestHelpers/TestWithDatabaseBase.cs | 7 ++++++ .../TestSystemDefaultCultureProvider.cs | 9 +++++++ src/Umbraco.Tests/Umbraco.Tests.csproj | 5 ++-- .../Web/Mvc/UmbracoViewPageTests.cs | 4 +++- .../ISystemDefaultCultureProvider.cs | 13 ++++++++++ .../NuCache/PublishedSnapshotService.cs | 5 +++- .../SystemDefaultCultureProvider.cs | 24 +++++++++++++++++++ .../XmlPublishedCache/DomainCache.cs | 4 ++-- .../PublishedSnapshotService.cs | 11 ++++++--- .../XmlPublishedCache/XmlCacheComponent.cs | 1 + .../Runtime/WebRuntimeComponent.cs | 3 +++ src/Umbraco.Web/Umbraco.Web.csproj | 2 ++ 15 files changed, 82 insertions(+), 16 deletions(-) create mode 100644 src/Umbraco.Tests/Testing/Objects/AccessorsAndProviders/TestSystemDefaultCultureProvider.cs create mode 100644 src/Umbraco.Web/PublishedCache/ISystemDefaultCultureProvider.cs create mode 100644 src/Umbraco.Web/PublishedCache/SystemDefaultCultureProvider.cs diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs index 8e42ee460b..1ca91d8774 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/LanguageRepository.cs @@ -256,10 +256,6 @@ namespace Umbraco.Core.Persistence.Repositories.Implement // do NOT leak that language, it's not deep-cloned! private ILanguage GetDefault() { - // FIXME - var temp = SqlContext.Sql(); - if (temp == null) return null; - // get all cached, non-cloned var all = TypedCachePolicy.GetAllCached(PerformGetAll); diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 234b31d5a0..8212243e26 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _xml.LoadXml(GetXml()); var xmlStore = new XmlStore(() => _xml, null, null, null); var cacheProvider = new StaticCacheProvider(); - var domainCache = new DomainCache(ServiceContext.DomainService, ServiceContext.LocalizationService); + var domainCache = new DomainCache(ServiceContext.DomainService, SystemDefaultCultureProvider); 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), diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 06c13b2733..cc9813cdbd 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -90,7 +90,9 @@ namespace Umbraco.Tests.Scoping publishedSnapshotAccessor, Logger, ScopeProvider, - documentRepository, mediaRepository, memberRepository, Container.GetInstance(), new SiteDomainHelper()); + documentRepository, mediaRepository, memberRepository, + SystemDefaultCultureProvider, + Container.GetInstance(), new SiteDomainHelper()); } protected UmbracoContext GetUmbracoContextNu(string url, int templateId = 1234, RouteData routeData = null, bool setSingleton = false, IUmbracoSettingsSection umbracoSettings = null, IEnumerable urlProviders = null) diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 070166eaff..0fcd3c9295 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -32,6 +32,7 @@ using LightInject; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Persistence.Repositories; +using Umbraco.Tests.Testing.Objects.AccessorsAndProviders; namespace Umbraco.Tests.TestHelpers { @@ -77,6 +78,7 @@ namespace Umbraco.Tests.TestHelpers Container.Register(); Container.Register(factory => PublishedSnapshotService); + Container.Register(factory => SystemDefaultCultureProvider); Container.GetInstance() .Clear() @@ -229,12 +231,16 @@ namespace Umbraco.Tests.TestHelpers } } + protected ISystemDefaultCultureProvider SystemDefaultCultureProvider { get; set; } + protected IPublishedSnapshotService PublishedSnapshotService { get; set; } protected override void Initialize() // fixme - should NOT be here! { base.Initialize(); + SystemDefaultCultureProvider = new TestSystemDefaultCultureProvider(); + CreateAndInitializeDatabase(); // ensure we have a PublishedSnapshotService @@ -264,6 +270,7 @@ namespace Umbraco.Tests.TestHelpers ScopeProvider, cache, publishedSnapshotAccessor, Container.GetInstance(), Container.GetInstance(), Container.GetInstance(), + SystemDefaultCultureProvider, Logger, Container.GetInstance(), new SiteDomainHelper(), ContentTypesCache, diff --git a/src/Umbraco.Tests/Testing/Objects/AccessorsAndProviders/TestSystemDefaultCultureProvider.cs b/src/Umbraco.Tests/Testing/Objects/AccessorsAndProviders/TestSystemDefaultCultureProvider.cs new file mode 100644 index 0000000000..f7e5484500 --- /dev/null +++ b/src/Umbraco.Tests/Testing/Objects/AccessorsAndProviders/TestSystemDefaultCultureProvider.cs @@ -0,0 +1,9 @@ +using Umbraco.Web.PublishedCache; + +namespace Umbraco.Tests.Testing.Objects.AccessorsAndProviders +{ + public class TestSystemDefaultCultureProvider : ISystemDefaultCultureProvider + { + public string DefaultCulture { get; set; } + } +} diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index eaec8a24ff..20bc181017 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -180,6 +180,7 @@ + @@ -595,9 +596,7 @@ - - - + diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index afc461c6de..295f42fee2 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -19,6 +19,7 @@ using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; +using Umbraco.Tests.Testing.Objects.AccessorsAndProviders; using Umbraco.Web; using Umbraco.Web.Models; using Umbraco.Web.Mvc; @@ -424,7 +425,8 @@ namespace Umbraco.Tests.Web.Mvc var scopeProvider = TestObjects.GetScopeProvider(Mock.Of()); var factory = Mock.Of(); _service = new PublishedSnapshotService(svcCtx, factory, scopeProvider, cache, Enumerable.Empty(), null, - null, null, null, + null, null, null, + new TestSystemDefaultCultureProvider(), Current.Logger, TestObjects.GetGlobalSettings(), new SiteDomainHelper(), null, true, false); // no events var http = GetHttpContextFactory(url, routeData).HttpContext; diff --git a/src/Umbraco.Web/PublishedCache/ISystemDefaultCultureProvider.cs b/src/Umbraco.Web/PublishedCache/ISystemDefaultCultureProvider.cs new file mode 100644 index 0000000000..022b6d3e25 --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/ISystemDefaultCultureProvider.cs @@ -0,0 +1,13 @@ +namespace Umbraco.Web.PublishedCache +{ + /// + /// Provides the system default culture. + /// + public interface ISystemDefaultCultureProvider + { + /// + /// Gets the system default culture. + /// + string DefaultCulture { get; } + } +} diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 923502bea2..b498a1a42b 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -44,6 +44,7 @@ namespace Umbraco.Web.PublishedCache.NuCache private readonly IMemberRepository _memberRepository; private readonly IGlobalSettings _globalSettings; private readonly ISiteDomainHelper _siteDomainHelper; + private readonly ISystemDefaultCultureProvider _systemDefaultCultureProvider; // volatile because we read it with no lock private volatile bool _isReady; @@ -83,6 +84,7 @@ namespace Umbraco.Web.PublishedCache.NuCache ServiceContext serviceContext, IPublishedContentTypeFactory publishedContentTypeFactory, IdkMap idkMap, IPublishedSnapshotAccessor publishedSnapshotAccessor, ILogger logger, IScopeProvider scopeProvider, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, + ISystemDefaultCultureProvider systemDefaultCultureProvider, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper) : base(publishedSnapshotAccessor) { @@ -97,6 +99,7 @@ namespace Umbraco.Web.PublishedCache.NuCache _documentRepository = documentRepository; _mediaRepository = mediaRepository; _memberRepository = memberRepository; + _systemDefaultCultureProvider = systemDefaultCultureProvider; _globalSettings = globalSettings; _siteDomainHelper = siteDomainHelper; @@ -1014,7 +1017,7 @@ namespace Umbraco.Web.PublishedCache.NuCache var memberTypeCache = new PublishedContentTypeCache(null, null, _serviceContext.MemberTypeService, _publishedContentTypeFactory, _logger); - var defaultCulture = _serviceContext.LocalizationService.GetDefaultLanguageIsoCode(); // capture - fast + var defaultCulture = _systemDefaultCultureProvider.DefaultCulture; var domainCache = new DomainCache(domainSnap, defaultCulture); var domainHelper = new DomainHelper(domainCache, _siteDomainHelper); diff --git a/src/Umbraco.Web/PublishedCache/SystemDefaultCultureProvider.cs b/src/Umbraco.Web/PublishedCache/SystemDefaultCultureProvider.cs new file mode 100644 index 0000000000..6838d483b0 --- /dev/null +++ b/src/Umbraco.Web/PublishedCache/SystemDefaultCultureProvider.cs @@ -0,0 +1,24 @@ +using Umbraco.Core.Services; + +namespace Umbraco.Web.PublishedCache +{ + /// + /// Provides the default implementation of . + /// + public class SystemDefaultCultureProvider : ISystemDefaultCultureProvider + { + private readonly ILocalizationService _localizationService; + + /// + /// Initializes a new instance of the class. + /// + /// + public SystemDefaultCultureProvider(ILocalizationService localizationService) + { + _localizationService = localizationService; + } + + /// + public string DefaultCulture => _localizationService.GetDefaultLanguageIsoCode(); // capture - fast + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs index 64c1d80852..9a82840024 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/DomainCache.cs @@ -11,10 +11,10 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache { private readonly IDomainService _domainService; - public DomainCache(IDomainService domainService, ILocalizationService localizationService) + public DomainCache(IDomainService domainService, ISystemDefaultCultureProvider systemDefaultCultureProvider) { _domainService = domainService; - DefaultCulture = localizationService.GetDefaultLanguageIsoCode(); // capture - fast + DefaultCulture = systemDefaultCultureProvider.DefaultCulture; } public IEnumerable GetAll(bool includeWildcards) diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs index 1f327f4cd3..3b9a97d8cc 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/PublishedSnapshotService.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly IUserService _userService; private readonly ICacheProvider _requestCache; private readonly IGlobalSettings _globalSettings; - private readonly ILocalizationService _localizationService; + private readonly ISystemDefaultCultureProvider _systemDefaultCultureProvider; private readonly ISiteDomainHelper _siteDomainHelper; #region Constructors @@ -45,6 +45,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IEnumerable segmentProviders, IPublishedSnapshotAccessor publishedSnapshotAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, + ISystemDefaultCultureProvider systemDefaultCultureProvider, ILogger logger, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, @@ -52,6 +53,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache bool testing = false, bool enableRepositoryEvents = true) : this(serviceContext, publishedContentTypeFactory, scopeProvider, requestCache, segmentProviders, publishedSnapshotAccessor, documentRepository, mediaRepository, memberRepository, + systemDefaultCultureProvider, logger, globalSettings, siteDomainHelper, null, mainDom, testing, enableRepositoryEvents) { } @@ -62,6 +64,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache ICacheProvider requestCache, IPublishedSnapshotAccessor publishedSnapshotAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, + ISystemDefaultCultureProvider systemDefaultCultureProvider, ILogger logger, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, @@ -70,6 +73,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache bool testing, bool enableRepositoryEvents) : this(serviceContext, publishedContentTypeFactory, scopeProvider, requestCache, Enumerable.Empty(), publishedSnapshotAccessor, documentRepository, mediaRepository, memberRepository, + systemDefaultCultureProvider, logger, globalSettings, siteDomainHelper, contentTypeCache, mainDom, testing, enableRepositoryEvents) { } @@ -80,6 +84,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache IEnumerable segmentProviders, IPublishedSnapshotAccessor publishedSnapshotAccessor, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IMemberRepository memberRepository, + ISystemDefaultCultureProvider systemDefaultCultureProvider, ILogger logger, IGlobalSettings globalSettings, ISiteDomainHelper siteDomainHelper, @@ -101,7 +106,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _memberService = serviceContext.MemberService; _mediaService = serviceContext.MediaService; _userService = serviceContext.UserService; - _localizationService = serviceContext.LocalizationService; + _systemDefaultCultureProvider = systemDefaultCultureProvider; _requestCache = requestCache; _globalSettings = globalSettings; @@ -146,7 +151,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache // the current caches, but that would mean creating an extra cache (StaticCache // probably) so better use RequestCache. - var domainCache = new DomainCache(_domainService, _localizationService); + var domainCache = new DomainCache(_domainService, _systemDefaultCultureProvider); return new PublishedSnapshot( new PublishedContentCache(_xmlStore, domainCache, _requestCache, _globalSettings, _siteDomainHelper, _contentTypeCache, _routesCache, previewToken), diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs index 37f29cc1d6..c9794eb99a 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlCacheComponent.cs @@ -32,6 +32,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index a0c482075a..54afd0ad75 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -69,6 +69,9 @@ namespace Umbraco.Web.Runtime //it still needs to use the install controller so we can't do that composition.Container.RegisterFrom(); + // register the system culture provider + composition.Container.RegisterSingleton(); + var typeLoader = composition.Container.GetInstance(); var logger = composition.Container.GetInstance(); var proflog = composition.Container.GetInstance(); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 1339166185..a39495430b 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -343,6 +343,7 @@ + @@ -387,6 +388,7 @@ + From a26d7747b6825e4167cb9b1232f99c757af05274 Mon Sep 17 00:00:00 2001 From: Shannon Date: Mon, 30 Apr 2018 15:51:05 +1000 Subject: [PATCH 44/58] removes commented out code --- src/Umbraco.Web/PublishedContentExtensions.cs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index ace05c33f5..e4a3a85d13 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -1228,24 +1228,6 @@ namespace Umbraco.Web #region Culture - //TODO: Not used - ///// - ///// Gets the culture that would be selected to render a specified content, - ///// within the context of a specified current request. - ///// - ///// The content. - ///// The request Uri. - ///// The culture that would be selected to render the content. - //public static CultureInfo GetCulture(this IPublishedContent content, Uri current = null) - //{ - // return Models.ContentExtensions.GetCulture(UmbracoContext.Current, - // Current.Services.DomainService, - // Current.Services.LocalizationService, - // Current.Services.ContentService, - // content.Id, content.Path, - // current); - //} - /// /// Return the URL name for the based on the culture specified or default culture defined /// From 954098eb7e9a2d81ee78c374e36250dda83dd3ad Mon Sep 17 00:00:00 2001 From: Warren Date: Mon, 30 Apr 2018 13:52:05 +0100 Subject: [PATCH 45/58] Comments out & leaves comment about removing the open in split view link (otherwise we will forget) --- .../src/views/components/editor/umb-editor-header.html | 3 +++ 1 file changed, 3 insertions(+) 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 2ce16c5609..41d44114a0 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 @@ -61,7 +61,10 @@ {{variant.language.name}} {{variant.state}} + + From 51d608125d5254b6f4a54d0858d0710b0f70cc2b Mon Sep 17 00:00:00 2001 From: Shannon Date: Mon, 30 Apr 2018 23:29:44 +1000 Subject: [PATCH 46/58] updates editor config file with vs specific rules --- .editorconfig | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.editorconfig b/.editorconfig index 5f3b4d684a..d2f3002c12 100644 --- a/.editorconfig +++ b/.editorconfig @@ -15,3 +15,16 @@ indent_size = 4 # Trim trailing whitespace, limited support. # https://github.com/editorconfig/editorconfig/wiki/Property-research:-Trim-trailing-spaces trim_trailing_whitespace = true + +[*.{cs,vb}] +dotnet_style_predefined_type_for_locals_parameters_members = true:error + +dotnet_naming_rule.private_members_with_underscore.symbols = private_fields +dotnet_naming_rule.private_members_with_underscore.style = prefix_underscore +dotnet_naming_rule.private_members_with_underscore.severity = suggestion + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private + +dotnet_naming_style.prefix_underscore.capitalization = camel_case +dotnet_naming_style.prefix_underscore.required_prefix = _ \ No newline at end of file From 9a2797303bdfa14a7a18003cbc1a3ee95b8b064f Mon Sep 17 00:00:00 2001 From: Shannon Date: Mon, 30 Apr 2018 23:30:08 +1000 Subject: [PATCH 47/58] cleaning up files --- build/NuSpecs/tools/trees.config.install.xdt | 3 - src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 13 - .../Umbraco/Images/editor/dictionaryItem.gif | Bin 1040 -> 0 bytes .../Umbraco/Images/editor/help.png | Bin 377 -> 0 bytes .../Images/editor/insChildTemplateNew.gif | Bin 914 -> 0 bytes .../Umbraco/Images/editor/insField.gif | Bin 648 -> 0 bytes .../Umbraco/Images/editor/insFieldByLevel.gif | Bin 626 -> 0 bytes .../Umbraco/Images/editor/insFieldByTree.gif | Bin 621 -> 0 bytes .../Umbraco/Images/editor/insMacro.gif | Bin 610 -> 0 bytes .../Umbraco/Images/editor/insMacroSB.png | Bin 474 -> 0 bytes .../Umbraco/Images/editor/insMemberItem.gif | Bin 627 -> 0 bytes .../Umbraco/Images/editor/insRazorMacro.png | Bin 529 -> 0 bytes .../Umbraco/Images/editor/inshtml.GIF | Bin 191 -> 0 bytes .../Images/editor/masterpageContent.gif | Bin 132 -> 0 bytes .../Images/editor/masterpagePlaceHolder.gif | Bin 286 -> 0 bytes .../Umbraco/Images/editor/xslVisualize.gif | Bin 663 -> 0 bytes .../config/trees.Release.config | 3 +- src/Umbraco.Web.UI/config/trees.config | 3 +- .../umbraco/config/create/UI.Release.xml | 21 - .../umbraco/config/create/UI.xml | 21 - .../umbraco/create/PartialViewMacro.ascx | 38 -- .../umbraco/create/PartialViewMacro.ascx.cs | 79 --- .../create/PartialViewMacro.ascx.designer.cs | 87 ---- src/Umbraco.Web.UI/umbraco/create/User.ascx | 35 -- .../umbraco/create/User.ascx.cs | 82 ---- .../umbraco/create/User.ascx.designer.cs | 105 ---- .../umbraco/create/language.ascx | 18 - src/Umbraco.Web.UI/umbraco/create/script.ascx | 34 -- src/Umbraco.Web.UI/umbraco/create/xslt.ascx | 30 -- .../umbraco/create/xslt.ascx.cs | 11 - .../umbraco/create/xslt.ascx.designer.cs | 15 - src/Umbraco.Web.UI/umbraco/css/background.gif | Bin 151 -> 0 bytes .../umbraco/css/permissionsEditor.css | 43 -- src/Umbraco.Web.UI/umbraco/css/splitter.gif | Bin 88 -> 0 bytes src/Umbraco.Web.UI/umbraco/css/umbracoGui.css | 455 ------------------ .../umbraco/users/EditUser.aspx | 14 - .../umbraco/users/EditUser.aspx.cs | 11 - .../umbraco/users/EditUser.aspx.designer.cs | 15 - .../umbraco/users/EditUserType.aspx | 27 -- .../umbraco/users/NodePermissions.ascx | 35 -- .../umbraco/users/PermissionEditor.aspx | 47 -- .../umbraco/users/PermissionsEditor.js | 144 ------ .../umbraco/users/PermissionsHandler.asmx | 1 - src/Umbraco.Web/Trees/XsltTreeController.cs | 69 --- src/Umbraco.Web/Umbraco.Web.csproj | 1 - 45 files changed, 2 insertions(+), 1458 deletions(-) delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/dictionaryItem.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/help.png delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insChildTemplateNew.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insField.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insFieldByLevel.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insFieldByTree.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insMacro.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insMacroSB.png delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insMemberItem.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/insRazorMacro.png delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/inshtml.GIF delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/masterpageContent.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/masterpagePlaceHolder.gif delete mode 100644 src/Umbraco.Web.UI/Umbraco/Images/editor/xslVisualize.gif delete mode 100644 src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/create/User.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/create/User.ascx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/create/User.ascx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/create/language.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/create/script.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/create/xslt.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/create/xslt.ascx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/create/xslt.ascx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/css/background.gif delete mode 100644 src/Umbraco.Web.UI/umbraco/css/permissionsEditor.css delete mode 100644 src/Umbraco.Web.UI/umbraco/css/splitter.gif delete mode 100644 src/Umbraco.Web.UI/umbraco/css/umbracoGui.css delete mode 100644 src/Umbraco.Web.UI/umbraco/users/EditUser.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/users/EditUser.aspx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/users/EditUser.aspx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/users/EditUserType.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/users/NodePermissions.ascx delete mode 100644 src/Umbraco.Web.UI/umbraco/users/PermissionEditor.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/users/PermissionsEditor.js delete mode 100644 src/Umbraco.Web.UI/umbraco/users/PermissionsHandler.asmx delete mode 100644 src/Umbraco.Web/Trees/XsltTreeController.cs diff --git a/build/NuSpecs/tools/trees.config.install.xdt b/build/NuSpecs/tools/trees.config.install.xdt index 5a549e3fd8..dc59b5db10 100644 --- a/build/NuSpecs/tools/trees.config.install.xdt +++ b/build/NuSpecs/tools/trees.config.install.xdt @@ -86,9 +86,6 @@ - create.aspx - - xslt.ascx - ASPXCodeBehind - - - xslt.ascx - UserControlProxy.aspx ASPXCodeBehind @@ -573,13 +566,7 @@ - - UserControl - - - UserControl - diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/dictionaryItem.gif b/src/Umbraco.Web.UI/Umbraco/Images/editor/dictionaryItem.gif deleted file mode 100644 index e9dc737967820c2eacff5ccae0a6b8ddc60f6d3f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1040 zcmeH`YfF=106^buUJDBm%tCC6go*@Ff@#nyHOmmAK8TIb5VbHcA^l)p*w!p4%?wPi zT1=aoQ)kn;T&8Z`CL21OCf>F=-PO%)y1m!uE&CIF>HL8M2hQ~y8Oaw5!l4t8j|HVM zE4qi3Y0S#Bdll)-N&=AW0}Aoj{PZe3w+^c}k&bVZ8Uyl0JjEButu7qHNw=3!X?6So z#kK=?>=QjwW%uyxx&;*sPPGU|1cTF{mkWA0ptD-F2@^sNij#VSS!ctXc9(J;UfxDl zc2JU^ota;?X~hs6^p4COAYgQM*^2-~#zBR}mL0RxWbvZFsr`u);QQp_veCDsKY(p| zzDV(`q5XM_&^j+$&?A_nrJVbrPo{!VAo`*5YWiRd_)tLfy)e6Q1Os*t?lJ9PIB+=j zJuo*0~?qjZT7dwCn(8JzakQO|B-S|oTsQTUBXp>J;v#9eR z!iRP@?)DLS8)mfmfS}5}hr7IlacRzG)U9k-@vr%SBv;L7w`6u`LPK;hbBbzB+SzR< zzGg<%n=mp^u2}IA{Uu(9-MLTL+}N)j)Z)Sy^f37s=s*9WKs4efcsYql<=NzexQ$*{|74oPz zOWx=`yzEvQEsxc9HNF00LiLb%yo^z&rbahhil<%+h)Sv9L?po?M)R?}x>sG43`KB! zI22i$15pFxZWZ-3u?<-br^|9rU4RN^qGGe=-@8KDA-v-!%hgG5{W;CCxpzB5<%}yY z1MVEnE@|R&>d)Wa&;{}76qf&kkd$PkZXzi4OvIY2t+;-T6%d35?DVB6cUq=Rp^(V|(yIunMk|nMY zCBgY=CFO}lsSJ)O`AMk?p1FzXsX?iUDV2pMQ*D5XBm#UwTz!20PnmMc$7k99|NmQB z{x4g$?8S>0K=ww{#dm>fI7)*2f`MERV7S-3Hxejz+0(@_q~cam!f`GJrVhs41`Z4l z1=u(gWDYSfwm3^DG(0$zqvLSk7~4}u76G3bt*wkK5|WBB4Gc*R9h)|7I&_o~s4I&p zV9LyyGpBYo3g+-RFgUh2su>tJ3k1lhFbFtsB!*4k5oQ*S02(H6NFgw6Mpgqu6SuLW ztKup~CJv=D9FL3}p3G1HTF6q$sqAAad_)z*G*=Fgd19xwVmDCHGjBIHHGzhoLO>%D u4{+F7Q^!T|g{Kw7&1_p-z z|NjHYQ7{?;Lm~tef3h$#Fi0`zfLsg86AT>r45l119vc=MY~~QwiaD`i;o%kmm4FQm z4;LN)3nTyBj+{C!d(emK<~? rAUNUVWKG_CcOnW>Pfus7?NZ4UTIw}T&pPYwsjaK8uV-auVz34Pz2|1g diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/insField.gif b/src/Umbraco.Web.UI/Umbraco/Images/editor/insField.gif deleted file mode 100644 index 3a3721dd352923b0dd762d8144f383770eb9f040..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 648 zcmZ?wbhEHb6k`x)cvi&l@83UD&*aIAwm*IQ```Ds|IWAn`u%t6lATL89li7X*X2h) z-+un{|3vxUm$h#`{dxQ8&;Q@YAMOwS@?!nvhd=Lc)BE!M@Bd{=pTGY-aP{k~6?^}$ zHU9r`^118JfByb^==9D1pQoL={r$lX!-q!_YkHUbcsYC8(p}Gv#lF4K^M8Thx7S;~ zznJy;K$^U;J zwhzvkzHGN&V%3w~CjUQ9czh`0&l1Hick@5r$@zC}#-A%Qeyn%?v&s42tJ6>3{(k=a z)xVE--rlUS^v!s5w*TG5{l%`*S`%T=MsITYORX^8=O}_nr&SY?{7o z*X?y`3)UU_|FP%hDy0{XZnaHY`}hBc{|D2ypZ_{{_5PJxPrQG2YvH;>4~`TRwaoed zVe-#cvp?S2`S0a)ARlIiR=@nZ~{Qv)-fjFS}lZBCip@=~Tq#P6{4D3%E zikg~RTHD$?I=i}?($%w~EP{M{nu8T%?CnGhrZ%a_3m93-dð1cXM|rP9$Nm<7V_vmP5yuk@r_P*fHdNvb%XKnmm6CF2 z;bZ2EzTKkFz~U^%%EH5{U9)A-LdDbGvrI2?YaZ f<->i@83UD&*aIAwm*IQo8gS{uit;CF4_6{K6EzYW*ymsg5?=NP3xtss<)$E@yCeK~H|Nrm9&rU`^ zI8yNO;gY|v+uq*j`Tt{ocxF?4QTMc^yZ(Qe?3Y;eWVgw)W3fM8&Yrb$-<=~BE4Q9# zo3{4<$DVJmw>)|K`}qM&``{c)-;B36YwmA1_khd`6;EHb>(8s^d29B6e!8}(WzM6s{r^8sSh()czwd7!9!ad}UGnbk%Tc4~RrOGF z3+idsj<$9WmWi0!WG2rapds&Q6&|Q)pl|GB@6hTcCFg1*Wx}v?7b}MgW2>^bo*cip z&aRyzd;&cCTNIplO^sw!*tvF{I&-esB8=D0&spdMHaE8M7k{+!xTth2R!HSb#D#^- s({-2((oQUJb>U+Rndjq?A~9p8ol2_Nkb{b`tARR$we)5zQ33?clG{->kj>S)%@Z9oPXcn&Retp%iVnY;GF*-C#>9h;>p|J zcaBut-)^vC>xqX)692w#dwZj2`}wcam+hXuY?pgf@weAo9vmt7{B-S)m$M)2F#P{x z|IJlO|NsAIpd(QH$->CM5Y3GqMMpqTHD$?I=i}?LjBduzr+}a^ z&;AxuZy7@y30DsGU8l~RYxeS$(R8#_JmJjB#AbD;Mg0WBb%y6J>|ZzQzGGnd#3si3 zwTbyotgu5sBdg~BZ7g@TI?QY05)o2~nbCdyK)ay&yQ&Wgos679We$=C7aNE diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/insMacro.gif b/src/Umbraco.Web.UI/Umbraco/Images/editor/insMacro.gif deleted file mode 100644 index eeb3cdb444ac6581d41b75834279ecf941fbd9f6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 610 zcmZ?wbhEHb6k`x)c*el+{Q1kbpZbFz3zh8d% zbLG|(Z$AAwaP{lrO($lp*t>k&nYpX?FIabI;krXhHyvHE^~B{zKiBR&y>aikL#J;( zdHehA=Rcpn|26eYp1f%L^kuuJE!{PB$n^m$|Gmo3p>wk3YqnelaR!MB6u-wsuOJ5u-USj+blZQoCJeLvOn{dE8Lvy*?E zpZ??GoS#>h{Jg&M=dJa>?rs0|V9)Qzhkidj_WSAafB*jd|Noz1pn>8~7Dfh!5C$EP zLqKujz`nmBq^Y^3wXIbkxU0LHSw>X0Jw#4YLY!MfSe0L1QBH2+q(zIH6uL~c^qIAF zELg<&7cSYnWvfO|V1U1$uaCEvr-z%yB&A?I(;iDhV-}%Jt#ZMZ!F@bzY+S6oiWj!t zfAH|pW)1geZZ1v^_I9>5)>f0Ay1P0%zIku;>qt9aPmdZ)&VmQI7dkZ6V^(Z1WOd_` zWZ-bo(C~=j7FTDB*?q97ja5iQT~kUxp@EHwQ%J#r!AocbpF#4e7Rz0004@NklPr%n+>$8H^hPNon+hbT)*dQnR%Evd}PvaQUQR6$J(}Q^-Akyd+A`%z6$Pn^)tv}By82qf%f3iUR3>PVpnO4r(|4{7 zwtG(5W}Ngxy`K3COFZPb1)t$jq3#!gG2vIZg z`8Nj7uN`ZHr=9zacBCkwZW51{@N%GjJ0u)<`n(- zQt--G@Ig?DKOdSHY<2DHgXt`rPrnY+q#tD@vw4Iv0;U`Ro$wFJ6OiVGfb{occM?k| zBf_5&K-X)Ax%dsXf=O%y;&79DO0U!+Ieq*3F`KE?b-|3CKp|FPfFH)GbyeSV2mfB%1&w`PA< z_2joVdLA4pIB@mbqqF@V?$7!E`|z`4v5yZ$e7T#y{ruOzuiI{}Qu=%+XTiEdpTGZI zvGv5XrMv!rm>izjRMWd;;krW`_nv$5_V>q!OV;i@{r2AC>C1LcU$*Q2#|ieqIqp%# zcaBuNy;<{MhvB=sGrzx>_4(=A=LalruT%T+a`vBB&EH;cX`8n8=d0QGw;Md!ZSwF) z;<@Y3|NsBbKu4hXlZBCiA(}x4WG5(27}zf~L^n0Jw6?W(bar(&>1c-q%IoX(G&}hy z8@WsPPHhU3mhm@`_71g^(^9lm_w-P0H4~TA2oaB9*tv_>(u%Rwk6%SnhTnA8P99+q z?)@z;;ZlY+62=TnOeasDZS{(j3J5lrWfBy;$;QfQajsSE1QRne)5}*1Z(FQST>tWw zOY{euV1v59Ln9NHhyH`=I2JW9Mu2fjrGiNgM%QrJ;80I6+%%$LtnjzeF;&>tof}4fM(S`H9 zRxshjqf?8s`B>nw85gEZDYwBf7mbILj_|;*H=O{l0{k1`uXIvgr8Q@(L8D5Cnieg} z8oE$a%_6s~2^ocTNXx52a#lH#(uG&-0YM^l9oYdl7qasw0pk4{e@c|4@uYC{ZP6y!7$3VQP z#r1j);9=<;5S~of0T|jLtS)^C{q_*lAH_*pY4=qurWc{DPWKk$${v+N2>JY_Z T!Jt=y00000NkvXXu0mjfyIlNb diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/inshtml.GIF b/src/Umbraco.Web.UI/Umbraco/Images/editor/inshtml.GIF deleted file mode 100644 index 3442c48cd48c9fdb78d08459a533baef47997cdd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 191 zcmZ?wbhEHb6k`x)*v!E2|NsB$>gtx3mIDV4R5LKN07XE8KvoNc0t+y}f#OdVMg|6E z1|5(H$P5RToPractGB8*oV8B4zMxVig0-E)!%?CyC4E;(ZZgBH<=-c;F&#@ZcF5s5 z7U{~Mp<>3!9P;sHFVz3j_fxPWUvMRMVdi) diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/masterpageContent.gif b/src/Umbraco.Web.UI/Umbraco/Images/editor/masterpageContent.gif deleted file mode 100644 index ad993382348565d4f7c7acdee5121d833c70bc9e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 132 zcmZ?wbhEHb6k`x)Sj586($aG5*f9nMhW}syWI%x8PZmZ71{MY#5ErDDf!Whz*PVX` zr#!U<8D5_;WN{YgOVV_3@?3Xd`zkfA{m#D|jBD&P*WTirqrav2OObMda|e%z^znt0 Z4t}wf417{@@nzn+X&Wkh^t^=_tN{TBF7^Nb diff --git a/src/Umbraco.Web.UI/Umbraco/Images/editor/masterpagePlaceHolder.gif b/src/Umbraco.Web.UI/Umbraco/Images/editor/masterpagePlaceHolder.gif deleted file mode 100644 index 00de9bed9ad59806e696ccad106b3f608e16cbf3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 286 zcmZ?wbhEHb6k`x)I3mWdbm`Kbo}RsX_pV*Lwxy+|y1M$$Pjwrc9Y~ z?%cWW-~WIA|Ns5>|IeR4zjp8W^Y=t=Vsbbj&ZE|)?%Z0yEF;3`$xUry@sI#Z?ciQrZ@QJW!usc-Ti^73s~Zhm@J&d&XZ9=&+|^yTZ0iBns8CoWmH zsek&cY4aBDIdo+D{Dtc_ZGQgx&88hYCQYAy<@)t|_wVmNa`@oUgW-{(D<;JLJ(l=( zbNHqi`DN+;lZ%}f_7z2k2R>im{$z&Zg?iJy@=g*(tzkmPw_3P))pFe*5`2PL-w{PFReEIU>!-x0p-@kkJ?(N&RZ{ECl{rdH* zSFc{aeEH(Vi|5auKYRA<>C>lAo;=yKY177y8#ip&uzvmeb?erxUAuP8nl-CeuU@rk zRd;uHRaI4DVxotK2QVbTAxZ+F_>+Z^fgztk2c!oSCk*Ug8uFW(TUy)NJK9sbds0*S zlarF#(-@~spTRh}EzLV1z;B_ix3?c-a(lW@c2stBc6MZTh<8eRhHp$xY+O!!Y)+`p zidLTtznI+kgv8vq+%Ugwt=?Gyd9itM@#gwkngOXkN3#OspT`^N8LDf`%zYB{!c2{k zLxfk7>v7A~PtSD&?(9BrfT>gU=p~Pfn_9WM1w~{WA_5p$4mojcO*zS=e1wHlP_DyZ z!jTJ-nh` - @@ -35,4 +34,4 @@ - \ No newline at end of file + diff --git a/src/Umbraco.Web.UI/config/trees.config b/src/Umbraco.Web.UI/config/trees.config index b647bcbcb6..3076936cd5 100644 --- a/src/Umbraco.Web.UI/config/trees.config +++ b/src/Umbraco.Web.UI/config/trees.config @@ -20,7 +20,6 @@ - @@ -39,4 +38,4 @@ - \ No newline at end of file + diff --git a/src/Umbraco.Web.UI/umbraco/config/create/UI.Release.xml b/src/Umbraco.Web.UI/umbraco/config/create/UI.Release.xml index 1a082ab916..69983469ae 100644 --- a/src/Umbraco.Web.UI/umbraco/config/create/UI.Release.xml +++ b/src/Umbraco.Web.UI/umbraco/config/create/UI.Release.xml @@ -59,13 +59,6 @@ - -
    XSLT file
    - /create/xslt.ascx - - - -
    member
    /create/member.ascx @@ -110,20 +103,6 @@
    - -
    Language
    - /create/language.ascx - - - -
    - -
    Language
    - /create/language.ascx - - - -
    diff --git a/src/Umbraco.Web.UI/umbraco/config/create/UI.xml b/src/Umbraco.Web.UI/umbraco/config/create/UI.xml index 46c93c6ede..a1bddce17e 100644 --- a/src/Umbraco.Web.UI/umbraco/config/create/UI.xml +++ b/src/Umbraco.Web.UI/umbraco/config/create/UI.xml @@ -68,13 +68,6 @@ - -
    XSLT file
    - /create/xslt.ascx - - - -
    membergroup
    /create/simple.ascx @@ -105,20 +98,6 @@
    - -
    Language
    - /create/language.ascx - - - -
    - -
    Language
    - /create/language.ascx - - - -
    diff --git a/src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx b/src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx deleted file mode 100644 index 99932fc2fe..0000000000 --- a/src/Umbraco.Web.UI/umbraco/create/PartialViewMacro.ascx +++ /dev/null @@ -1,38 +0,0 @@ -<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PartialViewMacro.ascx.cs" Inherits="Umbraco.Web.UI.Umbraco.Create.PartialViewMacro" %> -<%@ Import Namespace="umbraco" %> -<%@ Register TagPrefix="cc1" Namespace="umbraco.uicontrols" Assembly="controls" %> -<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %> - - - - - * - - Cannot end with '/' or '.' - - - - - - - - - - - - - - -
    [DataMember] string ControlType { get; set; } - - /// - /// Gets or sets the name of the assembly, which should be used by the Macro - /// - /// Will usually only be filled if the ScriptFile is a Usercontrol - [DataMember] - [Obsolete("This is no longer used, we should remove it in v8, CustomControl macros are gone")] - string ControlAssembly { get; set; } - + /// /// Gets or set the path to the Python file in use /// /// Optional: Can only be one of three Script, Python or Xslt [DataMember] string ScriptPath { get; set; } - - /// - /// Gets or sets the path to the Xslt file in use - /// - /// Optional: Can only be one of three Script, Python or Xslt - [DataMember] - string XsltPath { get; set; } - + /// /// Gets or sets a list of Macro Properties /// diff --git a/src/Umbraco.Core/Models/Macro.cs b/src/Umbraco.Core/Models/Macro.cs index bd05abb1c1..6e72942b6e 100644 --- a/src/Umbraco.Core/Models/Macro.cs +++ b/src/Umbraco.Core/Models/Macro.cs @@ -35,13 +35,11 @@ namespace Umbraco.Core.Models /// /// /// - /// - /// /// /// /// /// - public Macro(int id, Guid key, bool useInEditor, int cacheDuration, string @alias, string name, string controlType, string controlAssembly, string xsltPath, bool cacheByPage, bool cacheByMember, bool dontRender, string scriptPath) + public Macro(int id, Guid key, bool useInEditor, int cacheDuration, string @alias, string name, string controlType, bool cacheByPage, bool cacheByMember, bool dontRender, string scriptPath) : this() { Id = id; @@ -51,8 +49,6 @@ namespace Umbraco.Core.Models Alias = alias.ToCleanString(CleanStringType.Alias); Name = name; ControlType = controlType; - ControlAssembly = controlAssembly; - XsltPath = xsltPath; CacheByPage = cacheByPage; CacheByMember = cacheByMember; DontRender = dontRender; @@ -67,16 +63,12 @@ namespace Umbraco.Core.Models /// /// /// - /// - /// /// /// /// /// public Macro(string @alias, string name, string controlType = "", - string controlAssembly = "", - string xsltPath = "", string scriptPath = "", bool cacheByPage = false, bool cacheByMember = false, @@ -90,8 +82,6 @@ namespace Umbraco.Core.Models Alias = alias.ToCleanString(CleanStringType.Alias); Name = name; ControlType = controlType; - ControlAssembly = controlAssembly; - XsltPath = xsltPath; CacheByPage = cacheByPage; CacheByMember = cacheByMember; DontRender = dontRender; @@ -125,9 +115,7 @@ namespace Umbraco.Core.Models public readonly PropertyInfo CacheByMemberSelector = ExpressionHelper.GetPropertyInfo(x => x.CacheByMember); public readonly PropertyInfo DontRenderSelector = ExpressionHelper.GetPropertyInfo(x => x.DontRender); public readonly PropertyInfo ControlPathSelector = ExpressionHelper.GetPropertyInfo(x => x.ControlType); - public readonly PropertyInfo ControlAssemblySelector = ExpressionHelper.GetPropertyInfo(x => x.ControlAssembly); public readonly PropertyInfo ScriptPathSelector = ExpressionHelper.GetPropertyInfo(x => x.ScriptPath); - public readonly PropertyInfo XsltPathSelector = ExpressionHelper.GetPropertyInfo(x => x.XsltPath); public readonly PropertyInfo PropertiesSelector = ExpressionHelper.GetPropertyInfo(x => x.Properties); } @@ -281,17 +269,6 @@ namespace Umbraco.Core.Models set { SetPropertyValueAndDetectChanges(value, ref _scriptFile, Ps.Value.ControlPathSelector); } } - /// - /// Gets or sets the name of the assembly, which should be used by the Macro - /// - /// Will usually only be filled if the ControlType is a Usercontrol - [DataMember] - public string ControlAssembly - { - get { return _scriptAssembly; } - set { SetPropertyValueAndDetectChanges(value, ref _scriptAssembly, Ps.Value.ControlAssemblySelector); } - } - /// /// Gets or set the path to the Python file in use /// @@ -303,17 +280,6 @@ namespace Umbraco.Core.Models set { SetPropertyValueAndDetectChanges(value, ref _scriptPath, Ps.Value.ScriptPathSelector); } } - /// - /// Gets or sets the path to the Xslt file in use - /// - /// Optional: Can only be one of three Script, Python or Xslt - [DataMember] - public string XsltPath - { - get { return _xslt; } - set { SetPropertyValueAndDetectChanges(value, ref _xslt, Ps.Value.XsltPathSelector); } - } - /// /// Gets or sets a list of Macro Properties /// diff --git a/src/Umbraco.Core/Models/MacroTypes.cs b/src/Umbraco.Core/Models/MacroTypes.cs index 90eacf5171..310d6ccd7c 100644 --- a/src/Umbraco.Core/Models/MacroTypes.cs +++ b/src/Umbraco.Core/Models/MacroTypes.cs @@ -10,15 +10,11 @@ namespace Umbraco.Core.Models [DataContract(IsReference = true)] public enum MacroTypes { - [EnumMember] - Xslt = 1, [EnumMember] UserControl = 3, [EnumMember] Unknown = 4, [EnumMember] - Script = 6, - [EnumMember] PartialView = 7 } } diff --git a/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs b/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs index 821f092b38..2bfbcaba29 100644 --- a/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs @@ -37,15 +37,7 @@ namespace Umbraco.Core.Persistence.Dtos [Column("macroScriptType")] [NullSetting(NullSetting = NullSettings.Null)] public string ScriptType { get; set; } - - [Column("macroScriptAssembly")] - [NullSetting(NullSetting = NullSettings.Null)] - public string ScriptAssembly { get; set; } - - [Column("macroXSLT")] - [NullSetting(NullSetting = NullSettings.Null)] - public string Xslt { get; set; } - + [Column("macroCacheByPage")] [Constraint(Default = "1")] public bool CacheByPage { get; set; } diff --git a/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs b/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs index a854a3a65f..a85de1fa57 100644 --- a/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs +++ b/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs @@ -9,7 +9,7 @@ namespace Umbraco.Core.Persistence.Factories { public IMacro BuildEntity(MacroDto dto) { - var model = new Macro(dto.Id, dto.UniqueId, dto.UseInEditor, dto.RefreshRate, dto.Alias, dto.Name, dto.ScriptType, dto.ScriptAssembly, dto.Xslt, dto.CacheByPage, dto.CachePersonalized, dto.DontRender, dto.MacroFilePath); + var model = new Macro(dto.Id, dto.UniqueId, dto.UseInEditor, dto.RefreshRate, dto.Alias, dto.Name, dto.ScriptType, dto.CacheByPage, dto.CachePersonalized, dto.DontRender, dto.MacroFilePath); try { @@ -42,10 +42,8 @@ namespace Umbraco.Core.Persistence.Factories Name = entity.Name, MacroFilePath = entity.ScriptPath, RefreshRate = entity.CacheDuration, - ScriptAssembly = entity.ControlAssembly, ScriptType = entity.ControlType, UseInEditor = entity.UseInEditor, - Xslt = entity.XsltPath, MacroPropertyDtos = BuildPropertyDtos(entity) }; diff --git a/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs b/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs index c60feea9b8..07490a4cd8 100644 --- a/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs +++ b/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs @@ -18,14 +18,12 @@ namespace Umbraco.Core.Persistence.Mappers CacheMap(src => src.Alias, dto => dto.Alias); CacheMap(src => src.CacheByPage, dto => dto.CacheByPage); CacheMap(src => src.CacheByMember, dto => dto.CachePersonalized); - CacheMap(src => src.ControlAssembly, dto => dto.ScriptAssembly); CacheMap(src => src.ControlType, dto => dto.ScriptType); CacheMap(src => src.DontRender, dto => dto.DontRender); CacheMap(src => src.Name, dto => dto.Name); CacheMap(src => src.CacheDuration, dto => dto.RefreshRate); CacheMap(src => src.ScriptPath, dto => dto.MacroFilePath); CacheMap(src => src.UseInEditor, dto => dto.UseInEditor); - CacheMap(src => src.XsltPath, dto => dto.Xslt); } } } diff --git a/src/Umbraco.Core/Services/EntityXmlSerializer.cs b/src/Umbraco.Core/Services/EntityXmlSerializer.cs index 72838c3d55..772d1f183d 100644 --- a/src/Umbraco.Core/Services/EntityXmlSerializer.cs +++ b/src/Umbraco.Core/Services/EntityXmlSerializer.cs @@ -296,9 +296,7 @@ namespace Umbraco.Core.Services xml.Add(new XElement("name", macro.Name)); xml.Add(new XElement("alias", macro.Alias)); xml.Add(new XElement("scriptType", macro.ControlType)); - xml.Add(new XElement("scriptAssembly", macro.ControlAssembly)); xml.Add(new XElement("scriptingFile", macro.ScriptPath)); - xml.Add(new XElement("xslt", macro.XsltPath)); xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); xml.Add(new XElement("dontRender", macro.DontRender.ToString())); xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); diff --git a/src/Umbraco.Core/Services/Implement/MacroService.cs b/src/Umbraco.Core/Services/Implement/MacroService.cs index a28bb7ca50..1e0be6c4b3 100644 --- a/src/Umbraco.Core/Services/Implement/MacroService.cs +++ b/src/Umbraco.Core/Services/Implement/MacroService.cs @@ -31,9 +31,6 @@ namespace Umbraco.Core.Services.Implement /// internal static MacroTypes GetMacroType(IMacro macro) { - if (string.IsNullOrEmpty(macro.XsltPath) == false) - return MacroTypes.Xslt; - if (string.IsNullOrEmpty(macro.ScriptPath) == false) return MacroTypes.PartialView; diff --git a/src/Umbraco.Core/Services/Implement/PackagingService.cs b/src/Umbraco.Core/Services/Implement/PackagingService.cs index c83500c5d3..04e52833d6 100644 --- a/src/Umbraco.Core/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Core/Services/Implement/PackagingService.cs @@ -1271,8 +1271,6 @@ namespace Umbraco.Core.Services.Implement var macroName = macroElement.Element("name").Value; var macroAlias = macroElement.Element("alias").Value; var controlType = macroElement.Element("scriptType").Value; - var controlAssembly = macroElement.Element("scriptAssembly").Value; - var xsltPath = macroElement.Element("xslt").Value; var scriptPath = macroElement.Element("scriptingFile").Value; //Following xml elements are treated as nullable properties @@ -1308,7 +1306,7 @@ namespace Umbraco.Core.Services.Implement } var existingMacro = _macroService.GetByAlias(macroAlias) as Macro; - var macro = existingMacro ?? new Macro(macroAlias, macroName, controlType, controlAssembly, xsltPath, scriptPath, + var macro = existingMacro ?? new Macro(macroAlias, macroName, controlType, scriptPath, cacheByPage, cacheByMember, dontRender, useInEditor, cacheDuration); var properties = macroElement.Element("properties"); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index e9a781d560..bbb020f308 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -562,10 +562,6 @@ - - - - diff --git a/src/Umbraco.Tests/Composing/TypeFinderTests.cs b/src/Umbraco.Tests/Composing/TypeFinderTests.cs index 29458deefb..c665fc366e 100644 --- a/src/Umbraco.Tests/Composing/TypeFinderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeFinderTests.cs @@ -100,70 +100,6 @@ namespace Umbraco.Tests.Composing return new ProfilingLogger(logger, profiler); } - [Ignore("fixme - ignored test")] - [Test] - public void Benchmark_Original_Finder() - { - var profilingLogger = GetTestProfilingLogger(); - using (profilingLogger.TraceDuration("Starting test", "Finished test")) - { - using (profilingLogger.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinderOriginal.FindClassesOfType(_assemblies).Count(), 0); - } - } - using (profilingLogger.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute(_assemblies).Count(), 0); - } - } - using (profilingLogger.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinderOriginal.FindClassesWithAttribute(_assemblies).Count(), 0); - } - } - } - - } - - [Ignore("fixme - ignored test")] - [Test] - public void Benchmark_New_Finder() - { - var profilingLogger = GetTestProfilingLogger(); - using (profilingLogger.TraceDuration("Starting test", "Finished test")) - { - using (profilingLogger.TraceDuration("Starting FindClassesOfType", "Finished FindClassesOfType")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinder.FindClassesOfType(_assemblies).Count(), 0); - } - } - using (profilingLogger.TraceDuration("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinder.FindClassesOfTypeWithAttribute(_assemblies).Count(), 0); - } - } - using (profilingLogger.TraceDuration("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) - { - for (var i = 0; i < 1000; i++) - { - Assert.Greater(TypeFinder.FindClassesWithAttribute(_assemblies).Count(), 0); - } - } - } - - } - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class MyTestAttribute : Attribute { diff --git a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs index 6fba071709..4cdd9687f5 100644 --- a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs @@ -288,14 +288,7 @@ AnotherContentFinder var types = _typeLoader.GetDataEditors(); Assert.AreEqual(43, types.Count()); } - - [Test] - public void Resolves_XsltExtensions() - { - var types = _typeLoader.GetXsltExtensions(); - Assert.AreEqual(3, types.Count()); - } - + /// /// This demonstrates this issue: http://issues.umbraco.org/issue/U4-3505 - the TypeList was returning a list of assignable types /// not explicit types which is sort of ideal but is confusing so we'll do it the less confusing way. @@ -319,12 +312,6 @@ AnotherContentFinder Assert.IsNull(shouldNotFind); } - [XsltExtension("Blah.Blah")] - public class MyXsltExtension - { - - } - public interface IFindMe : IDiscoverable { diff --git a/src/Umbraco.Tests/Composing/XsltExtensionCollectionTests.cs b/src/Umbraco.Tests/Composing/XsltExtensionCollectionTests.cs deleted file mode 100644 index 399b1df7bb..0000000000 --- a/src/Umbraco.Tests/Composing/XsltExtensionCollectionTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Linq; -using LightInject; -using NUnit.Framework; -using Umbraco.Core.Macros; -using Umbraco.Web; - -namespace Umbraco.Tests.Composing -{ - [TestFixture] - public class XsltExtensionCollectionTests : ComposingTestBase - { - [Test] - public void XsltExtensionsCollectionBuilderWorks() - { - var container = new ServiceContainer(); - var builder = new XsltExtensionCollectionBuilder(container); - builder.AddExtensionObjectProducer(() => TypeLoader.GetXsltExtensions()); - var extensions = builder.CreateCollection(); - - Assert.AreEqual(3, extensions.Count()); - - Assert.IsTrue(extensions.Select(x => x.ExtensionObject.GetType()).Contains(typeof (XsltEx1))); - Assert.IsTrue(extensions.Select(x => x.ExtensionObject.GetType()).Contains(typeof(XsltEx2))); - Assert.AreEqual("test1", extensions.Single(x => x.ExtensionObject.GetType() == typeof(XsltEx1)).Namespace); - Assert.AreEqual("test2", extensions.Single(x => x.ExtensionObject.GetType() == typeof(XsltEx2)).Namespace); - } - - #region Test Objects - - [XsltExtension("test1")] - public class XsltEx1 - { } - - //test with legacy one - [umbraco.XsltExtension("test2")] - public class XsltEx2 - { } - - #endregion - } -} diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index e3a4db5390..98d36ca616 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -78,7 +78,6 @@ namespace Umbraco.Tests.Macros var model = new MacroModel { MacroType = macroType, - Xslt = "anything", ScriptName = "anything", TypeName = "anything" }; diff --git a/src/Umbraco.Tests/Models/MacroTests.cs b/src/Umbraco.Tests/Models/MacroTests.cs index 052c42942b..c1fda841c2 100644 --- a/src/Umbraco.Tests/Models/MacroTests.cs +++ b/src/Umbraco.Tests/Models/MacroTests.cs @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Models [Test] public void Can_Deep_Clone() { - var macro = new Macro(1, Guid.NewGuid(), true, 3, "test", "Test", "blah", "blah", "xslt", false, true, true, "script"); + var macro = new Macro(1, Guid.NewGuid(), true, 3, "test", "Test", "blah", false, true, true, "script"); macro.Properties.Add(new MacroProperty(6, Guid.NewGuid(), "rewq", "REWQ", 1, "asdfasdf")); var clone = (Macro)macro.DeepClone(); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs index de013426b7..d4dbd51991 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs @@ -37,7 +37,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "MyAssembly", "test.xslt", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); ; Assert.Throws(() => repository.Save(macro)); @@ -94,14 +94,12 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(macro.Alias, Is.EqualTo("test1")); Assert.That(macro.CacheByPage, Is.EqualTo(false)); Assert.That(macro.CacheByMember, Is.EqualTo(false)); - Assert.That(macro.ControlAssembly, Is.EqualTo("MyAssembly1")); Assert.That(macro.ControlType, Is.EqualTo("~/usercontrol/test1.ascx")); Assert.That(macro.DontRender, Is.EqualTo(true)); Assert.That(macro.Name, Is.EqualTo("Test1")); Assert.That(macro.CacheDuration, Is.EqualTo(0)); Assert.That(macro.ScriptPath, Is.EqualTo("~/views/macropartials/test1.cshtml")); Assert.That(macro.UseInEditor, Is.EqualTo(false)); - Assert.That(macro.XsltPath, Is.EqualTo("test1.xslt")); } @@ -171,7 +169,7 @@ namespace Umbraco.Tests.Persistence.Repositories var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); // Act - var macro = new Macro("test", "Test", "~/usercontrol/blah.ascx", "MyAssembly", "test.xslt", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); macro.Properties.Add(new MacroProperty("test", "Test", 0, "test")); repository.Save(macro); @@ -197,12 +195,10 @@ namespace Umbraco.Tests.Persistence.Repositories macro.CacheDuration = 1234; macro.CacheByPage = true; macro.CacheByMember = true; - macro.ControlAssembly = ""; macro.ControlType = ""; macro.DontRender = false; macro.ScriptPath = "~/newpath.cshtml"; macro.UseInEditor = true; - macro.XsltPath = ""; repository.Save(macro); @@ -214,12 +210,10 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(macroUpdated.CacheDuration, Is.EqualTo(1234)); Assert.That(macroUpdated.CacheByPage, Is.EqualTo(true)); Assert.That(macroUpdated.CacheByMember, Is.EqualTo(true)); - Assert.That(macroUpdated.ControlAssembly, Is.EqualTo("")); Assert.That(macroUpdated.ControlType, Is.EqualTo("")); Assert.That(macroUpdated.DontRender, Is.EqualTo(false)); Assert.That(macroUpdated.ScriptPath, Is.EqualTo("~/newpath.cshtml")); Assert.That(macroUpdated.UseInEditor, Is.EqualTo(true)); - Assert.That(macroUpdated.XsltPath, Is.EqualTo("")); } } @@ -299,7 +293,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "MyAssembly1", "test1.xslt", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); @@ -324,7 +318,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "MyAssembly1", "test1.xslt", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); @@ -348,7 +342,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "MyAssembly1", "test1.xslt", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); @@ -434,9 +428,9 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "MyAssembly1", "test1.xslt", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "MyAssembly2", "test2.xslt", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "MyAssembly3", "test3.xslt", "~/views/macropartials/test3.cshtml")); + repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml")); + repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "~/views/macropartials/test2.cshtml")); + repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "~/views/macropartials/test3.cshtml")); scope.Complete(); } diff --git a/src/Umbraco.Tests/Services/MacroServiceTests.cs b/src/Umbraco.Tests/Services/MacroServiceTests.cs index c7e2978b19..44c5596bfc 100644 --- a/src/Umbraco.Tests/Services/MacroServiceTests.cs +++ b/src/Umbraco.Tests/Services/MacroServiceTests.cs @@ -28,9 +28,9 @@ namespace Umbraco.Tests.Services { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "MyAssembly1", "test1.xslt", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "MyAssembly2", "test2.xslt", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "MyAssembly3", "test3.xslt", "~/views/macropartials/test3.cshtml")); + repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml")); + repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "~/views/macropartials/test2.cshtml")); + repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "~/views/macropartials/test3.cshtml")); scope.Complete(); } } diff --git a/src/Umbraco.Tests/Services/PackagingServiceTests.cs b/src/Umbraco.Tests/Services/PackagingServiceTests.cs index 17c065338d..36093e4feb 100644 --- a/src/Umbraco.Tests/Services/PackagingServiceTests.cs +++ b/src/Umbraco.Tests/Services/PackagingServiceTests.cs @@ -23,7 +23,7 @@ namespace Umbraco.Tests.Services public void PackagingService_Can_Export_Macro() { // Arrange - var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "MyAssembly", "test.xslt", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); ServiceContext.MacroService.Save(macro); // Act diff --git a/src/Umbraco.Tests/UI/LegacyDialogTests.cs b/src/Umbraco.Tests/UI/LegacyDialogTests.cs index 5a978fb418..13503e4223 100644 --- a/src/Umbraco.Tests/UI/LegacyDialogTests.cs +++ b/src/Umbraco.Tests/UI/LegacyDialogTests.cs @@ -22,7 +22,6 @@ namespace Umbraco.Tests.UI } } - [TestCase(typeof(XsltTasks), Constants.Applications.Developer)] [TestCase(typeof(StylesheetTasks), Constants.Applications.Settings)] [TestCase(typeof(stylesheetPropertyTasks), Constants.Applications.Settings)] [TestCase(typeof(MemberGroupTasks), Constants.Applications.Members)] diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 0d964dcd21..3eb6d8ae73 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -335,7 +335,6 @@ - diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 787742de4e..451b5c5a32 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -567,7 +567,6 @@ - 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 b1997a1c0a..c362f91df0 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml @@ -378,8 +378,6 @@ 讀取使用者控制項 %0% 錯誤 讀取使用者控制項 %0% 錯誤(組件:%0%,類別:%1%) 讀取巨集引擎腳本錯誤(檔案:%0%) - 分析XSLT檔案錯誤:%0% - 讀取XSLT檔案錯誤:%0% 請輸入標題 請選擇類型 圖片尺寸大於原始尺寸不會提高圖片品質,您確定要把圖片尺寸變大嗎? @@ -1350,4 +1348,4 @@ 轉址追蹤器已開啟。 啟動轉址追蹤器錯誤,更多資訊請參閱您的紀錄檔。 - \ No newline at end of file + diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/umbraco/config/lang/en.xml index 993f845831..50ee041e9f 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/en.xml @@ -434,8 +434,6 @@ Error loading userControl '%0%' Error loading customControl (Assembly: %0%, Type: '%1%') Error loading MacroEngine script (file: %0%) - "Error parsing XSLT file: %0% - "Error reading XSLT file: %0% Please enter a title Please choose a type You're about to make the picture larger than the original size. Are you sure that you want to proceed? 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 d3326c57b3..6304fda60f 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/en_us.xml @@ -503,8 +503,6 @@ Error loading userControl '%0%' Error loading customControl (Assembly: %0%, Type: '%1%') Error loading MacroEngine script (file: %0%) - "Error parsing XSLT file: %0% - "Error reading XSLT file: %0% Please enter a title Please choose a type You're about to make the picture larger than the original size. Are you sure that you want to proceed? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/es.xml b/src/Umbraco.Web.UI/umbraco/config/lang/es.xml index cf44e6e955..a259c11346 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/es.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/es.xml @@ -487,8 +487,6 @@ Error cargando userControl '%0%' Error cargandog customControl (Assembly: %0%, Type: '%1%') Error cargando MacroEngine script (file: %0%) - "Error analizando archivo XSLT: %0% - "Error leyendo archivo XSLT: %0% diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/fr.xml b/src/Umbraco.Web.UI/umbraco/config/lang/fr.xml index 37a3795d12..e047ff611b 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/fr.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/fr.xml @@ -388,8 +388,6 @@ Erreur de chargement du userControl '%0%' Erreur de chargement d'un customControl (Assembly: %0%, Type: '%1%') Erreur de chargement d'un script du MacroEngine (fichier : %0%) - "Erreur de parsing d'un fichier XSLT : %0% - "Erreur de lecture d'un fichier XSLT : %0% Veuillez entrer un titre Veuillez choisir un type Vous allez définir une taille d'image supérieure à sa taille d'origine. Êtes-vous certain(e) de vouloir continuer? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/ja.xml b/src/Umbraco.Web.UI/umbraco/config/lang/ja.xml index 36e294f1b8..1fcb8d889c 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/ja.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/ja.xml @@ -370,8 +370,6 @@ userControl の読み込みエラー '%0%' customControl の読み込みエラー (アセンブリ: %0%, タイプ: '%1%') MacroEngine スクリプトの読み込みエラー (ファイル: %0%) - XSLT ファイル解析エラー: %0% - XSLT ファイル読み込みエラー: %0% タイトルを入力してください 型を選択してください 元画像より大きくしようとしていますが、本当によろしいのですか? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/nl.xml b/src/Umbraco.Web.UI/umbraco/config/lang/nl.xml index d398a839ec..dd7f5b58a2 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/nl.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/nl.xml @@ -398,8 +398,6 @@ Error bij het laden van userControl '%0%' Error bij het laden van customControl (Assembly: %0%, Type: '%1%') Error bij het laden van MacroEngine script (file: %0%) - "Error bij het parsen van XSLT file: %0% - "Error bij het laden van XSLT file: %0% Vul een titel in Selecteer een type U wilt een afbeelding groter maken dan de originele afmetingen. Weet je zeker dat je wilt doorgaan? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/pl.xml b/src/Umbraco.Web.UI/umbraco/config/lang/pl.xml index d47b06d10e..39e70003fe 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/pl.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/pl.xml @@ -487,8 +487,6 @@ Wystąpił błąd podczas ładowania userControl '%0%' Wystąpił błąd podczas ładowania customControl (Assembly: %0%, Typ: '%1%') Wystąpił błąd podczas ładowania skryptu MacroEngine (plik: %0%) - "Wystąpił błąd podczas parsowania pliku XSLT: %0% - "Wystąpił błąd odczytu pliku XSLT: %0% Proszę podać tytuł Proszę wybrać typ Chcesz utworzyć obraz większy niż rozmiar oryginalny. Czy na pewno chcesz kontynuować? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/ru.xml b/src/Umbraco.Web.UI/umbraco/config/lang/ru.xml index 009fbdb683..d234ab0e62 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/ru.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/ru.xml @@ -512,8 +512,6 @@ Ошибка загрузки пользовательского элемента управления '%0%' Ошибка загрузки внешнего типа (сборка: %0%, тип: '%1%') Ошибка загрузки макроса (файл: %0%) - "Ошибка разбора кода XSLT в файле: %0% - "Ошибка чтения XSLT-файла: %0% Ошибка в конфигурации типа данных, используемого для свойства, проверьте тип данных Укажите заголовок Выберите тип diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/tr.xml b/src/Umbraco.Web.UI/umbraco/config/lang/tr.xml index 8436976f9e..0439b09b3a 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/tr.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/tr.xml @@ -314,8 +314,6 @@ Error loading userControl '%0%' Error loading customControl (Assembly: %0%, Type: '%1%') Error loading MacroEngine script (Dosya: %0%) - "Error parsing XSLT file: %0% - "Error reading XSLT file: %0% Lütfen bir başlık girin Lütfen bir tür seçin Orijinal boyutundan daha resmi büyütmek üzereyiz. Devam etmek istediğinizden emin misiniz? diff --git a/src/Umbraco.Web.UI/umbraco/config/lang/zh.xml b/src/Umbraco.Web.UI/umbraco/config/lang/zh.xml index fed9f9d057..9513536c98 100644 --- a/src/Umbraco.Web.UI/umbraco/config/lang/zh.xml +++ b/src/Umbraco.Web.UI/umbraco/config/lang/zh.xml @@ -393,8 +393,6 @@ 加载 userControl 时出错 '%0%' 加载 customControl 时出错(程序集: %0%, 类型: '%1%') 加载 MacroEngine 脚本时出错 (文件: %0%) - "解析 xslt 文件时出错: %0% - "读取 xslt 文件时出错: %0% 请输入标题 请选择类型 图片尺寸大于原始尺寸不会提高图片质量,您确定要把图片尺寸变大吗? diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs index d01d9b08e7..621b2926e6 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs @@ -29,9 +29,9 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Macros /// /// /// - protected override void PopulateFieldsOnLoad(IMacro macro, string macroAssemblyValue, string macroTypeValue) + protected override void PopulateFieldsOnLoad(IMacro macro, string macroTypeValue) { - base.PopulateFieldsOnLoad(macro, macroAssemblyValue, macroTypeValue); + base.PopulateFieldsOnLoad(macro, macroTypeValue); //check if the ScriptingFile property contains the MacroPartials path if (macro.ScriptPath.IsNullOrWhiteSpace() == false && (macro.ScriptPath.StartsWith(SystemDirectories.MvcViews + "/MacroPartials/") diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs index a64101c102..a1febaa2ba 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs @@ -3,15 +3,15 @@ // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // //------------------------------------------------------------------------------ namespace Umbraco.Web.UI.Umbraco.Developer.Macros { - - + + public partial class EditMacro { - + /// /// CssInclude1 control. /// @@ -20,7 +20,7 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Macros { /// To modify move field declaration from designer file to code-behind file. /// protected global::ClientDependency.Core.Controls.CssInclude CssInclude1; - + /// /// SelectedPartialView control. /// @@ -29,7 +29,7 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Macros { /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox SelectedPartialView; - + /// /// PartialViewList control. /// diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/assemblyBrowser.aspx b/src/Umbraco.Web.UI/umbraco/developer/Macros/assemblyBrowser.aspx deleted file mode 100644 index 4aaf155fa1..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/assemblyBrowser.aspx +++ /dev/null @@ -1,28 +0,0 @@ -<%@ Page Language="c#" MasterPageFile="../../masterpages/umbracoPage.Master" Title="Assembly Browser" Codebehind="assemblyBrowser.aspx.cs" AutoEventWireup="True" - Inherits="umbraco.developer.assemblyBrowser" %> - - -

    - -

    The following list shows the Public Properties from the - Control. By checking the Properties and click the "Save Properties" button at - - the bottom, umbraco will create the corresponding Macro Elements.

    - -

    - -

    -
    - - -

    The following Macro Parameters was added:

    -
    -

    - Important: You might need to reload the macro to see the changes.

    - -

    - - -
    - -
    diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx b/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx index d6291f0511..fc8aff082d 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx @@ -68,27 +68,12 @@ - - - - - - - + - - - - - (Assembly)
    - - (Type) - -
    diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index d2a1ee6f80..e1317a902b 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -124,10 +124,7 @@ namespace Umbraco.Web.Composing internal static EditorValidatorCollection EditorValidators => Container.GetInstance(); - - internal static XsltExtensionCollection XsltExtensions - => Container.GetInstance(); - + internal static UmbracoApiControllerTypeCollection UmbracoApiControllerTypes => Container.GetInstance(); @@ -143,9 +140,6 @@ namespace Umbraco.Web.Composing internal static IPublishedSnapshotService PublishedSnapshotService => Container.GetInstance(); - public static ThumbnailProviderCollection ThumbnailProviders - => Container.GetInstance(); - #endregion #region Web Constants diff --git a/src/Umbraco.Web/CompositionExtensions.cs b/src/Umbraco.Web/CompositionExtensions.cs index 881a88c05f..e172af7b8a 100644 --- a/src/Umbraco.Web/CompositionExtensions.cs +++ b/src/Umbraco.Web/CompositionExtensions.cs @@ -33,15 +33,7 @@ namespace Umbraco.Core.Components /// internal static ActionCollectionBuilder Actions(this Composition composition) => composition.Container.GetInstance(); - - /// - /// Gets the content finders collection builder. - /// - /// The composition. - /// - internal static XsltExtensionCollectionBuilder XsltExtensions(this Composition composition) - => composition.Container.GetInstance(); - + /// /// Gets the content finders collection builder. /// @@ -80,13 +72,6 @@ namespace Umbraco.Core.Components internal static ImageUrlProviderCollectionBuilder ImageUrlProviders(this Composition composition) => composition.Container.GetInstance(); - /// - /// Gets the thumbnail providers collection builder. - /// - /// The composition. - internal static ThumbnailProviderCollectionBuilder ThumbnailProviders(this Composition composition) - => composition.Container.GetInstance(); - /// /// Gets the url providers collection builder. /// diff --git a/src/Umbraco.Web/Macros/MacroModel.cs b/src/Umbraco.Web/Macros/MacroModel.cs index 4239dbc827..28aad1b777 100644 --- a/src/Umbraco.Web/Macros/MacroModel.cs +++ b/src/Umbraco.Web/Macros/MacroModel.cs @@ -19,13 +19,8 @@ namespace Umbraco.Web.Macros public MacroTypes MacroType { get; set; } - // that one was for CustomControls which are gone in v8 - //public string TypeAssembly { get; set; } - public string TypeName { get; set; } - public string Xslt { get; set; } - public string ScriptName { get; set; } public string ScriptCode { get; set; } @@ -54,9 +49,7 @@ namespace Umbraco.Web.Macros Id = macro.Id; Name = macro.Name; Alias = macro.Alias; - //TypeAssembly = macro.ControlAssembly; TypeName = macro.ControlType; - Xslt = macro.XsltPath; ScriptName = macro.ScriptPath; CacheDuration = macro.CacheDuration; CacheByPage = macro.CacheByPage; diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index 9692b73b52..c1b613e2f2 100644 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -177,22 +177,12 @@ namespace Umbraco.Web.Macros switch (model.MacroType) { - case MacroTypes.Xslt: - filename = SystemDirectories.Xslt.EnsureEndsWith('/') + model.Xslt; - break; - //case MacroTypes.Script: - // // was "~/macroScripts/" - // filename = SystemDirectories.MacroScripts.EnsureEndsWith('/') + model.ScriptName; - // break; case MacroTypes.PartialView: filename = model.ScriptName; //partial views are saved with their full virtual path break; case MacroTypes.UserControl: filename = model.TypeName; //user controls are saved with their full virtual path break; - //case MacroTypes.Script: - //case MacroTypes.CustomControl: - //case MacroTypes.Unknown: default: // not file-based, or not supported filename = null; @@ -381,24 +371,7 @@ namespace Umbraco.Web.Macros "Executed PartialView.", () => ExecutePartialView(model), () => textService.Localize("errors/macroErrorLoadingPartialView", new[] { model.ScriptName })); - - //case MacroTypes.Script: - // return ExecuteMacroWithErrorWrapper(model, - // "Executing Script: " + (string.IsNullOrWhiteSpace(model.ScriptCode) - // ? "ScriptName=\"" + model.ScriptName + "\"" - // : "Inline, Language=\"" + model.ScriptLanguage + "\""), - // "Executed Script.", - // () => ExecuteScript(model), - // () => textService.Localize("errors/macroErrorLoadingMacroEngineScript", new[] { model.ScriptName })); - - case MacroTypes.Xslt: - return ExecuteMacroWithErrorWrapper(model, - $"Executing Xslt: TypeName=\"{model.TypeName}\", ScriptName=\"{model.Xslt}\".", - "Executed Xslt.", - () => ExecuteXslt(model, _plogger), - // cannot diff. between reading & parsing... bah - () => textService.Localize("errors/macroErrorParsingXSLTFile", new[] { model.Xslt })); - + case MacroTypes.UserControl: return ExecuteMacroWithErrorWrapper(model, $"Loading UserControl: TypeName=\"{model.TypeName}\".", @@ -447,16 +420,6 @@ namespace Umbraco.Web.Macros return engine.Execute(macro, content); } - /// - /// Renders an Xslt Macro. - /// - /// The text output of the macro execution. - public static MacroContent ExecuteXslt(MacroModel macro, ProfilingLogger plogger) - { - var engine = new XsltMacroEngine(plogger); - return engine.Execute(macro); - } - public static MacroContent ExecuteUserControl(MacroModel macro) { // add tilde for v4 defined macros diff --git a/src/Umbraco.Web/Macros/XsltMacroEngine.cs b/src/Umbraco.Web/Macros/XsltMacroEngine.cs deleted file mode 100644 index 10fd6b5305..0000000000 --- a/src/Umbraco.Web/Macros/XsltMacroEngine.cs +++ /dev/null @@ -1,687 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Web; -using System.Web.Caching; -using System.Xml; -using System.Xml.XPath; -using System.Xml.Xsl; -using umbraco; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Xml.XPath; -using Umbraco.Web.Composing; -using Umbraco.Web.Templates; - -namespace Umbraco.Web.Macros -{ - /// - /// A macro engine using XSLT to execute. - /// - public class XsltMacroEngine - { - private readonly Func _getHttpContext; - private readonly Func _getUmbracoContext; - private readonly ProfilingLogger _plogger; - - public XsltMacroEngine(ProfilingLogger plogger) - { - _plogger = plogger; - - _getHttpContext = () => - { - if (HttpContext.Current == null) - throw new InvalidOperationException("The Xslt Macro Engine cannot execute with a null HttpContext.Current reference"); - return new HttpContextWrapper(HttpContext.Current); - }; - - _getUmbracoContext = () => - { - if (UmbracoContext.Current == null) - throw new InvalidOperationException("The Xslt Macro Engine cannot execute with a null UmbracoContext.Current reference"); - return UmbracoContext.Current; - }; - } - - #region Execute Xslt - - // executes the macro, relying on GetXsltTransform - // will pick XmlDocument or Navigator mode depending on the capabilities of the published caches - public MacroContent Execute(MacroModel model) - { - var hasCode = string.IsNullOrWhiteSpace(model.ScriptCode) == false; - var hasXslt = string.IsNullOrWhiteSpace(model.Xslt) == false; - - if (hasXslt == false && hasCode == false) - { - Current.Logger.Warn("Xslt is empty"); - return MacroContent.Empty; - } - - if (hasCode && model.ScriptLanguage.InvariantEquals("xslt") == false) - { - Current.Logger.Warn("Unsupported script language \"" + model.ScriptLanguage + "\"."); - return MacroContent.Empty; - } - - var msg = "Executing Xslt: " + (hasCode ? "Inline." : "Xslt=\"" + model.Xslt + "\"."); - using (_plogger.DebugDuration(msg, "ExecutedXslt.")) - { - // need these two here for error reporting - MacroNavigator macroNavigator = null; - XmlDocument macroXml = null; - - IXPathNavigable macroNavigable; - IXPathNavigable contentNavigable; - - var xmlCache = UmbracoContext.Current.ContentCache as PublishedCache.XmlPublishedCache.PublishedContentCache; - - if (xmlCache == null) - { - // a different cache - // inheriting from NavigableNavigator is required - - var contentNavigator = UmbracoContext.Current.ContentCache.CreateNavigator() as NavigableNavigator; - var mediaNavigator = UmbracoContext.Current.MediaCache.CreateNavigator() as NavigableNavigator; - - if (contentNavigator == null || mediaNavigator == null) - throw new Exception("Published caches XPathNavigator do not inherit from NavigableNavigator."); - - var parameters = new List(); - foreach (var prop in model.Properties) - AddMacroParameter(parameters, contentNavigator, mediaNavigator, prop.Key, prop.Type, prop.Value); - - macroNavigable = macroNavigator = new MacroNavigator(parameters); - contentNavigable = UmbracoContext.Current.ContentCache; - } - else - { - // the original XML cache - // render the macro on top of the Xml document - - var umbracoXml = xmlCache.GetXml(UmbracoContext.Current.InPreviewMode); - - macroXml = new XmlDocument(); - macroXml.LoadXml(""); - - foreach (var prop in model.Properties) - AddMacroXmlNode(umbracoXml, macroXml, prop.Key, prop.Type, prop.Value); - - macroNavigable = macroXml; - contentNavigable = umbracoXml; - } - - // this is somewhat ugly but eh... - var httpContext = _getHttpContext(); - if (httpContext.Request.QueryString["umbDebug"] != null && GlobalSettings.DebugMode) - { - var outerXml = macroXml?.OuterXml ?? macroNavigator.OuterXml; - var text = $"
    Debug from {model.Name}
    {HttpUtility.HtmlEncode(outerXml)}
    "; - return new MacroContent { Text = text }; - } - - // get the transform - XslCompiledTransform transform; - if (hasCode) - { - try - { - using (var sreader = new StringReader(model.ScriptCode)) - using (var xreader = new XmlTextReader(sreader)) - { - transform = GetXsltTransform(xreader, GlobalSettings.DebugMode); - } - } - catch (Exception e) - { - throw new Exception("Failed to parse inline Xslt.", e); - } - } - else - { - try - { - transform = GetCachedXsltTransform(model.Xslt); - } - catch (Exception e) - { - throw new Exception($"Failed to read Xslt file \"{model.Xslt}\".", e); - } - } - - using (_plogger.DebugDuration("Performing transformation.", "Performed transformation.")) - { - try - { - var transformed = XsltTransform(_plogger, macroNavigable, contentNavigable, transform); - var text = TemplateUtilities.ResolveUrlsFromTextString(transformed); - return new MacroContent { Text = text }; - } - catch (Exception e) - { - throw new Exception($"Failed to exec Xslt file \"{model.Xslt}\".", e); - } - } - } - } - - /// - /// Adds the XSLT extension namespaces to the XSLT header using - /// {0} as the container for the namespace references and - /// {1} as the container for the exclude-result-prefixes - /// - /// The XSLT - /// The XSLT with {0} and {1} replaced. - /// This is done here because it needs the engine's XSLT extensions. - public static string AddXsltExtensionsToHeader(string xslt) - { - var namespaceList = new StringBuilder(); - var namespaceDeclaractions = new StringBuilder(); - foreach (var extension in GetXsltExtensions()) - { - namespaceList.Append(extension.Key).Append(' '); - namespaceDeclaractions.AppendFormat("xmlns:{0}=\"urn:{0}\" ", extension.Key); - } - - // parse xslt - xslt = xslt.Replace("{0}", namespaceDeclaractions.ToString()); - xslt = xslt.Replace("{1}", namespaceList.ToString()); - return xslt; - } - - public static string TestXsltTransform(ProfilingLogger plogger, string xsltText, int currentPageId = -1) - { - IXPathNavigable macroNavigable; - IXPathNavigable contentNavigable; - - var xmlCache = UmbracoContext.Current.ContentCache as PublishedCache.XmlPublishedCache.PublishedContentCache; - - var xslParameters = new Dictionary(); - xslParameters["currentPage"] = UmbracoContext.Current.ContentCache - .CreateNavigator() - .Select(currentPageId > 0 ? ("//* [@id=" + currentPageId + "]") : "//* [@parentID=-1]"); - - if (xmlCache == null) - { - // a different cache - // inheriting from NavigableNavigator is required - - var contentNavigator = UmbracoContext.Current.ContentCache.CreateNavigator() as NavigableNavigator; - if (contentNavigator == null) - throw new Exception("Published caches XPathNavigator do not inherit from NavigableNavigator."); - - var parameters = new List(); - macroNavigable = new MacroNavigator(parameters); - contentNavigable = UmbracoContext.Current.ContentCache; - } - else - { - // the original XML cache - // render the macro on top of the Xml document - - var umbracoXml = xmlCache.GetXml(UmbracoContext.Current.InPreviewMode); - - var macroXml = new XmlDocument(); - macroXml.LoadXml(""); - - macroNavigable = macroXml; - contentNavigable = umbracoXml; - } - - // for a test, do not try...catch - // but let the exceptions be thrown - - XslCompiledTransform transform; - using (var reader = new XmlTextReader(new StringReader(xsltText))) - { - transform = GetXsltTransform(reader, true); - } - var transformed = XsltTransform(plogger, macroNavigable, contentNavigable, transform, xslParameters); - - return transformed; - } - - public static string ExecuteItemRenderer(ProfilingLogger plogger, XslCompiledTransform transform, string itemData) - { - IXPathNavigable macroNavigable; - IXPathNavigable contentNavigable; - - var xmlCache = UmbracoContext.Current.ContentCache as PublishedCache.XmlPublishedCache.PublishedContentCache; - - if (xmlCache == null) - { - // a different cache - // inheriting from NavigableNavigator is required - - var contentNavigator = UmbracoContext.Current.ContentCache.CreateNavigator() as NavigableNavigator; - var mediaNavigator = UmbracoContext.Current.MediaCache.CreateNavigator() as NavigableNavigator; - - if (contentNavigator == null || mediaNavigator == null) - throw new Exception("Published caches XPathNavigator do not inherit from NavigableNavigator."); - - var parameters = new List(); - - macroNavigable = new MacroNavigator(parameters); - contentNavigable = UmbracoContext.Current.ContentCache; - } - else - { - // the original XML cache - // render the macro on top of the Xml document - - var umbracoXml = xmlCache.GetXml(UmbracoContext.Current.InPreviewMode); - - var macroXml = new XmlDocument(); - macroXml.LoadXml(""); - - macroNavigable = macroXml; - contentNavigable = umbracoXml; - } - - var xslParameters = new Dictionary { { "itemData", itemData } }; - return XsltTransform(plogger, macroNavigable, contentNavigable, transform, xslParameters); - } - - #endregion - - #region XsltTransform - - // running on the XML cache, document mode - // add parameters to the root node - // note: contains legacy dirty code - private static void AddMacroXmlNode(XmlDocument umbracoXml, XmlDocument macroXml, - string macroPropertyAlias, string macroPropertyType, string macroPropertyValue) - { - var macroXmlNode = macroXml.CreateNode(XmlNodeType.Element, macroPropertyAlias, string.Empty); - - // if no value is passed, then use the current "pageID" as value - var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue; - - Current.Logger.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); - - switch (macroPropertyType) - { - case "contentTree": - var nodeId = macroXml.CreateAttribute("nodeID"); - nodeId.Value = contentId; - macroXmlNode.Attributes.SetNamedItem(nodeId); - - // Get subs - try - { - macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.GetElementById(contentId), true)); - } - catch - { } - break; - - case "contentCurrent": - var importNode = macroPropertyValue == string.Empty - ? umbracoXml.GetElementById(contentId) - : umbracoXml.GetElementById(macroPropertyValue); - - var currentNode = macroXml.ImportNode(importNode, true); - - // remove all sub content nodes - foreach (XmlNode n in currentNode.SelectNodes("*[@isDoc]")) - currentNode.RemoveChild(n); - - macroXmlNode.AppendChild(currentNode); - - break; - - case "contentSubs": // disable that one, it does not work anyway... - //x.LoadXml(""); - //x.FirstChild.AppendChild(x.ImportNode(umbracoXml.GetElementById(contentId), true)); - //macroXmlNode.InnerXml = TransformMacroXml(x, "macroGetSubs.xsl"); - break; - - case "contentAll": - macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.DocumentElement, true)); - break; - - case "contentRandom": - XmlNode source = umbracoXml.GetElementById(contentId); - if (source != null) - { - var sourceList = source.SelectNodes("*[@isDoc]"); - if (sourceList.Count > 0) - { - int rndNumber; - var r = library.GetRandom(); - lock (r) - { - rndNumber = r.Next(sourceList.Count); - } - var node = macroXml.ImportNode(sourceList[rndNumber], true); - // remove all sub content nodes - foreach (XmlNode n in node.SelectNodes("*[@isDoc]")) - node.RemoveChild(n); - - macroXmlNode.AppendChild(node); - } - else - Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); - } - else - Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); - break; - - case "mediaCurrent": - if (string.IsNullOrEmpty(macroPropertyValue) == false) - { - //var c = new global::umbraco.cms.businesslogic.Content(int.Parse(macroPropertyValue)); - //macroXmlNode.AppendChild(macroXml.ImportNode(c.ToXml(global::umbraco.content.Instance.XmlContent, false), true)); - var nav = UmbracoContext.Current.MediaCache.CreateNodeNavigator(int.Parse(macroPropertyValue), false); - if (nav != null) - macroXmlNode.AppendChild(macroXml.ReadNode(nav.ReadSubtree())); - } - break; - - default: - macroXmlNode.InnerText = HttpUtility.HtmlDecode(macroPropertyValue); - break; - } - macroXml.FirstChild.AppendChild(macroXmlNode); - } - - // running on a navigable cache, navigable mode - // add parameters to the macro parameters collection - private static void AddMacroParameter(ICollection parameters, - NavigableNavigator contentNavigator, NavigableNavigator mediaNavigator, - string macroPropertyAlias, string macroPropertyType, string macroPropertyValue) - { - // if no value is passed, then use the current "pageID" as value - var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue; - - Current.Logger.Info($"Xslt node adding search start ({macroPropertyAlias},{macroPropertyValue})"); - - // beware! do not use the raw content- or media- navigators, but clones !! - - switch (macroPropertyType) - { - case "contentTree": - parameters.Add(new MacroNavigator.MacroParameter( - macroPropertyAlias, - contentNavigator.CloneWithNewRoot(contentId), // null if not found - will be reported as empty - attributes: new Dictionary { { "nodeID", contentId } })); - - break; - - case "contentPicker": - parameters.Add(new MacroNavigator.MacroParameter( - macroPropertyAlias, - contentNavigator.CloneWithNewRoot(contentId), // null if not found - will be reported as empty - 0)); - break; - - case "contentSubs": - parameters.Add(new MacroNavigator.MacroParameter( - macroPropertyAlias, - contentNavigator.CloneWithNewRoot(contentId), // null if not found - will be reported as empty - 1)); - break; - - case "contentAll": - parameters.Add(new MacroNavigator.MacroParameter(macroPropertyAlias, contentNavigator.Clone())); - break; - - case "contentRandom": - var nav = contentNavigator.Clone(); - if (nav.MoveToId(contentId)) - { - var descendantIterator = nav.Select("./* [@isDoc]"); - if (descendantIterator.MoveNext()) - { - // not empty - and won't change - var descendantCount = descendantIterator.Count; - - int index; - var r = library.GetRandom(); - lock (r) - { - index = r.Next(descendantCount); - } - - while (index > 0 && descendantIterator.MoveNext()) - index--; - - var node = descendantIterator.Current.UnderlyingObject as INavigableContent; - if (node != null) - { - nav = contentNavigator.CloneWithNewRoot(node.Id); - parameters.Add(new MacroNavigator.MacroParameter(macroPropertyAlias, nav, 0)); - } - else - throw new InvalidOperationException("Iterator contains non-INavigableContent elements."); - } - else - Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't have children!"); - } - else - Current.Logger.Warn("Error adding random node - parent (" + macroPropertyValue + ") doesn't exists!"); - break; - - case "mediaCurrent": - parameters.Add(new MacroNavigator.MacroParameter( - macroPropertyAlias, - mediaNavigator.CloneWithNewRoot(contentId), // null if not found - will be reported as empty - 0)); - break; - - default: - parameters.Add(new MacroNavigator.MacroParameter(macroPropertyAlias, HttpUtility.HtmlDecode(macroPropertyValue))); - break; - } - } - - // gets the result of the xslt transform - private static string XsltTransform(ProfilingLogger plogger, IXPathNavigable macroNavigable, IXPathNavigable contentNavigable, - XslCompiledTransform xslt, IDictionary xslParameters = null) - { - TextWriter tw = new StringWriter(); - - XsltArgumentList xslArgs; - using (plogger.DebugDuration("Adding Xslt extensions", "Added Xslt extensions")) - { - xslArgs = GetXsltArgumentListWithExtensions(); - var lib = new library(); - xslArgs.AddExtensionObject("urn:umbraco.library", lib); - } - - // add parameters - if (xslParameters == null || xslParameters.ContainsKey("currentPage") == false) - { - // note: "PageId" is a legacy stuff that might be != from what's in current PublishedContentRequest - var currentPageId = UmbracoContext.Current.PageId; - var current = contentNavigable.CreateNavigator().Select("//* [@id=" + currentPageId + "]"); - xslArgs.AddParam("currentPage", string.Empty, current); - } - if (xslParameters != null) - foreach (var parameter in xslParameters) - xslArgs.AddParam(parameter.Key, string.Empty, parameter.Value); - - // transform - using (plogger.DebugDuration("Executing Xslt transform", "Executed Xslt transform")) - { - xslt.Transform(macroNavigable, xslArgs, tw); - } - - return tw.ToString(); - } - - #endregion - - #region Manage transforms - - private static XslCompiledTransform GetCachedXsltTransform(string filename) - { - //TODO: SD: Do we really need to cache this?? - var filepath = IOHelper.MapPath(SystemDirectories.Xslt.EnsureEndsWith('/') + filename); - return Current.ApplicationCache.GetCacheItem( - CacheKeys.MacroXsltCacheKey + filename, - CacheItemPriority.Default, - new CacheDependency(filepath), - () => - { - using (var xslReader = new XmlTextReader(filepath)) - { - return GetXsltTransform(xslReader, GlobalSettings.DebugMode); - } - }); - } - - public static XslCompiledTransform GetXsltTransform(XmlTextReader xslReader, bool debugMode) - { - var transform = new XslCompiledTransform(debugMode); - var xslResolver = new XmlUrlResolver - { - Credentials = CredentialCache.DefaultCredentials - }; - - xslReader.EntityHandling = EntityHandling.ExpandEntities; - xslReader.DtdProcessing = DtdProcessing.Parse; - - try - { - transform.Load(xslReader, XsltSettings.TrustedXslt, xslResolver); - } - finally - { - xslReader.Close(); - } - - return transform; - } - - #endregion - - #region Manage extensions - - /* - private static readonly string XsltExtensionsConfig = - IOHelper.MapPath(SystemDirectories.Config + "/xsltExtensions.config"); - - private static readonly Func XsltExtensionsDependency = - () => new CacheDependency(XsltExtensionsConfig); - */ - - // creates and return an Xslt argument list with all Xslt extensions. - public static XsltArgumentList GetXsltArgumentListWithExtensions() - { - var xslArgs = new XsltArgumentList(); - - foreach (var extension in GetXsltExtensions()) - { - var extensionNamespace = "urn:" + extension.Key; - xslArgs.AddExtensionObject(extensionNamespace, extension.Value); - Current.Logger.Info($"Extension added: {extensionNamespace}, {extension.Value.GetType().Name}"); - } - - return xslArgs; - } - - /* - // gets the collection of all XSLT extensions for macros - // ie predefined, configured in the config file, and marked with the attribute - public static Dictionary GetCachedXsltExtensions() - { - // We could cache the extensions in a static variable but then the cache - // would not be refreshed when the .config file is modified. An application - // restart would be required. Better use the cache and add a dependency. - - // SD: The only reason the above statement might be true is because the xslt extension .config file is not a - // real config file!! if it was, we wouldn't have this issue. Having these in a static variable would be preferred! - // If you modify a config file, the app restarts and thus all static variables are reset. - // Having this stuff in cache just adds to the gigantic amount of cache data and will cause more cache turnover to happen. - - return ApplicationContext.Current.ApplicationCache.GetCacheItem( - "UmbracoXsltExtensions", - CacheItemPriority.NotRemovable, // NH 4.7.1, Changing to NotRemovable - null, // no refresh action - XsltExtensionsDependency(), // depends on the .config file - TimeSpan.FromDays(1), // expires in 1 day (?) - GetXsltExtensions); - } - */ - - // actually gets the collection of all XSLT extensions for macros - // ie predefined, configured in the config file, and marked with the attribute - public static Dictionary GetXsltExtensions() - { - return Current.XsltExtensions - .ToDictionary(x => x.Namespace, x => x.ExtensionObject); - - /* - // initialize the collection - // there is no "predefined" extensions anymore - var extensions = new Dictionary(); - - // Load the XSLT extensions configuration - var xsltExt = new XmlDocument(); - xsltExt.Load(XsltExtensionsConfig); - - // get the configured types - var extensionsNode = xsltExt.SelectSingleNode("/XsltExtensions"); - if (extensionsNode != null) - foreach (var attributes in extensionsNode.Cast() - .Where(x => x.NodeType == XmlNodeType.Element) - .Select(x => x.Attributes)) - { - Debug.Assert(attributes["assembly"] != null, "Extension attribute 'assembly' not specified."); - Debug.Assert(attributes["type"] != null, "Extension attribute 'type' not specified."); - Debug.Assert(attributes["alias"] != null, "Extension attribute 'alias' not specified."); - - // load the extension assembly - var extensionFile = IOHelper.MapPath(string.Format("{0}/{1}.dll", - SystemDirectories.Bin, attributes["assembly"].Value)); - - Assembly extensionAssembly; - try - { - extensionAssembly = Assembly.LoadFrom(extensionFile); - } - catch (Exception ex) - { - throw new Exception( - String.Format("Could not load assembly {0} for XSLT extension {1}. Please check config/xsltExtensions.config.", - extensionFile, attributes["alias"].Value), ex); - } - - // load the extension type - var extensionType = extensionAssembly.GetType(attributes["type"].Value); - if (extensionType == null) - throw new Exception( - String.Format("Could not load type {0} ({1}) for XSLT extension {2}. Please check config/xsltExtensions.config.", - attributes["type"].Value, extensionFile, attributes["alias"].Value)); - - // create an instance and add it to the extensions list - extensions.Add(attributes["alias"].Value, Activator.CreateInstance(extensionType)); - } - - // get types marked with XsltExtension attribute - var foundExtensions = TypeLoader.Current.ResolveXsltExtensions(); - foreach (var xsltType in foundExtensions) - { - var attributes = xsltType.GetCustomAttributes(true); - var xsltTypeName = xsltType.FullName; - foreach (var ns in attributes - .Select(attribute => string.IsNullOrEmpty(attribute.Namespace) ? attribute.Namespace : xsltTypeName)) - { - extensions.Add(ns, Activator.CreateInstance(xsltType)); - } - } - - return extensions; - */ - } - - #endregion - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollection.cs b/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollection.cs deleted file mode 100644 index 1668677649..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollection.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core.Composing; -using Umbraco.Core.Media; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - // fixme - kill entirely in v8 thumbs should be generated by ImageProcessor - public class ThumbnailProviderCollection : BuilderCollectionBase - { - public ThumbnailProviderCollection(IEnumerable items) - : base(items) - { } - - public string GetThumbnailUrl(string fileUrl) - { - var provider = this.FirstOrDefault(x => x.CanProvideThumbnail(fileUrl)); - return provider != null ? provider.GetThumbnailUrl(fileUrl) : string.Empty; - } - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollectionBuilder.cs b/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollectionBuilder.cs deleted file mode 100644 index e5925ac4e7..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/ThumbnailProviderCollectionBuilder.cs +++ /dev/null @@ -1,15 +0,0 @@ -using LightInject; -using Umbraco.Core.Composing; -using Umbraco.Core.Media; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - public class ThumbnailProviderCollectionBuilder : WeightedCollectionBuilderBase - { - public ThumbnailProviderCollectionBuilder(IServiceContainer container) - : base(container) - { } - - protected override ThumbnailProviderCollectionBuilder This => this; - } -} diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index 54afd0ad75..e408a46db5 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -121,9 +121,6 @@ namespace Umbraco.Web.Runtime composition.Container.EnableWebApi(GlobalConfiguration.Configuration); composition.Container.RegisterApiControllers(typeLoader, GetType().Assembly); - XsltExtensionCollectionBuilder.Register(composition.Container) - .AddExtensionObjectProducer(() => typeLoader.GetXsltExtensions()); - composition.Container.RegisterCollectionBuilder() .Add(() => typeLoader.GetTypes()); // fixme which searchable trees?! @@ -179,13 +176,7 @@ namespace Umbraco.Web.Runtime .Append(); composition.Container.RegisterSingleton(); - - composition.Container.RegisterCollectionBuilder() - .Add(typeLoader.GetThumbnailProviders()); - - composition.Container.RegisterCollectionBuilder() - .Append(typeLoader.GetImageUrlProviders()); - + composition.Container.RegisterSingleton(); // register *all* checks, except those marked [HideFromTypeFinder] of course diff --git a/src/Umbraco.Web/TypeLoaderExtensions.cs b/src/Umbraco.Web/TypeLoaderExtensions.cs index 2c7bc430ce..a1209abccf 100644 --- a/src/Umbraco.Web/TypeLoaderExtensions.cs +++ b/src/Umbraco.Web/TypeLoaderExtensions.cs @@ -63,36 +63,6 @@ namespace Umbraco.Web { return mgr.GetTypes(); } - - /// - /// Returns all classes attributed with XsltExtensionAttribute attribute - /// - /// - /// - internal static IEnumerable GetXsltExtensions(this TypeLoader mgr) - { - return mgr.GetAttributedTypes(); - } - - /// - /// Returns all IThumbnailProvider classes - /// - /// - /// - internal static IEnumerable GetThumbnailProviders(this TypeLoader mgr) - { - return mgr.GetTypes(); - } - - /// - /// Returns all IImageUrlProvider classes - /// - /// - /// - internal static IEnumerable GetImageUrlProviders(this TypeLoader mgr) - { - return mgr.GetTypes(); - } - + } } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 9b771f09c9..5b4da825a8 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -204,7 +204,6 @@ - @@ -217,8 +216,6 @@ - - @@ -443,6 +440,7 @@ ASPXCodeBehind + @@ -808,9 +806,6 @@ ASPXCodeBehind - - ASPXCodeBehind - @@ -1181,9 +1176,6 @@ ASPXCodeBehind - - ASPXCodeBehind - ASPXCodeBehind @@ -1200,7 +1192,6 @@ ASPXCodeBehind - @@ -1293,7 +1284,6 @@ - FeedProxy.aspx ASPXCodeBehind @@ -1327,13 +1317,6 @@ Preview.aspx - - xsltVisualize.aspx - ASPXCodeBehind - - - xsltVisualize.aspx - insertMasterpageContent.aspx ASPXCodeBehind @@ -1374,13 +1357,6 @@ Code - - assemblyBrowser.aspx - ASPXCodeBehind - - - assemblyBrowser.aspx - editPackage.aspx ASPXCodeBehind @@ -1388,24 +1364,6 @@ editPackage.aspx - - getXsltStatus.asmx - Component - - - xsltChooseExtension.aspx - ASPXCodeBehind - - - xsltChooseExtension.aspx - - - xsltInsertValueOf.aspx - ASPXCodeBehind - - - xsltInsertValueOf.aspx - exportDocumenttype.aspx ASPXCodeBehind @@ -1466,11 +1424,6 @@ - - True - True - Resources.resx - default.aspx ASPXCodeBehind @@ -1506,9 +1459,6 @@ - - XmlTree.xsd - @@ -1519,10 +1469,6 @@ CheckForUpgrade.asmx Component - - codeEditorSave.asmx - Component - legacyAjaxCalls.asmx Component @@ -1571,11 +1517,6 @@ ResXFileCodeGenerator Strings.Designer.cs - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - @@ -1593,10 +1534,6 @@
    - - - - ASPXCodeBehind @@ -1604,7 +1541,6 @@ Form - @@ -1624,7 +1560,6 @@ ASPXCodeBehind - ASPXCodeBehind @@ -1655,11 +1590,6 @@ - - - - XmlTree.xsd - @@ -1685,7 +1615,6 @@ SettingsSingleFileGenerator Settings1.Designer.cs - diff --git a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs index d887a706d5..ced330c638 100644 --- a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs +++ b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs @@ -132,9 +132,6 @@ namespace umbraco.cms.businesslogic.packager if (appendFile) { - if (!string.IsNullOrEmpty(mcr.XsltPath)) - AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.Xslt) + "/" + mcr.XsltPath, packageDirectory, doc); - //TODO: Clearly the packager hasn't worked very well for packaging Partial Views to date since there is no logic in here for that //if (!string.IsNullOrEmpty(mcr.ScriptingFile)) diff --git a/src/Umbraco.Web/umbraco.presentation/XsltExtensionAttribute.cs b/src/Umbraco.Web/umbraco.presentation/XsltExtensionAttribute.cs deleted file mode 100644 index b3e0e7dce8..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/XsltExtensionAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Security.Permissions; -using System.Web; - -namespace umbraco -{ - /// - /// Allows App_Code XSLT extensions to be declared using the [XsltExtension] class attribute. - /// - /// - /// An optional XML namespace can be specified using [XsltExtension("MyNamespace")]. - /// - [AttributeUsage(AttributeTargets.Class)] - [Obsolete("Use Umbraco.Core.Macros.XsltExtensionAttribute instead")] - public class XsltExtensionAttribute : Umbraco.Core.Macros.XsltExtensionAttribute - { - public XsltExtensionAttribute() : base() - { - - } - - public XsltExtensionAttribute(string ns) : base(ns) - { - - } - - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/Trees.cd b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/Trees.cd deleted file mode 100644 index 28c6272d99..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/Trees.cd +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - umbraco\Trees\BaseTree.cs - AABUAABAAAQSAQAIAAAAQAAABRBgBEUBWDIAAMKAAyI= - - - - - - - umbraco\Trees\BaseContentTree.cs - ACAAAAAIBICAgAIIEAEAAAAAAAAAAAAAgBQAAAAAAAI= - - - - - - umbraco\Trees\loadContent.cs - AAAAAAAAAQAABAAIAAQAAAAAAABAAAABABAAAEAAAAA= - - - - - - umbraco\Trees\loadMedia.cs - AAAAAAAAAAAAAAAIAAAAAAAAAABAAAABABAAAEAAAAI= - - - - - - umbraco\Trees\FileSystemTree.cs - AAABAAAAAAAAABAAAAAAAAAAAAAAEAABABBAAAAAAAI= - - - - - - umbraco\Trees\loadXslt.cs - AAAAAAAAAAAAABAAAAAAAAAAAAAAEAABAABAAAAAAAI= - - - - - - umbraco\Trees\loadPython.cs - AAAAAAAAAAAAABAAAAAAAAAAAAAAEAABAABAAAAAAAI= - - - - - - umbraco\Trees\ContentRecycleBin.cs - AAAAAAAAAAAAAAAIEAAAAAAAAABAAAABAAIAAEAAAAA= - - - - - - umbraco\Trees\LegacyTree.cs - AAAAAAAAACAAAAAAAAAAAAABACAAAAABABAAAAAAAAI= - - - - - - umbraco\Trees\NullTree.cs - AAAAAAAAAAAAAAAAAAAAAAAAAQAAAAABABAAAAAAAAI= - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsd b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsd deleted file mode 100644 index e577da3663..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsd +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsx b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsx deleted file mode 100644 index ff71343be3..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/XmlTree.xsx +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs deleted file mode 100644 index 8b9f5cb8e5..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/XsltTasks.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.IO; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Web.UI; -using Umbraco.Core.FileResources; -using Umbraco.Core.Models; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web._Legacy.UI; -using File = System.IO.File; - -namespace umbraco -{ - /// - /// Summary description for standardTasks. - /// - /// - - public class XsltTasks : LegacyDialogTask - { - - public override bool PerformSave() - { - IOHelper.EnsurePathExists(SystemDirectories.Xslt); - IOHelper.EnsureFileExists(Path.Combine(IOHelper.MapPath(SystemDirectories.Xslt), "web.config"), Files.BlockingWebConfig); - - var template = Alias.Substring(0, Alias.IndexOf("|||")); - var fileName = Alias.Substring(Alias.IndexOf("|||") + 3, Alias.Length - Alias.IndexOf("|||") - 3).Replace(" ", ""); - if (fileName.ToLowerInvariant().EndsWith(".xslt") == false) - fileName += ".xslt"; - var xsltTemplateSource = IOHelper.MapPath(SystemDirectories.Umbraco + "/xslt/templates/" + template); - var xsltNewFilename = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); - - if (File.Exists(xsltNewFilename) == false) - { - if (fileName.Contains("/")) //if there's a / create the folder structure for it - { - var folders = fileName.Split("/".ToCharArray()); - var xsltBasePath = IOHelper.MapPath(SystemDirectories.Xslt); - for (var i = 0; i < folders.Length - 1; i++) - { - xsltBasePath = System.IO.Path.Combine(xsltBasePath, folders[i]); - System.IO.Directory.CreateDirectory(xsltBasePath); - } - } - - // update with xslt references - var xslt = ""; - using (var xsltFile = System.IO.File.OpenText(xsltTemplateSource)) - { - xslt = xsltFile.ReadToEnd(); - xsltFile.Close(); - } - - // prepare support for XSLT extensions - xslt = Umbraco.Web.Macros.XsltMacroEngine.AddXsltExtensionsToHeader(xslt); - var xsltWriter = System.IO.File.CreateText(xsltNewFilename); - xsltWriter.Write(xslt); - xsltWriter.Flush(); - xsltWriter.Close(); - - // Create macro? - if (ParentID == 1) - { - var name = Alias.Substring(Alias.IndexOf("|||") + 3, Alias.Length - Alias.IndexOf("|||") - 3); - if (name.ToLowerInvariant().EndsWith(".xslt")) - name = name.Substring(0, name.Length - 5); - - name = name.SplitPascalCasing().ToFirstUpperInvariant(); - //cms.businesslogic.macro.Macro m = - // cms.businesslogic.macro.Macro.MakeNew(name); - var m = new Macro - { - Name = name, - Alias = name.Replace(" ", String.Empty) - }; - m.XsltPath = fileName; - //m.Save(); - Current.Services.MacroService.Save(m); - } - } - - _returnUrl = string.Format(SystemDirectories.Umbraco + "/developer/xslt/editXslt.aspx?file={0}", fileName); - - return true; - } - - public override bool PerformDelete() - { - var path = IOHelper.MapPath(SystemDirectories.Xslt + "/" + Alias.TrimStart('/')); - - try - { - if(System.IO.Directory.Exists(path)) - System.IO.Directory.Delete(path); - else if(System.IO.File.Exists(path)) - System.IO.File.Delete(path); - } - catch (Exception ex) - { - Current.Logger.Error(string.Format("Could not remove XSLT file {0} - User {1}", Alias, UmbracoContext.Current.Security.GetUserId()), ex); - } - return true; - } - - private string _returnUrl = ""; - - public override string ReturnUrl - { - get { return _returnUrl; } - } - - public override string AssignedApp - { - get { return Constants.Applications.Developer.ToString(); } - } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/xslt.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/xslt.ascx.cs deleted file mode 100644 index 90ffd2101e..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/xslt.ascx.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Umbraco.Core.Services; -using System.Web; -using System.Web.UI.WebControls; -using System.IO; -using Umbraco.Core; -using Umbraco.Web.UI; -using Umbraco.Core.IO; -using Umbraco.Web; -using Umbraco.Web.UI.Controls; -using Umbraco.Web._Legacy.UI; - -namespace umbraco.presentation.create -{ - - - /// - /// Summary description for xslt. - /// - public partial class xslt : UmbracoUserControl - { - protected System.Web.UI.WebControls.ListBox nodeType; - - protected void Page_Load(object sender, System.EventArgs e) - { - sbmt.Text = Services.TextService.Localize("create"); - foreach (string fileName in Directory.GetFiles(IOHelper.MapPath(SystemDirectories.Umbraco + GetXsltTemplatePath()), "*.xslt")) - { - FileInfo fi = new FileInfo(fileName); - if (fi.Name != "Clean.xslt") - { - var liText = fi.Name.Replace(".xslt", "").SplitPascalCasing().ToFirstUpperInvariant(); - xsltTemplate.Items.Add(new ListItem(liText, fi.Name)); - } - } - - } - - private static string GetXsltTemplatePath() - { - return "/xslt/templates/schema2"; - } - - protected void sbmt_Click(object sender, System.EventArgs e) - { - if (Page.IsValid) - { - var createMacroVal = 0; - if (createMacro.Checked) - createMacroVal = 1; - - var xsltName = Path.Combine("schema2", xsltTemplate.SelectedValue); - - - var returnUrl = LegacyDialogHandler.Create( - new HttpContextWrapper(Context), - Security.CurrentUser, - Request.GetItemAsString("nodeType"), - createMacroVal, - xsltName + "|||" + rename.Text); - - ClientTools - .ChangeContentFrameUrl(returnUrl) - .ChildNodeCreated() - .CloseModalWindow(); - - - - - } - - } - - /// - /// rename control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox rename; - - /// - /// RequiredFieldValidator1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; - - /// - /// xsltTemplate control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.ListBox xsltTemplate; - - /// - /// createMacro control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox createMacro; - - /// - /// Textbox1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox Textbox1; - - /// - /// sbmt control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button sbmt; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx deleted file mode 100644 index 18b582707d..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx +++ /dev/null @@ -1,29 +0,0 @@ -<%@ Page Language="c#" MasterPageFile="../../masterpages/umbracoDialog.Master" Title="Assembly Browser" Codebehind="assemblyBrowser.aspx.cs" AutoEventWireup="True" - Inherits="umbraco.developer.assemblyBrowser" %> - - -

    - - -

    The following list shows the Public Properties from the - Control. By checking the Properties and click the "Save Properties" button at - - the bottom, umbraco will create the corresponding Macro Elements.

    - -

    - -

    -
    - - -

    The following Macro Parameters was added:

    -
    -

    - Important: You might need to reload the macro to see the changes.

    - -

    - - -
    - -
    diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.cs deleted file mode 100644 index 96b815019f..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.cs +++ /dev/null @@ -1,204 +0,0 @@ -using System; -using System.Linq; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Reflection; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web.UI.Pages; -using UserControl = System.Web.UI.UserControl; - -namespace umbraco.developer -{ - /// - /// Summary description for assemblyBrowser. - /// - public partial class assemblyBrowser : UmbracoEnsuredPage - { - public assemblyBrowser() - { - CurrentApp = Constants.Applications.Developer.ToString(); - } - protected void Page_Load(object sender, EventArgs e) - { - - var isUserControl = false; - var errorReadingControl = false; - - try - { - - Type type = null; - if (Request.QueryString["type"] == null) - { - isUserControl = true; - var fileName = Request.GetItemAsString("fileName"); - if (!fileName.StartsWith("~")) - { - if (fileName.StartsWith("/")) - { - fileName = "~" + fileName; - } - else - { - fileName = "~/" + fileName; - } - } - IOHelper.ValidateEditPath(fileName, SystemDirectories.UserControls); - - if (System.IO.File.Exists(IOHelper.MapPath(fileName))) - { - var oControl = (UserControl)LoadControl(fileName); - - type = oControl.GetType(); - } - else - { - errorReadingControl = true; - ChooseProperties.Visible = false; - AssemblyName.Text = "User control doesn't exist

    Please verify that you've copied the file to:
    " + IOHelper.MapPath("~/" + fileName); - } - } - else - { - var currentAss = IOHelper.MapPath(SystemDirectories.Bin + "/" + Request.QueryString["fileName"] + ".dll"); - var asm = Assembly.LoadFrom(currentAss); - type = asm.GetType(Request.QueryString["type"]); - } - - if (!errorReadingControl) - { - string fullControlAssemblyName; - if (isUserControl) - { - AssemblyName.Text = "Choose Properties from " + type.BaseType.Name; - fullControlAssemblyName = type.BaseType.Namespace + "." + type.BaseType.Name; - } - else - { - AssemblyName.Text = "Choose Properties from " + type.Name; - fullControlAssemblyName = type.Namespace + "." + type.Name; - } - - - if (!IsPostBack && type != null) - { - MacroProperties.Items.Clear(); - foreach (var pi in type.GetProperties()) - { - if (pi.CanWrite && ((fullControlAssemblyName == pi.DeclaringType.Namespace + "." + pi.DeclaringType.Name) || pi.DeclaringType == type)) - { - MacroProperties.Items.Add(new ListItem(pi.Name + " (" + pi.PropertyType.Name + ")", pi.PropertyType.Name)); - } - - foreach (ListItem li in MacroProperties.Items) - li.Selected = true; - } - } - - } - } - catch (Exception err) - { - AssemblyName.Text = "Error reading " + Request.CleanForXss("fileName"); - Button1.Visible = false; - ChooseProperties.Controls.Add(new LiteralControl("

    " + err.ToString() + "

    ")); - } - - } - - protected void Button1_Click(object sender, EventArgs e) - { - var result = ""; - - // Get the macro object - var macroObject = Current.Services.MacroService.GetById(Convert.ToInt32(Request.QueryString["macroID"])); - - //// Load all macroPropertyTypes - //var macroPropertyTypes = new Hashtable(); - //var macroPropertyIds = new Hashtable(); - - //var macroPropTypes = ParameterEditorResolver.Current.ParameterEditors.ToArray(); - - //foreach (var mpt in macroPropTypes) - //{ - // macroPropertyIds.Add(mpt.Alias, mpt.Id.ToString()); - // macroPropertyTypes.Add(mpt.Alias, mpt.BaseType); - //} - var changed = false; - - foreach (ListItem li in MacroProperties.Items) - { - if (li.Selected && MacroHasProperty(macroObject, li.Text.Substring(0, li.Text.IndexOf(" ", StringComparison.Ordinal)).ToLower()) == false) - { - result += "

  • Added: " + SpaceCamelCasing(li.Text) + "
  • "; - var macroPropertyTypeAlias = GetMacroTypeFromClrType(li.Value); - - macroObject.Properties.Add(new Umbraco.Core.Models.MacroProperty - { - Name = SpaceCamelCasing(li.Text), - Alias = li.Text.Substring(0, li.Text.IndexOf(" ", StringComparison.Ordinal)), - EditorAlias = macroPropertyTypeAlias - }); - - changed = true; - } - else if (li.Selected) - { - result += "
  • Skipped: " + SpaceCamelCasing(li.Text) + " (already exists as a parameter)
  • "; - } - } - - if (changed) - { - Current.Services.MacroService.Save(macroObject); - } - - ChooseProperties.Visible = false; - ConfigProperties.Visible = true; - resultLiteral.Text = result; - } - - private static bool MacroHasProperty(IMacro macroObject, string propertyAlias) - { - return macroObject.Properties.Any(mp => mp.Alias.ToLower() == propertyAlias); - } - - private static string SpaceCamelCasing(string text) - { - var tempString = text.Substring(0, 1).ToUpper(); - for (var i = 1; i < text.Length; i++) - { - if (text.Substring(i, 1) == " ") - break; - if (text.Substring(i, 1).ToUpper() == text.Substring(i, 1)) - tempString += " "; - tempString += text.Substring(i, 1); - } - return tempString; - } - - private static string GetMacroTypeFromClrType(string baseTypeName) - { - switch (baseTypeName) - { - case "Int32": - return Constants.PropertyEditors.Aliases.Integer; - case "Decimal": - //we previously only had an integer editor too! - this would of course - // fail if someone enters a real long number - return Constants.PropertyEditors.Aliases.Integer; - case "Boolean": - return Constants.PropertyEditors.Aliases.Boolean; - case "String": - default: - return Constants.PropertyEditors.Aliases.TextBox; - } - } - - } - -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.designer.cs deleted file mode 100644 index 9b8f124443..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/assemblyBrowser.aspx.designer.cs +++ /dev/null @@ -1,69 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.developer { - - - public partial class assemblyBrowser { - - /// - /// AssemblyName control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label AssemblyName; - - /// - /// ChooseProperties control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Panel ChooseProperties; - - /// - /// MacroProperties control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBoxList MacroProperties; - - /// - /// Button1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button Button1; - - /// - /// ConfigProperties control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Panel ConfigProperties; - - /// - /// resultLiteral control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal resultLiteral; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs index 163e1da2b8..1f2fcf515c 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs @@ -47,22 +47,9 @@ namespace umbraco.cms.presentation.developer ClientTools .SyncTree("-1," + _macro.Id, false); - string tempMacroAssembly = _macro.ControlAssembly ?? ""; string tempMacroType = _macro.ControlType ?? ""; - PopulateFieldsOnLoad(_macro, tempMacroAssembly, tempMacroType); - - // Check for assemblyBrowser - if (tempMacroType.IndexOf(".ascx", StringComparison.Ordinal) > 0) - assemblyBrowserUserControl.Controls.Add( - new LiteralControl("
    ")); - else if (tempMacroType != string.Empty && tempMacroAssembly != string.Empty) - assemblyBrowser.Controls.Add( - new LiteralControl("
    ")); + PopulateFieldsOnLoad(_macro, tempMacroType); // Load elements from macro macroPropertyBind(); @@ -83,12 +70,11 @@ namespace umbraco.cms.presentation.developer /// /// /// - protected virtual void PopulateFieldsOnLoad(IMacro macro, string macroAssemblyValue, string macroTypeValue) + protected virtual void PopulateFieldsOnLoad(IMacro macro, string macroTypeValue) { macroName.Text = macro.Name; macroAlias.Text = macro.Alias; macroKey.Text = macro.Key.ToString(); - macroXslt.Text = macro.XsltPath; cachePeriod.Text = macro.CacheDuration.ToInvariantString(); macroRenderContent.Checked = macro.DontRender == false; macroEditor.Checked = macro.UseInEditor; @@ -96,9 +82,8 @@ namespace umbraco.cms.presentation.developer cachePersonalized.Checked = macro.CacheByMember; // Populate either user control or custom control - if (macroTypeValue != string.Empty && macroAssemblyValue != string.Empty) + if (macroTypeValue != string.Empty) { - macroAssembly.Text = macroAssemblyValue; macroType.Text = macroTypeValue; } else @@ -119,9 +104,7 @@ namespace umbraco.cms.presentation.developer macro.CacheDuration = macroCachePeriod; macro.Alias = macroAlias.Text; macro.Name = macroName.Text; - macro.ControlAssembly = macroAssemblyValue; macro.ControlType = macroTypeValue; - macro.XsltPath = macroXslt.Text; } private static void GetXsltFilesFromDir(string orgPath, string path, ArrayList files) @@ -229,7 +212,7 @@ namespace umbraco.cms.presentation.developer return Convert.ToBoolean(isChecked); } - public void AddChooseList(Object sender, EventArgs e) + public void AddChooseList(object sender, EventArgs e) { if (IsPostBack == false) { @@ -341,18 +324,6 @@ namespace umbraco.cms.presentation.developer ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Save, "Macro saved", ""); - // Check for assemblyBrowser - if (tempMacroType.IndexOf(".ascx", StringComparison.Ordinal) > 0) - assemblyBrowserUserControl.Controls.Add( - new LiteralControl("
    ")); - else if (tempMacroType != string.Empty && tempMacroAssembly != string.Empty) - assemblyBrowser.Controls.Add( - new LiteralControl("
    ")); - macroPropertyBind(); } @@ -418,16 +389,7 @@ namespace umbraco.cms.presentation.developer /// To modify move field declaration from designer file to code-behind file. /// protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_2; - - /// - /// macroXslt control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroXslt; - + /// /// xsltFiles control. /// @@ -454,16 +416,7 @@ namespace umbraco.cms.presentation.developer /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList userControlList; - - /// - /// assemblyBrowserUserControl control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.PlaceHolder assemblyBrowserUserControl; - + /// /// macroAssembly control. /// @@ -481,16 +434,7 @@ namespace umbraco.cms.presentation.developer /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.TextBox macroType; - - /// - /// assemblyBrowser control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.PlaceHolder assemblyBrowser; - + /// /// Pane1_3 control. /// diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/editXslt.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/editXslt.aspx.cs deleted file mode 100644 index 82bc42a2e6..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/editXslt.aspx.cs +++ /dev/null @@ -1,198 +0,0 @@ -using Umbraco.Core.Services; -using System; -using System.Collections.Generic; -using System.IO; -using System.Web.UI; -using System.Web.UI.WebControls; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Web._Legacy.Controls; -using umbraco.cms.presentation.Trees; -using Umbraco.Web.UI.Pages; - -namespace umbraco.cms.presentation.developer -{ - /// - /// Summary description for editXslt. - /// - [WebformsPageTreeAuthorize(Constants.Trees.Xslt)] - public partial class editXslt : UmbracoEnsuredPage - { - - protected PlaceHolder buttons; - - protected MenuButton SaveButton; - - protected void Page_Load(object sender, EventArgs e) - { - if (!IsPostBack) - { - string file = Request.QueryString["file"]; - string path = BaseTree.GetTreePathFromFilePath(file, false, true); - ClientTools - .SyncTree(path, false); - } - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - SaveButton = UmbracoPanel1.Menu.NewButton(); - SaveButton.ToolTip = "Save Xslt File"; - SaveButton.Text = Services.TextService.Localize("save"); - SaveButton.ButtonType = MenuButtonType.Primary; - SaveButton.ID = "save"; - SaveButton.CssClass = "client-side"; - - var code = UmbracoPanel1.NewTabPage("xslt"); - code.Controls.Add(pane1); - - var props = UmbracoPanel1.NewTabPage("properties"); - props.Controls.Add(pane2); - - var tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/images/editor/insField.GIF"; - tmp.OnClickCommand = ClientTools.Scripts.OpenModalWindow(IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/developer/xslt/xsltinsertvalueof.aspx?objectId=" + editorSource.ClientID, "Insert value", 750, 250); - //"umbracoInsertField(document.getElementById('editorSource'), 'xsltInsertValueOf', '','felt', 750, 230, '');"; - tmp.AltText = "Insert xslt:value-of"; - - editorSource.Menu.InsertSplitter(); - - tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = SystemDirectories.Umbraco + "/images/editor/insMemberItem.GIF"; - tmp.OnClickCommand = "UmbEditor.Insert('\\n', '" + editorSource.ClientID + "'); return false;"; - tmp.AltText = "Insert xsl:variable"; - - editorSource.Menu.InsertSplitter(); - - tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = SystemDirectories.Umbraco + "/images/editor/insChildTemplateNew.GIF"; - tmp.OnClickCommand = "UmbEditor.Insert('\\n', '\\n\\n', '" + editorSource.ClientID + "'); return false;"; - tmp.AltText = "Insert xsl:if"; - - tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = SystemDirectories.Umbraco + "/images/editor/insChildTemplateNew.GIF"; - tmp.OnClickCommand = "UmbEditor.Insert('\\n', '\\n\\n', '" + editorSource.ClientID + "'); return false;"; - tmp.AltText = "Insert xsl:for-each"; - - editorSource.Menu.InsertSplitter(); - - tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = SystemDirectories.Umbraco + "/images/editor/insFieldByLevel.GIF"; - tmp.OnClickCommand = "UmbEditor.Insert('\\n\\n', '\\n\\n\\n\\n\\n', '" + editorSource.ClientID + "'); return false;"; - tmp.AltText = "Insert xsl:choose"; - - editorSource.Menu.InsertSplitter(); - - tmp = editorSource.Menu.NewIcon(); - tmp.ImageURL = SystemDirectories.Umbraco + "/images/editor/xslVisualize.GIF"; - tmp.OnClickCommand = "xsltVisualize();"; - tmp.AltText = "Visualize XSLT"; - - - // Add source and filename - var file = IOHelper.MapPath(SystemDirectories.Xslt + "/" + Request.QueryString["file"]); - - // validate file - IOHelper.ValidateEditPath(file, SystemDirectories.Xslt); - // validate extension - IOHelper.ValidateFileExtension(file, new List() { "xslt", "xsl" }); - - - xsltFileName.Text = file.Replace(IOHelper.MapPath(SystemDirectories.Xslt), "").Substring(1).Replace(@"\", "/"); - - StreamReader SR; - string S; - SR = File.OpenText(file); - - S = SR.ReadToEnd(); - SR.Close(); - - editorSource.Text = S; - } - - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference(IOHelper.ResolveUrl(SystemDirectories.WebServices) + "/codeEditorSave.asmx")); - ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference(IOHelper.ResolveUrl(SystemDirectories.WebServices) + "/legacyAjaxCalls.asmx")); - } - - - /// - /// JsInclude1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::ClientDependency.Core.Controls.JsInclude JsInclude1; - - /// - /// UmbracoPanel1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.TabView UmbracoPanel1; - - /// - /// Pane1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane pane1; - protected global::Umbraco.Web._Legacy.Controls.Pane pane2; - - /// - /// pp_filename control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.PropertyPanel pp_filename; - - /// - /// xsltFileName control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox xsltFileName; - - /// - /// pp_errorMsg control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.PropertyPanel pp_errorMsg; - - /// - /// editorSource control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.CodeArea editorSource; - - /// - /// editorJs control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal editorJs; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx deleted file mode 100644 index 7d5385af8f..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx +++ /dev/null @@ -1 +0,0 @@ -<%@ WebService Language="c#" Codebehind="getXsltStatus.asmx.cs" Class="umbraco.developer.getXsltStatus" %> diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx.cs deleted file mode 100644 index 99a74b0d8c..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/getXsltStatus.asmx.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; -using System.Web; -using System.Web.Services; -using System.Xml; -using System.IO; -using Umbraco.Core.IO; -using umbraco.presentation.webservices; -using Umbraco.Web.WebServices; - -namespace umbraco.developer -{ - /// - /// Summary description for getXsltStatus. - /// - [WebService(Namespace="http://umbraco.org/webservices")] - public class getXsltStatus : UmbracoAuthorizedWebService - { - public getXsltStatus() - { - //CODEGEN: This call is required by the ASP.NET Web Services Designer - InitializeComponent(); - } - - // TODO: Security-check - [WebMethod] - public XmlDocument FilesFromDirectory(string dir) - { - AuthorizeRequest(true); - - XmlDocument xd = new XmlDocument(); - xd.LoadXml(""); - foreach (string file in System.IO.Directory.GetFiles(IOHelper.MapPath(SystemDirectories.Umbraco + "/xslt/" + dir), "*.xsl*")) - { - FileInfo fi = new FileInfo(file); - FileAttributes fa = fi.Attributes; - XmlElement fileXml = xd.CreateElement("file"); - fileXml.SetAttribute("name", fi.Name); - //fileXml.SetAttribute("created", fi.CreationTimeUtc); - fileXml.SetAttribute("modified", fi.LastWriteTimeUtc.ToString()); - fileXml.SetAttribute("size", fi.Length.ToString()); - xd.DocumentElement.AppendChild((XmlNode) fileXml); - } - return xd; - } - - #region Component Designer generated code - - //Required by the Web Services Designer - private IContainer components = null; - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - } - - /// - /// Clean up any resources being used. - /// - protected override void Dispose( bool disposing ) - { - if(disposing && components != null) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #endregion - - // WEB SERVICE EXAMPLE - // The HelloWorld() example service returns the string Hello World - // To build, uncomment the following lines then save and build the project - // To test this web service, press F5 - -// [WebMethod] -// public string HelloWorld() -// { -// return "Hello World"; -// } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx deleted file mode 100644 index b719951aed..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx +++ /dev/null @@ -1,44 +0,0 @@ -<%@ Page Language="c#" Codebehind="xsltChooseExtension.aspx.cs" MasterPageFile="../../masterpages/umbracoDialog.Master" AutoEventWireup="True" - Inherits="umbraco.developer.xsltChooseExtension" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" %> - - - - - - - - - - - - - - - - - - - -

    - <%= Services.TextService.Localize("or") %> <%= Services.TextService.Localize("cancel") %> -

    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.cs deleted file mode 100644 index e258a69a65..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using System.Web.UI; -using System.Web.UI.WebControls; -using Umbraco.Core; -using Umbraco.Web.UI.Pages; - -namespace umbraco.developer -{ - /// - /// Summary description for xsltChooseExtension. - /// - [WebformsPageTreeAuthorize(Constants.Trees.Xslt)] - public partial class xsltChooseExtension : UmbracoEnsuredPage - { - - protected void Page_Load(object sender, System.EventArgs e) - { - SortedList> ht = GetXsltAssembliesAndMethods(); - if (!IsPostBack) - { - assemblies.Attributes.Add("onChange", "document.forms[0].submit()"); - foreach(string s in ht.Keys) - assemblies.Items.Add(new ListItem(s)); - - // Select the umbraco extensions as default - assemblies.Items[0].Selected = true; - } - - string selectedMethod = ""; - if (methods.SelectedValue != "") - { - selectedMethod = methods.SelectedValue; - PlaceHolderParamters.Controls.Clear(); - PlaceHolderParamters.Controls.Add(new LiteralControl("
    " + assemblies.SelectedItem + ":" + methods.SelectedValue.Substring(0, methods.SelectedValue.IndexOf("(")) + "(")); - PlaceHolderParamters.Controls.Add(new LiteralControl("")); - - int counter = 0; - string[] props = methods.SelectedValue.Substring(methods.SelectedValue.IndexOf("(") + 1, methods.SelectedValue.IndexOf(")") - methods.SelectedValue.IndexOf("(") - 1).Split(','); - - foreach (string s in props) - { - if (s.Trim() != "") - { - counter++; - TextBox t = new TextBox(); - t.ID = "param" + Guid.NewGuid().ToString(); - t.Text = s.Trim(); - t.TabIndex = (short) counter; - t.Attributes.Add("onFocus", "if (this.value == '" + s.Trim() + "') this.value = '';"); - t.Attributes.Add("onBlur", "if (this.value == '') this.value = '" + s.Trim() + "'"); - t.Attributes.Add("style", "width:80px;"); - PlaceHolderParamters.Controls.Add(t); - - if(counter < props.Length) - PlaceHolderParamters.Controls.Add(new LiteralControl(",")); - } - } - - counter++; - - //PlaceHolderParamters.Controls.Add(new LiteralControl(")

    ")); - PlaceHolderParamters.Controls.Add(new LiteralControl(")")); - bt_insert.Enabled = true; - } - else - PlaceHolderParamters.Controls.Clear(); - - - if (assemblies.SelectedValue != "") - { - methods.Items.Clear(); - methods.Items.Add(new ListItem("Choose method", "")); - methods.Attributes.Add("onChange", "document.forms[0].submit()"); - List methodList = ht[assemblies.SelectedValue]; - foreach (string method in methodList) - { - ListItem li = new ListItem(method); - if (method == selectedMethod) - li.Selected = true; - methods.Items.Add(li); - } - } - } - - /// - /// Gets the XSLT assemblies and their methods. - /// - /// A list of assembly names linked to a list of method signatures. - private SortedList> GetXsltAssembliesAndMethods() - { - SortedList> _tempAssemblies = new SortedList>(); - - // add all extensions definied by macro - foreach(KeyValuePair extension in Umbraco.Web.Macros.XsltMacroEngine.GetXsltExtensions()) - _tempAssemblies.Add(extension.Key, GetStaticMethods(extension.Value.GetType())); - - // add the Umbraco library (not included in macro extensions) - _tempAssemblies.Add("umbraco.library", GetStaticMethods(typeof(umbraco.library))); - - return _tempAssemblies; - - } - - /// - /// Gets the static methods of the specified type, alphabetically sorted. - /// - /// The type. - /// A sortd list with method signatures. - private List GetStaticMethods(Type type) - { - List methods = new List(); - foreach (MethodInfo method in type.GetMethods()) - { - if (method.IsStatic) - { - // add method name to signature - StringBuilder methodSignature = new StringBuilder(method.Name); - - // add parameters to signature - methodSignature.Append('('); - ParameterInfo[] parameters = method.GetParameters(); - for(int i=0; i - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - ///
    - private void InitializeComponent() - { - } - #endregion - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.designer.cs deleted file mode 100644 index 2b5efd94bf..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltChooseExtension.aspx.designer.cs +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.developer { - - - public partial class xsltChooseExtension { - - /// - /// assemblies control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList assemblies; - - /// - /// methods control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList methods; - - /// - /// PlaceHolderParamters control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.PlaceHolder PlaceHolderParamters; - - /// - /// bt_insert control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button bt_insert; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx deleted file mode 100644 index 34142b2805..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx +++ /dev/null @@ -1,61 +0,0 @@ -<%@ Page Language="c#" MasterPageFile="../../masterpages/umbracoDialog.Master" Codebehind="xsltInsertValueOf.aspx.cs" AutoEventWireup="True" Inherits="umbraco.developer.xsltInsertValueOf" %> -<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" %> - - - - - - - - - - - - - - - - - - - - - - -

    - <%= Services.TextService.Localize("or") %> <%= Services.TextService.Localize("cancel") %> -

    -
    \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.cs deleted file mode 100644 index 1a0c1d1c90..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections; -using System.Linq; -using System.Web.UI.WebControls; -using Umbraco.Core; -using Umbraco.Web.UI.Pages; - -namespace umbraco.developer -{ - /// - /// Summary description for xsltInsertValueOf. - /// - [WebformsPageTreeAuthorize(Constants.Trees.Xslt)] - public partial class xsltInsertValueOf : UmbracoEnsuredPage - { - protected void Page_Load(object sender, System.EventArgs e) - { - ArrayList preValuesSource = new ArrayList(); - - // Attributes - string[] attributes = {"@id", "@parentID", "@level", "@writerID", "@nodeType", "@template", "@sortOrder", "@createDate", "@creatorName", "@updateDate", "@nodeName", "@urlName", "@writerName", "@nodeTypeAlias", "@path"}; - foreach (string att in attributes) - preValuesSource.Add(att); - - // generic properties - string existingGenProps = ","; - var exclude = Constants.Conventions.Member.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray(); - - var propertyTypes = Services.ContentTypeService.GetAllPropertyTypeAliases(); - - foreach (var ptAlias in propertyTypes.Where(x => exclude.Contains(x) == false)) - { - if (!existingGenProps.Contains("," + ptAlias + ",")) - { - preValuesSource.Add(ptAlias); - - - existingGenProps += ptAlias + ","; - } - } - - - preValuesSource.Sort(); - preValues.DataSource = preValuesSource; - preValues.DataBind(); - preValues.Items.Insert(0, new ListItem("Prevalues...", "")); - - preValues.Attributes.Add("onChange", "if (this.value != '') document.getElementById('" + valueOf.ClientID + "').value = this.value"); - - if(!String.IsNullOrEmpty(Request.QueryString["value"])) - valueOf.Text = Request.QueryString["value"]; - } - - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.designer.cs deleted file mode 100644 index d02006dd22..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltInsertValueOf.aspx.designer.cs +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.developer { - - - public partial class xsltInsertValueOf { - - /// - /// JsInclude1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::ClientDependency.Core.Controls.JsInclude JsInclude1; - - /// - /// valueOf control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox valueOf; - - /// - /// preValues control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList preValues; - - /// - /// disableOutputEscaping control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox disableOutputEscaping; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx deleted file mode 100644 index 74c40eca64..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx +++ /dev/null @@ -1,55 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="../../masterpages/umbracoDialog.Master" AutoEventWireup="true" - CodeBehind="xsltVisualize.aspx.cs" ValidateRequest="false" Inherits="umbraco.presentation.umbraco.developer.Xslt.xsltVisualize" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" Assembly="Umbraco.Web" %> -<%@ Register TagPrefix="cc2" Namespace="umbraco.controls" Assembly="Umbraco.Web" %> - - - - - - - - - - - -

    - -
    -
    - -

    - -

    - - - -
    - -
    diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.cs deleted file mode 100644 index fe4bca93e5..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -using System.Text; -using System.Xml; -using System.IO; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web.UI.Pages; - -namespace umbraco.presentation.umbraco.developer.Xslt -{ - [WebformsPageTreeAuthorize(Constants.Trees.Xslt)] - public partial class xsltVisualize : UmbracoEnsuredPage - { - private const string XsltVisualizeCookieName = "UMB_XSLTVISPG"; - - protected void Page_Load(object sender, EventArgs e) - { - if (!IsPostBack) - { - // Check if cookie exists in the current request. - // zb-00004 #29956 : refactor cookies names & handling - if (Request.HasCookieValue(XsltVisualizeCookieName)) - contentPicker.Value = Request.GetCookieValue(XsltVisualizeCookieName); - } - - } - - protected void visualizeDo_Click(object sender, EventArgs e) - { - // get xslt file - string xslt; - if (xsltSelection.Value.Contains("", xsltSelection.Value); - xslt = Umbraco.Web.Macros.XsltMacroEngine.AddXsltExtensionsToHeader(xslt); - } - - int pageId; - if (int.TryParse(contentPicker.Value, out pageId) == false) - pageId = -1; - - // transform - string xsltResult; - try - { - xsltResult = Umbraco.Web.Macros.XsltMacroEngine.TestXsltTransform(Current.ProfilingLogger, xslt, pageId); - } - catch (Exception ee) - { - xsltResult = string.Format( - "

    Error parsing the XSLT:

    {0}

    ", - ee.ToString()); - } - - visualizeContainer.Visible = true; - - // update output - visualizeArea.Text = !String.IsNullOrEmpty(xsltResult) ? "
    " + xsltResult + "
    " : "

    The XSLT didn't generate any output

    "; - - - // add cookie with current page - // zb-00004 #29956 : refactor cookies names & handling - Response.Cookies.Set(new HttpCookie(XsltVisualizeCookieName, contentPicker.Value) - { - Expires = DateTime.Now + TimeSpan.FromMinutes(20) - }); - } - - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.designer.cs deleted file mode 100644 index cfc124ef7a..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Xslt/xsltVisualize.aspx.designer.cs +++ /dev/null @@ -1,87 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.presentation.umbraco.developer.Xslt { - - - public partial class xsltVisualize { - - /// - /// Pane1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Pane1; - - /// - /// PropertyPanel1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.PropertyPanel PropertyPanel1; - - /// - /// xsltSelection control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlInputHidden xsltSelection; - - /// - /// contentPicker control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::umbraco.controls.ContentPicker contentPicker; - - /// - /// visualizeDo control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button visualizeDo; - - /// - /// visualizeContainer control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane visualizeContainer; - - /// - /// visualizePanel control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.PropertyPanel visualizePanel; - - /// - /// visualizeArea control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Literal visualizeArea; - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/InlineXslt.xsltTemplate b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/InlineXslt.xsltTemplate deleted file mode 100644 index b26ca5da89..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/InlineXslt.xsltTemplate +++ /dev/null @@ -1,14 +0,0 @@ - - ]> - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Item.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Item.cs index b015fdd02a..0439cfe89d 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Item.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Item.cs @@ -82,42 +82,7 @@ namespace umbraco.presentation.templateControls get { return (string)ViewState["TextIfEmpty"] ?? String.Empty; } set { ViewState["TextIfEmpty"] = value; } } - - /// - /// Gets or sets the XPath expression used for the inline XSLT transformation. - /// - /// - /// The XPath expression, or an empty string to disable XSLT transformation. - /// The code {0} is used as a placeholder for the rendered field contents. - /// - [Bindable(true)] - [Category("Umbraco")] - [DefaultValue("")] - [Localizable(true)] - public string Xslt - { - get { return (string)ViewState["Xslt"] ?? String.Empty; } - set { ViewState["Xslt"] = value; } - } - - /// - /// Gets or sets a value indicating whether XML entity escaping of the XSLT transformation output is disabled. - /// - /// true HTML escaping is disabled; otherwise, false (default). - /// - /// This corresponds value to the disable-output-escaping parameter - /// of the XSLT value-of element. - /// - [Bindable(true)] - [Category("Umbraco")] - [DefaultValue(false)] - [Localizable(true)] - public bool XsltDisableEscaping - { - get { return ViewState["XsltEscape"] == null ? false : (bool)ViewState["XsltEscape"]; } - set { ViewState["XsltEscape"] = value; } - } - + [Bindable(true)] [Category("Umbraco")] [DefaultValue("")] diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs index 06c09225e2..13414c7648 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/ItemRenderer.cs @@ -56,12 +56,10 @@ namespace umbraco.presentation.templateControls // parse macros and execute the XSLT transformation on the result if not empty string renderOutput = renderOutputWriter.ToString(); - string xsltTransformedOutput = renderOutput.Trim().Length == 0 - ? String.Empty - : XsltTransform(item.Xslt, renderOutput, item.XsltDisableEscaping); + renderOutput = renderOutput.Trim().Length == 0 ? string.Empty : renderOutput; // handle text before/after - xsltTransformedOutput = AddBeforeAfterText(xsltTransformedOutput, helper.FindAttribute(item.LegacyAttributes, "insertTextBefore"), helper.FindAttribute(item.LegacyAttributes, "insertTextAfter")); - string finalResult = xsltTransformedOutput.Trim().Length > 0 ? xsltTransformedOutput : GetEmptyText(item); + renderOutput = AddBeforeAfterText(renderOutput, helper.FindAttribute(item.LegacyAttributes, "insertTextBefore"), helper.FindAttribute(item.LegacyAttributes, "insertTextAfter")); + string finalResult = renderOutput.Trim().Length > 0 ? renderOutput : GetEmptyText(item); //Don't parse urls if a content item is assigned since that is taken care // of with the value converters @@ -192,48 +190,6 @@ namespace umbraco.presentation.templateControls } - /// - /// Transforms the content using the XSLT attribute, if provided. - /// - /// The xpath expression. - /// The item's rendered content. - /// if set to true, escaping is disabled. - /// The transformed content if the XSLT attribute is present, otherwise the original content. - protected virtual string XsltTransform(string xpath, string itemData, bool disableEscaping) - { - if (!String.IsNullOrEmpty(xpath)) - { - // XML-encode the expression and add the itemData parameter to it - string xpathEscaped = xpath.Replace("<", "<").Replace(">", ">").Replace("\"", """); - string xpathExpression = string.Format(xpathEscaped, "$itemData"); - - // prepare support for XSLT extensions - StringBuilder namespaceList = new StringBuilder(); - StringBuilder namespaceDeclaractions = new StringBuilder(); - foreach (KeyValuePair extension in Umbraco.Web.Macros.XsltMacroEngine.GetXsltExtensions()) - { - namespaceList.Append(extension.Key).Append(' '); - namespaceDeclaractions.AppendFormat("xmlns:{0}=\"urn:{0}\" ", extension.Key); - } - - // add the XSLT expression into the full XSLT document, together with the needed parameters - string xslt = string.Format(Umbraco.Web.umbraco.presentation.umbraco.templateControls.Resources.InlineXslt, xpathExpression, disableEscaping ? "yes" : "no", - namespaceList, namespaceDeclaractions); - - // create the parameter - Dictionary parameters = new Dictionary(1); - parameters.Add("itemData", itemData); - - // apply the XSLT transformation - using (var xslReader = new XmlTextReader(new StringReader(xslt))) - { - var transform = Umbraco.Web.Macros.XsltMacroEngine.GetXsltTransform(xslReader, false); - return Umbraco.Web.Macros.XsltMacroEngine.ExecuteItemRenderer(Current.ProfilingLogger, transform, itemData); - } - } - return itemData; - } - protected string AddBeforeAfterText(string text, string before, string after) { if (!String.IsNullOrEmpty(text)) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.Designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.Designer.cs deleted file mode 100644 index ab69886621..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.Designer.cs +++ /dev/null @@ -1,84 +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.Web.umbraco.presentation.umbraco.templateControls { - 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 Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// 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.Web.umbraco.presentation.umbraco.templateControls.Resources", typeof(Resources).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"?> - ///<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#x00A0;"> ]> - ///<xsl:stylesheet - /// version="1.0" - /// xmlns:xsl="http://www.w3.org/1999/XSL/Transform" - /// xmlns:msxml="urn:schemas-microsoft-com:xslt" - /// xmlns:umbraco.library="urn:umbraco.library" - /// {3} - /// exclude-result-prefixes="msxml umbraco.library {2}"> - ///<xsl:output method="xml" omit-xml-declaration="yes"/> - ///<xsl:param name="currentPage"/> - ///<xsl:param name="itemData"/> - ///<xsl:template match="/"><xsl:value-of select="{0}" disa [rest of string was truncated]";. - /// - internal static string InlineXslt { - get { - return ResourceManager.GetString("InlineXslt", resourceCulture); - } - } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.resx b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.resx deleted file mode 100644 index 00bf9d42e1..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Resources.resx +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - inlinexslt.xsltTemplate;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - - \ No newline at end of file diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx deleted file mode 100644 index 46767336e7..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx +++ /dev/null @@ -1 +0,0 @@ -<%@ WebService Language="C#" CodeBehind="codeEditorSave.asmx.cs" Class="umbraco.presentation.webservices.codeEditorSave" %> diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs deleted file mode 100644 index f39dd051be..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Text.RegularExpressions; -using System.Web.Script.Services; -using System.Web.Services; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Web.WebServices; -using Umbraco.Web.Macros; - -namespace umbraco.presentation.webservices -{ - /// - /// Summary description for codeEditorSave - /// - [WebService(Namespace = "http://tempuri.org/")] - [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] - [ToolboxItem(false)] - [ScriptService] - public class codeEditorSave : UmbracoAuthorizedWebService - { - [WebMethod] - public string SaveXslt(string fileName, string oldName, string fileContents, bool ignoreDebugging) - { - if (AuthorizeRequest(Constants.Applications.Developer.ToString())) - { - IOHelper.EnsurePathExists(SystemDirectories.Xslt); - - // validate file - IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), - SystemDirectories.Xslt); - // validate extension - IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), - new List() { "xsl", "xslt" }); - - StreamWriter SW; - string tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + DateTime.Now.Ticks + "_temp.xslt"); - SW = File.CreateText(tempFileName); - SW.Write(fileContents); - SW.Close(); - - // Test the xslt - string errorMessage = ""; - - if (ignoreDebugging == false) - { - try - { - if (UmbracoContext.ContentCache.HasContent()) - XsltMacroEngine.TestXsltTransform(ProfilingLogger, fileContents); - - /* - // Check if there's any documents yet - string xpath = "/root/*"; - if (content.Instance.XmlContent.SelectNodes(xpath).Count > 0) - { - var macroXML = new XmlDocument(); - macroXML.LoadXml(""); - - var macroXSLT = new XslCompiledTransform(); - var umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//* [@parentID = -1]")); - - var xslArgs = macro.AddMacroXsltExtensions(); - var lib = new library(umbPage); - xslArgs.AddExtensionObject("urn:umbraco.library", lib); - HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions"); - - // Add the current node - xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString())); - - HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation"); - - // Create reader and load XSL file - // We need to allow custom DTD's, useful for defining an ENTITY - var readerSettings = new XmlReaderSettings(); - readerSettings.ProhibitDtd = false; - using (var xmlReader = XmlReader.Create(tempFileName, readerSettings)) - { - var xslResolver = new XmlUrlResolver(); - xslResolver.Credentials = CredentialCache.DefaultCredentials; - macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver); - xmlReader.Close(); - // Try to execute the transformation - var macroResult = new HtmlTextWriter(new StringWriter()); - macroXSLT.Transform(macroXML, xslArgs, macroResult); - macroResult.Close(); - - File.Delete(tempFileName); - } - } - */ - else - { - //errorMessage = Services.TextService.Localize("developer/xsltErrorNoNodesPublished"); - File.Delete(tempFileName); - //base.speechBubble(speechBubbleIcon.info, Services.TextService.Localize("errors/xsltErrorHeader"), "Unable to validate xslt as no published content nodes exist."); - } - } - catch (Exception errorXslt) - { - File.Delete(tempFileName); - - errorMessage = (errorXslt.InnerException ?? errorXslt).ToString(); - - // Full error message - errorMessage = errorMessage.Replace("\n", "
    \n"); - //closeErrorMessage.Visible = true; - - // Find error - var m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - foreach (Match mm in m) - { - string[] errorLine = mm.Value.Split(','); - - if (errorLine.Length > 0) - { - var theErrorLine = int.Parse(errorLine[0]); - var theErrorChar = int.Parse(errorLine[1]); - - errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] + - "
    "; - errorMessage += ""; - - var xsltText = fileContents.Split("\n".ToCharArray()); - for (var i = 0; i < xsltText.Length; i++) - { - if (i >= theErrorLine - 3 && i <= theErrorLine + 1) - if (i + 1 == theErrorLine) - { - errorMessage += "" + (i + 1) + ": >>>  " + - Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar)); - errorMessage += - "" + - Server.HtmlEncode( - xsltText[i].Substring(theErrorChar, - xsltText[i].Length - theErrorChar)). - Trim() + ""; - errorMessage += " <<<
    "; - } - else - errorMessage += (i + 1) + ":      " + - Server.HtmlEncode(xsltText[i]) + "
    "; - } - errorMessage += "
    "; - } - } - } - } - - if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt")) - { - //Hardcoded security-check... only allow saving files in xslt directory... - var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); - - if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt + "/"))) - { - //deletes the old xslt file - if (fileName != oldName) - { - - var p = IOHelper.MapPath(SystemDirectories.Xslt + "/" + oldName); - if (File.Exists(p)) - File.Delete(p); - } - - SW = File.CreateText(savePath); - SW.Write(fileContents); - SW.Close(); - errorMessage = "true"; - - - } - else - { - errorMessage = "Illegal path"; - } - } - - File.Delete(tempFileName); - - return errorMessage; - } - return "false"; - } - } -} From 0a5db8f97b1e53e2a6d705184e45d34ec3d91b62 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 00:35:49 +1000 Subject: [PATCH 49/58] Fixes up macros and file trees --- .../developer/Macros/EditMacro.aspx.cs | 4 +- .../umbraco/developer/Macros/editMacro.aspx | 5 +- .../Trees/FileSystemTreeController.cs | 134 ++++++++---------- .../Trees/PartialViewsTreeController.cs | 2 - .../Trees/ScriptsTreeController.cs | 2 - .../Trees/StylesheetsTreeController.cs | 2 - .../developer/Macros/editMacro.aspx.cs | 95 ++----------- 7 files changed, 78 insertions(+), 166 deletions(-) diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs index 621b2926e6..353828f7dc 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs @@ -49,9 +49,9 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Macros /// /// /// - protected override void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroAssemblyValue, string macroTypeValue) + protected override void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroTypeValue) { - base.SetMacroValuesFromPostBack(macro, macroCachePeriod, macroAssemblyValue, macroTypeValue); + base.SetMacroValuesFromPostBack(macro, macroCachePeriod, macroTypeValue); if (!SelectedPartialView.Text.IsNullOrWhiteSpace()) { macro.ScriptPath = SelectedPartialView.Text; diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx b/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx index fc8aff082d..7fef2cf9ab 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/editMacro.aspx @@ -57,6 +57,9 @@ + + + @@ -149,7 +152,7 @@ - + diff --git a/src/Umbraco.Web/Trees/FileSystemTreeController.cs b/src/Umbraco.Web/Trees/FileSystemTreeController.cs index c31da79724..21e81a58af 100644 --- a/src/Umbraco.Web/Trees/FileSystemTreeController.cs +++ b/src/Umbraco.Web/Trees/FileSystemTreeController.cs @@ -18,30 +18,28 @@ namespace Umbraco.Web.Trees protected abstract IFileSystem FileSystem { get; } protected abstract string[] Extensions { get; } protected abstract string FileIcon { get; } - protected abstract bool EnableCreateOnFolder { get; } /// /// Inheritors can override this method to modify the file node that is created. /// - protected virtual void OnRenderFileNode(ref TreeNode treeNode) - { } + /// + protected virtual void OnRenderFileNode(ref TreeNode treeNode) { } /// /// Inheritors can override this method to modify the folder node that is created. /// - protected virtual void OnRenderFolderNode(ref TreeNode treeNode) - { } + /// + protected virtual void OnRenderFolderNode(ref TreeNode treeNode) { } protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) { - var nodes = new TreeNodeCollection(); - var path = string.IsNullOrEmpty(id) == false && id != Constants.System.Root.ToInvariantString() ? HttpUtility.UrlDecode(id).TrimStart("/") : ""; var directories = FileSystem.GetDirectories(path); + var nodes = new TreeNodeCollection(); foreach (var directory in directories) { var hasChildren = FileSystem.GetFiles(directory).Any() || FileSystem.GetDirectories(directory).Any(); @@ -53,24 +51,22 @@ namespace Umbraco.Web.Trees nodes.Add(node); } + //this is a hack to enable file system tree to support multiple file extension look-up + //so the pattern both support *.* *.xml and xml,js,vb for lookups var files = FileSystem.GetFiles(path).Where(x => { var extension = Path.GetExtension(x); return extension != null && Extensions.Contains(extension.Trim('.'), StringComparer.InvariantCultureIgnoreCase); - - // fixme - should we filter out hidden files? but then, FileSystem does not support attributes! }); foreach (var file in files) { var withoutExt = Path.GetFileNameWithoutExtension(file); - if (string.IsNullOrWhiteSpace(withoutExt)) continue; + if (withoutExt.IsNullOrWhiteSpace()) continue; var name = Path.GetFileName(file); var node = CreateTreeNode(HttpUtility.UrlEncode(file), path, queryStrings, name, FileIcon, false); - OnRenderFileNode(ref node); - if (node != null) nodes.Add(node); } @@ -78,89 +74,77 @@ namespace Umbraco.Web.Trees return nodes; } - protected virtual TreeNodeCollection GetTreeNodesForFile(string path, string id, FormDataCollection queryStrings) - { - return new TreeNodeCollection(); - } - - protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) + protected virtual MenuItemCollection GetMenuForRootNode(FormDataCollection queryStrings) { var menu = new MenuItemCollection(); - OnBeforeRenderMenu(menu, id, queryStrings); - - // if root node no need to visit the filesystem so lets just create the menu and return it - if (id == Constants.System.Root.ToInvariantString()) - { - GetMenuForRootNode(menu, queryStrings); - } - else - { - var path = string.IsNullOrEmpty(id) == false && id != Constants.System.Root.ToInvariantString() - ? HttpUtility.UrlDecode(id).TrimStart("/") - : ""; - var isFile = FileSystem.FileExists(path); - var isDirectory = FileSystem.DirectoryExists(path); - - if (isDirectory) - GetMenuForFolder(menu, path, id, queryStrings); - else if (isFile) - GetMenuForFile(menu, path, id, queryStrings); - } - - OnAfterRenderMenu(menu, id, queryStrings); + //set the default to create + menu.DefaultMenuAlias = ActionNew.Instance.Alias; + //create action + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionNew.Instance.Alias))); + //refresh action + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionRefresh.Instance.Alias)), true); return menu; } - protected virtual void GetMenuForRootNode(MenuItemCollection menu, FormDataCollection queryStrings) + protected virtual MenuItemCollection GetMenuForFolder(string path, FormDataCollection queryStrings) { - // default create + var menu = new MenuItemCollection(); + + //set the default to create menu.DefaultMenuAlias = ActionNew.Instance.Alias; + //create action + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionNew.Instance.Alias))); - // create action - //Since we haven't implemented anything for file systems in angular, this needs to be converted to - //use the legacy format - menu.Items.Add(Services.TextService.Localize("actions", ActionNew.Instance.Alias)) - .ConvertLegacyFileSystemMenuItem("", "init" + TreeAlias, queryStrings.GetValue("application")); + var hasChildren = FileSystem.GetFiles(path).Any() || FileSystem.GetDirectories(path).Any(); - // refresh action - menu.Items.Add(Services.TextService.Localize("actions", ActionRefresh.Instance.Alias), true); - } - - protected virtual void GetMenuForFolder(MenuItemCollection menu, string path, string id, FormDataCollection queryStrings) - { - if (EnableCreateOnFolder) + //We can only delete folders if it doesn't have any children (folders or files) + if (hasChildren == false) { - // default create - menu.DefaultMenuAlias = ActionNew.Instance.Alias; - - // create action - //Since we haven't implemented anything for file systems in angular, this needs to be converted to - //use the legacy format - menu.Items.Add(Services.TextService.Localize("actions", ActionNew.Instance.Alias)) - .ConvertLegacyFileSystemMenuItem(id, TreeAlias + "Folder", queryStrings.GetValue("application")); + //delete action + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionDelete.Instance.Alias)), true); } - // delete action - menu.Items.Add(Services.TextService.Localize("actions", ActionDelete.Instance.Alias), true) - .ConvertLegacyFileSystemMenuItem(id, TreeAlias + "Folder", queryStrings.GetValue("application")); + //refresh action + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionRefresh.Instance.Alias)), true); - // refresh action - menu.Items.Add(Services.TextService.Localize("actions", ActionRefresh.Instance.Alias), true); + return menu; } - protected virtual void GetMenuForFile(MenuItemCollection menu, string path, string id, FormDataCollection queryStrings) + protected virtual MenuItemCollection GetMenuForFile(string path, FormDataCollection queryStrings) { - // delete action - menu.Items.Add(Services.TextService.Localize("actions", ActionDelete.Instance.Alias), true) - .ConvertLegacyFileSystemMenuItem(id, TreeAlias, queryStrings.GetValue("application")); + var menu = new MenuItemCollection(); + + //if it's not a directory then we only allow to delete the item + menu.Items.Add(Services.TextService.Localize(string.Format("actions/{0}", ActionDelete.Instance.Alias))); + + return menu; } - protected virtual void OnBeforeRenderMenu(MenuItemCollection menu, string id, FormDataCollection queryStrings) - { } + protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) + { + //if root node no need to visit the filesystem so lets just create the menu and return it + if (id == Constants.System.Root.ToInvariantString()) + { + return GetMenuForRootNode(queryStrings); + } - protected virtual void OnAfterRenderMenu(MenuItemCollection menu, string id, FormDataCollection queryStrings) - { } + var menu = new MenuItemCollection(); + + var path = string.IsNullOrEmpty(id) == false && id != Constants.System.Root.ToInvariantString() + ? HttpUtility.UrlDecode(id).TrimStart("/") + : ""; + + var isFile = FileSystem.FileExists(path); + var isDirectory = FileSystem.DirectoryExists(path); + + if (isDirectory) + { + return GetMenuForFolder(path, queryStrings); + } + + return isFile ? GetMenuForFile(path, queryStrings) : menu; + } } } diff --git a/src/Umbraco.Web/Trees/PartialViewsTreeController.cs b/src/Umbraco.Web/Trees/PartialViewsTreeController.cs index 2aa52a563e..aaaeb2d175 100644 --- a/src/Umbraco.Web/Trees/PartialViewsTreeController.cs +++ b/src/Umbraco.Web/Trees/PartialViewsTreeController.cs @@ -31,7 +31,5 @@ namespace Umbraco.Web.Trees treeNode.AdditionalData["jsClickCallback"] = "javascript:void(0);"; treeNode.Icon = "icon-article"; } - - protected override bool EnableCreateOnFolder => true; } } diff --git a/src/Umbraco.Web/Trees/ScriptsTreeController.cs b/src/Umbraco.Web/Trees/ScriptsTreeController.cs index adab7b5c4c..47d7aa6b8f 100644 --- a/src/Umbraco.Web/Trees/ScriptsTreeController.cs +++ b/src/Umbraco.Web/Trees/ScriptsTreeController.cs @@ -17,8 +17,6 @@ namespace Umbraco.Web.Trees protected override string FileIcon => "icon-script"; - protected override bool EnableCreateOnFolder => true; - protected override void OnRenderFolderNode(ref TreeNode treeNode) { //TODO: This isn't the best way to ensure a noop process for clicking a node but it works for now. diff --git a/src/Umbraco.Web/Trees/StylesheetsTreeController.cs b/src/Umbraco.Web/Trees/StylesheetsTreeController.cs index f044d7ea60..650407296e 100644 --- a/src/Umbraco.Web/Trees/StylesheetsTreeController.cs +++ b/src/Umbraco.Web/Trees/StylesheetsTreeController.cs @@ -14,7 +14,5 @@ namespace Umbraco.Web.Trees protected override string[] Extensions => ExtensionsStatic; protected override string FileIcon => "icon-brackets"; - - protected override bool EnableCreateOnFolder => false; } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs index 1f2fcf515c..2183f5fc83 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs @@ -52,10 +52,7 @@ namespace umbraco.cms.presentation.developer PopulateFieldsOnLoad(_macro, tempMacroType); // Load elements from macro - macroPropertyBind(); - - // Load xslt files from default dir - PopulateXsltFiles(); + MacroPropertyBind(); // Load usercontrols PopulateUserControls(IOHelper.MapPath(SystemDirectories.UserControls)); @@ -81,21 +78,13 @@ namespace umbraco.cms.presentation.developer cacheByPage.Checked = macro.CacheByPage; cachePersonalized.Checked = macro.CacheByMember; - // Populate either user control or custom control - if (macroTypeValue != string.Empty) - { - macroType.Text = macroTypeValue; - } - else - { - macroUserControl.Text = macroTypeValue; - } + macroUserControl.Text = macroTypeValue; } /// /// Sets the values on the Macro object from the values posted back before saving the macro /// - protected virtual void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroAssemblyValue, string macroTypeValue) + protected virtual void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroTypeValue) { macro.UseInEditor = macroEditor.Checked; macro.DontRender = macroRenderContent.Checked == false; @@ -106,37 +95,8 @@ namespace umbraco.cms.presentation.developer macro.Name = macroName.Text; macro.ControlType = macroTypeValue; } - - private static void GetXsltFilesFromDir(string orgPath, string path, ArrayList files) - { - var dirInfo = new DirectoryInfo(path); - - if (dirInfo.Exists == false) return; - - // Populate subdirectories - var dirInfos = dirInfo.GetDirectories(); - foreach (var dir in dirInfos) - GetXsltFilesFromDir(orgPath, path + "/" + dir.Name, files); - - var fileInfo = dirInfo.GetFiles("*.xsl*"); - - foreach (var file in fileInfo) - files.Add((path.Replace(orgPath, string.Empty).Trim('/') + "/" + file.Name).Trim('/')); - } - - private void PopulateXsltFiles() - { - var xslts = new ArrayList(); - var xsltDir = IOHelper.MapPath(SystemDirectories.Xslt + "/"); - GetXsltFilesFromDir(xsltDir, xsltDir, xslts); - xsltFiles.DataSource = xslts; - xsltFiles.DataBind(); - xsltFiles.Items.Insert(0, new ListItem("Browse xslt files on server...", string.Empty)); - } - - - - public void deleteMacroProperty(object sender, EventArgs e) + + public void DeleteMacroProperty(object sender, EventArgs e) { var macroPropertyId = (HtmlInputHidden)((Control)sender).Parent.FindControl("macroPropertyID"); @@ -145,10 +105,10 @@ namespace umbraco.cms.presentation.developer Services.MacroService.Save(_macro); - macroPropertyBind(); + MacroPropertyBind(); } - public void macroPropertyBind() + public void MacroPropertyBind() { macroProperties.DataSource = _macro.Properties.OrderBy(x => x.SortOrder); macroProperties.DataBind(); @@ -203,7 +163,7 @@ namespace umbraco.cms.presentation.developer Services.MacroService.Save(_macro); - macroPropertyBind(); + MacroPropertyBind(); } } @@ -274,15 +234,13 @@ namespace umbraco.cms.presentation.developer ClientTools .SyncTree("-1," + _macro.Id.ToInvariantString(), true); //true forces the reload - var tempMacroAssembly = macroAssembly.Text; - var tempMacroType = macroType.Text; + var tempCachePeriod = cachePeriod.Text; if (tempCachePeriod == string.Empty) tempCachePeriod = "0"; - if (tempMacroAssembly == string.Empty && macroUserControl.Text != string.Empty) - tempMacroType = macroUserControl.Text; + var tempMacroType = macroUserControl.Text; - SetMacroValuesFromPostBack(_macro, Convert.ToInt32(tempCachePeriod), tempMacroAssembly, tempMacroType); + SetMacroValuesFromPostBack(_macro, Convert.ToInt32(tempCachePeriod), tempMacroType); // save elements // this is oh so completely broken @@ -324,7 +282,7 @@ namespace umbraco.cms.presentation.developer ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Save, "Macro saved", ""); - macroPropertyBind(); + MacroPropertyBind(); } /// @@ -390,15 +348,6 @@ namespace umbraco.cms.presentation.developer /// protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_2; - /// - /// xsltFiles control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList xsltFiles; - /// /// macroUserControl control. /// @@ -416,25 +365,7 @@ namespace umbraco.cms.presentation.developer /// To modify move field declaration from designer file to code-behind file. /// protected global::System.Web.UI.WebControls.DropDownList userControlList; - - /// - /// macroAssembly control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroAssembly; - - /// - /// macroType control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroType; - + /// /// Pane1_3 control. /// From 0a18306d40751c39651e20af09915e7c2aead97a Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 00:45:05 +1000 Subject: [PATCH 50/58] More xslt removal --- src/Umbraco.Core/Cache/CacheKeys.cs | 46 +----- .../RepositoryCompositionRoot.cs | 1 - src/Umbraco.Core/Constants-Applications.cs | 4 +- src/Umbraco.Core/Constants-Composing.cs | 1 - src/Umbraco.Core/IO/FileSystems.cs | 15 +- src/Umbraco.Core/IO/SystemDirectories.cs | 2 - src/Umbraco.Core/Models/IXsltFile.cs | 7 - src/Umbraco.Core/Models/XsltFile.cs | 32 ----- .../Repositories/IXsltFileRepository.cs | 13 -- .../Implement/XsltFileRepository.cs | 133 ------------------ .../Runtime/CoreRuntimeComponent.cs | 1 - src/Umbraco.Core/Services/IFileService.cs | 23 --- .../Services/Implement/FileService.cs | 51 +------ src/Umbraco.Core/UdiEntityType.cs | 4 +- src/Umbraco.Core/UdiGetterExtensions.cs | 16 +-- src/Umbraco.Core/Umbraco.Core.csproj | 4 - src/Umbraco.Tests/IO/IoHelperTests.cs | 1 - src/Umbraco.Tests/TestHelpers/TestObjects.cs | 2 +- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 43 ------ .../umbraco/developer/Xslt/editXslt.aspx | 68 --------- .../umbraco/developer/Xslt/getXsltStatus.asmx | 1 - .../developer/Xslt/xsltChooseExtension.aspx | 44 ------ .../developer/Xslt/xsltInsertValueOf.aspx | 62 -------- .../umbraco/developer/Xslt/xsltVisualize.aspx | 70 --------- .../umbraco/developer/autoDoc.aspx | 23 --- src/Umbraco.Web.UI/umbraco/xslt/Web.config | 18 --- .../umbraco/xslt/macroGetCurrent.xsl | 23 --- .../umbraco/xslt/macroGetSubs.xsl | 38 ----- .../umbraco/xslt/searchResult.xslt | 32 ----- .../umbraco/xslt/sqlNodeHierachy.xslt | 85 ----------- .../umbraco/xslt/templates/Breadcrumb.xslt | 34 ----- .../umbraco/xslt/templates/Clean.xslt | 21 --- .../templates/ListSubPagesAsThumbnails.xslt | 33 ----- .../templates/ListSubPagesByDateAndLimit.xslt | 36 ----- .../templates/ListSubPagesByDocumentType.xslt | 32 ----- .../xslt/templates/ListSubPagesByLevel.xslt | 32 ----- .../ListSubPagesFromAChangableSource.xslt | 33 ----- .../ListSubPagesFromCurrentPage.xslt | 29 ---- .../ListThumbnailsFromCurrentPage.xslt | 31 ---- .../ListWholeStructureFromCurrentPage.xslt | 30 ---- .../xslt/templates/NavigationPrototype.xslt | 40 ------ .../umbraco/xslt/templates/RSSFeed.xslt | 92 ------------ .../umbraco/xslt/templates/RelatedLinks.xslt | 51 ------- .../xslt/templates/Schema2/Breadcrumb.xslt | 34 ----- .../umbraco/xslt/templates/Schema2/Clean.xslt | 21 --- .../Schema2/ListSubPagesAsThumbnails.xslt | 33 ----- .../Schema2/ListSubPagesByDateAndLimit.xslt | 36 ----- .../Schema2/ListSubPagesByDocumentType.xslt | 32 ----- .../Schema2/ListSubPagesByLevel.xslt | 32 ----- .../ListSubPagesFromAChangableSource.xslt | 33 ----- .../Schema2/ListSubPagesFromCurrentPage.xslt | 29 ---- .../ListThumbnailsFromCurrentPage.xslt | 31 ---- .../ListWholeStructureFromCurrentPage.xslt | 30 ---- .../Schema2/NavigationPrototype.xslt | 40 ------ .../xslt/templates/Schema2/RSSFeed.xslt | 92 ------------ .../xslt/templates/Schema2/RelatedLinks.xslt | 51 ------- .../xslt/templates/Schema2/Sitemap.xslt | 42 ------ .../templates/Schema2/TablePrototype.xslt | 54 ------- .../umbraco/xslt/templates/Sitemap.xslt | 42 ------ .../xslt/templates/TablePrototype.xslt | 54 ------- .../Cache/ContentCacheRefresher.cs | 14 +- .../Cache/DataTypeCacheRefresher.cs | 3 - src/Umbraco.Web/Cache/MacroCacheRefresher.cs | 5 - .../FolderAndFilePermissionsCheck.cs | 3 +- .../Install/FilePermissionHelper.cs | 2 +- 65 files changed, 12 insertions(+), 2058 deletions(-) delete mode 100644 src/Umbraco.Core/Models/IXsltFile.cs delete mode 100644 src/Umbraco.Core/Models/XsltFile.cs delete mode 100644 src/Umbraco.Core/Persistence/Repositories/IXsltFileRepository.cs delete mode 100644 src/Umbraco.Core/Persistence/Repositories/Implement/XsltFileRepository.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Xslt/getXsltStatus.asmx delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltChooseExtension.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltInsertValueOf.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltVisualize.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/developer/autoDoc.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/Web.config delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/macroGetCurrent.xsl delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/macroGetSubs.xsl delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/searchResult.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/sqlNodeHierachy.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Breadcrumb.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Clean.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesAsThumbnails.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDateAndLimit.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDocumentType.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByLevel.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromAChangableSource.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListThumbnailsFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/ListWholeStructureFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/NavigationPrototype.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/RSSFeed.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/RelatedLinks.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Breadcrumb.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Clean.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesAsThumbnails.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDateAndLimit.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDocumentType.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByLevel.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromAChangableSource.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListThumbnailsFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListWholeStructureFromCurrentPage.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/NavigationPrototype.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RSSFeed.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RelatedLinks.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Sitemap.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/TablePrototype.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/Sitemap.xslt delete mode 100644 src/Umbraco.Web.UI/umbraco/xslt/templates/TablePrototype.xslt diff --git a/src/Umbraco.Core/Cache/CacheKeys.cs b/src/Umbraco.Core/Cache/CacheKeys.cs index 68b4c3b157..bba5655b7a 100644 --- a/src/Umbraco.Core/Cache/CacheKeys.cs +++ b/src/Umbraco.Core/Cache/CacheKeys.cs @@ -22,9 +22,7 @@ namespace Umbraco.Core.Cache [UmbracoWillObsolete("This cache key is only used for the legacy 'library' caching, remove in v8")] public const string MediaCacheKey = "UL_GetMedia"; - - public const string MacroXsltCacheKey = "macroXslt_"; - + [UmbracoWillObsolete("This cache key is only used for legacy business logic caching, remove in v8")] public const string MacroCacheKey = "UmbracoMacroCache"; @@ -39,54 +37,14 @@ namespace Umbraco.Core.Cache [UmbracoWillObsolete("This cache key is only used for legacy template business logic caching, remove in v8")] public const string TemplateFrontEndCacheKey = "template"; - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string TemplateBusinessLogicCacheKey = "UmbracoTemplateCache"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string UserContextCacheKey = "UmbracoUserContext"; - public const string UserContextTimeoutCacheKey = "UmbracoUserContextTimeout"; - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string UserCacheKey = "UmbracoUser"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string UserGroupPermissionsCacheKey = "UmbracoUserGroupPermissions"; - [UmbracoWillObsolete("This cache key is only used for legacy business logic caching, remove in v8")] public const string ContentTypeCacheKey = "UmbracoContentType"; [UmbracoWillObsolete("This cache key is only used for legacy business logic caching, remove in v8")] public const string ContentTypePropertiesCacheKey = "ContentType_PropertyTypes_Content:"; - - [Obsolete("No longer used and will be removed in v8")] - public const string PropertyTypeCacheKey = "UmbracoPropertyTypeCache"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string LanguageCacheKey = "UmbracoLanguageCache"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string DomainCacheKey = "UmbracoDomainList"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string StylesheetCacheKey = "UmbracoStylesheet"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string StylesheetPropertyCacheKey = "UmbracoStylesheetProperty"; - - [Obsolete("This is no longer used and will be removed from the codebase in the future")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string DataTypeCacheKey = "UmbracoDataTypeDefinition"; - public const string DataTypePreValuesCacheKey = "UmbracoPreVal"; - + public const string IdToKeyCacheKey = "UI2K__"; public const string KeyToIdCacheKey = "UK2I__"; } diff --git a/src/Umbraco.Core/Composing/CompositionRoots/RepositoryCompositionRoot.cs b/src/Umbraco.Core/Composing/CompositionRoots/RepositoryCompositionRoot.cs index 56538a8058..26a95af801 100644 --- a/src/Umbraco.Core/Composing/CompositionRoots/RepositoryCompositionRoot.cs +++ b/src/Umbraco.Core/Composing/CompositionRoots/RepositoryCompositionRoot.cs @@ -76,7 +76,6 @@ namespace Umbraco.Core.Composing.CompositionRoots container.RegisterSingleton(); container.RegisterSingleton(); container.RegisterSingleton(); - container.RegisterSingleton(); } } } diff --git a/src/Umbraco.Core/Constants-Applications.cs b/src/Umbraco.Core/Constants-Applications.cs index 4c859469fd..7d8476989a 100644 --- a/src/Umbraco.Core/Constants-Applications.cs +++ b/src/Umbraco.Core/Constants-Applications.cs @@ -121,9 +121,7 @@ public const string Templates = "templates"; public const string RelationTypes = "relationTypes"; - - public const string Xslt = "xslt"; - + public const string Languages = "languages"; /// diff --git a/src/Umbraco.Core/Constants-Composing.cs b/src/Umbraco.Core/Constants-Composing.cs index 734a715c2d..1e8c9886d2 100644 --- a/src/Umbraco.Core/Constants-Composing.cs +++ b/src/Umbraco.Core/Constants-Composing.cs @@ -21,7 +21,6 @@ public const string StylesheetFileSystem = "StylesheetFileSystem"; public const string MasterpageFileSystem = "MasterpageFileSystem"; public const string ViewFileSystem = "ViewFileSystem"; - public const string XsltFileSystem = "XsltFileSystem"; public const string JavascriptLibraryFileSystem = "JavascriptLibraryFileSystem"; } } diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 39e7fa30fc..2366bde7e2 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -26,7 +26,6 @@ namespace Umbraco.Core.IO private ShadowWrapper _partialViewsFileSystem; private ShadowWrapper _stylesheetsFileSystem; private ShadowWrapper _scriptsFileSystem; - private ShadowWrapper _xsltFileSystem; private ShadowWrapper _masterPagesFileSystem; private ShadowWrapper _mvcViewsFileSystem; private ShadowWrapper _javaScriptLibraryFileSystem; @@ -103,16 +102,7 @@ namespace Umbraco.Core.IO return _scriptsFileSystem; } } - - public IFileSystem XsltFileSystem - { - get - { - if (Volatile.Read(ref _wkfsInitialized) == false) EnsureWellKnownFileSystems(); - return _xsltFileSystem; - } - } - + public IFileSystem MasterPagesFileSystem { get @@ -163,7 +153,6 @@ namespace Umbraco.Core.IO var partialViewsFileSystem = new PhysicalFileSystem(SystemDirectories.PartialViews); var stylesheetsFileSystem = new PhysicalFileSystem(SystemDirectories.Css); var scriptsFileSystem = new PhysicalFileSystem(SystemDirectories.Scripts); - var xsltFileSystem = new PhysicalFileSystem(SystemDirectories.Xslt); var masterPagesFileSystem = new PhysicalFileSystem(SystemDirectories.Masterpages); var mvcViewsFileSystem = new PhysicalFileSystem(SystemDirectories.MvcViews); var javaScriptLibraryFileSystem = new PhysicalFileSystem(SystemDirectories.JavaScriptLibrary); @@ -172,7 +161,6 @@ namespace Umbraco.Core.IO _partialViewsFileSystem = new ShadowWrapper(partialViewsFileSystem, "Views/Partials", () => IsScoped()); _stylesheetsFileSystem = new ShadowWrapper(stylesheetsFileSystem, "css", () => IsScoped()); _scriptsFileSystem = new ShadowWrapper(scriptsFileSystem, "scripts", () => IsScoped()); - _xsltFileSystem = new ShadowWrapper(xsltFileSystem, "xslt", () => IsScoped()); _masterPagesFileSystem = new ShadowWrapper(masterPagesFileSystem, "masterpages", () => IsScoped()); _mvcViewsFileSystem = new ShadowWrapper(mvcViewsFileSystem, "Views", () => IsScoped()); _javascriptLibraryFileSystem = new ShadowWrapper(javaScriptLibraryFileSystem, "Lib", () => IsScoped()); @@ -373,7 +361,6 @@ namespace Umbraco.Core.IO wrappers[i++] = _partialViewsFileSystem; wrappers[i++] = _stylesheetsFileSystem; wrappers[i++] = _scriptsFileSystem; - wrappers[i++] = _xsltFileSystem; wrappers[i++] = _masterPagesFileSystem; wrappers[i] = _mvcViewsFileSystem; diff --git a/src/Umbraco.Core/IO/SystemDirectories.cs b/src/Umbraco.Core/IO/SystemDirectories.cs index 7d3bfd3ae0..37eb1a09b9 100644 --- a/src/Umbraco.Core/IO/SystemDirectories.cs +++ b/src/Umbraco.Core/IO/SystemDirectories.cs @@ -46,8 +46,6 @@ namespace Umbraco.Core.IO public static string WebServices => IOHelper.ReturnPath("umbracoWebservicesPath", Umbraco.EnsureEndsWith("/") + "webservices"); - public static string Xslt => IOHelper.ReturnPath("umbracoXsltPath", "~/xslt"); - //by default the packages folder should exist in the data folder public static string Packages => IOHelper.ReturnPath("umbracoPackagesPath", Data + IOHelper.DirSepChar + "packages"); diff --git a/src/Umbraco.Core/Models/IXsltFile.cs b/src/Umbraco.Core/Models/IXsltFile.cs deleted file mode 100644 index 028b5581c9..0000000000 --- a/src/Umbraco.Core/Models/IXsltFile.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Umbraco.Core.Models -{ - public interface IXsltFile : IFile - { - - } -} diff --git a/src/Umbraco.Core/Models/XsltFile.cs b/src/Umbraco.Core/Models/XsltFile.cs deleted file mode 100644 index a88cd2c127..0000000000 --- a/src/Umbraco.Core/Models/XsltFile.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace Umbraco.Core.Models -{ - /// - /// Represents a XSLT file - /// - [Serializable] - [DataContract(IsReference = true)] - public class XsltFile : File, IXsltFile - { - public XsltFile(string path) - : this(path, (Func) null) - { } - - internal XsltFile(string path, Func getFileContent) - : base(path, getFileContent) - { } - - /// - /// Indicates whether the current entity has an identity, which in this case is a path/name. - /// - /// - /// Overrides the default Entity identity check. - /// - public override bool HasIdentity - { - get { return string.IsNullOrEmpty(Path) == false; } - } - } -} diff --git a/src/Umbraco.Core/Persistence/Repositories/IXsltFileRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IXsltFileRepository.cs deleted file mode 100644 index 2e9e840036..0000000000 --- a/src/Umbraco.Core/Persistence/Repositories/IXsltFileRepository.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.IO; -using Umbraco.Core.Models; - -namespace Umbraco.Core.Persistence.Repositories -{ - public interface IXsltFileRepository : IReadRepository, IWriteRepository - { - bool ValidateXsltFile(XsltFile xsltFile); - Stream GetFileContentStream(string filepath); - void SetFileContent(string filepath, Stream content); - long GetFileSize(string filepath); - } -} diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/XsltFileRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/XsltFileRepository.cs deleted file mode 100644 index 75d92eabf6..0000000000 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/XsltFileRepository.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using LightInject; -using Umbraco.Core.IO; -using Umbraco.Core.Models; - -namespace Umbraco.Core.Persistence.Repositories.Implement -{ - /// - /// Represents the XsltFile Repository - /// - internal class XsltFileRepository : FileRepository, IXsltFileRepository - { - public XsltFileRepository([Inject("XsltFileSystem")] IFileSystem fileSystem) - : base(fileSystem) - { } - - public override XsltFile Get(string id) - { - var path = FileSystem.GetRelativePath(id); - - path = path.EnsureEndsWith(".xslt"); - - if (FileSystem.FileExists(path) == false) - return null; - - var created = FileSystem.GetCreated(path).UtcDateTime; - var updated = FileSystem.GetLastModified(path).UtcDateTime; - - var xsltFile = new XsltFile(path, file => GetFileContent(file.OriginalPath)) - { - Key = path.EncodeAsGuid(), - CreateDate = created, - UpdateDate = updated, - Id = path.GetHashCode(), - VirtualPath = FileSystem.GetUrl(path) - }; - - // reset dirty initial properties (U4-1946) - xsltFile.ResetDirtyProperties(false); - - return xsltFile; - } - - public override void Save(XsltFile entity) - { - base.Save(entity); - - // ensure that from now on, content is lazy-loaded - if (entity.GetFileContent == null) - entity.GetFileContent = file => GetFileContent(file.OriginalPath); - } - - public override IEnumerable GetMany(params string[] ids) - { - ids = ids - .Select(x => StringExtensions.EnsureEndsWith(x, ".xslt")) - .Distinct() - .ToArray(); - - if (ids.Any()) - { - foreach (var id in ids) - { - yield return Get(id); - } - } - else - { - var files = FindAllFiles("", "*.xslt"); - foreach (var file in files) - { - yield return Get(file); - } - } - } - - /// - /// Gets a list of all that exist at the relative path specified. - /// - /// - /// If null or not specified, will return the XSLT files at the root path relative to the IFileSystem - /// - /// - public IEnumerable GetXsltFilesAtPath(string rootPath = null) - { - return FileSystem.GetFiles(rootPath ?? string.Empty, "*.xslt").Select(Get); - } - - private static readonly List ValidExtensions = new List { "xslt" }; - - public bool ValidateXsltFile(XsltFile xsltFile) - { - // get full path - string fullPath; - try - { - // may throw for security reasons - fullPath = FileSystem.GetFullPath(xsltFile.Path); - } - catch - { - return false; - } - - // validate path and extension - var validDir = SystemDirectories.Xslt; - var isValidPath = IOHelper.VerifyEditPath(fullPath, validDir); - var isValidExtension = IOHelper.VerifyFileExtension(xsltFile.Path, ValidExtensions); - return isValidPath && isValidExtension; - } - - public Stream GetFileContentStream(string filepath) - { - if (FileSystem.FileExists(filepath) == false) return null; - - try - { - return FileSystem.OpenFile(filepath); - } - catch - { - return null; // deal with race conds - } - } - - public void SetFileContent(string filepath, Stream content) - { - FileSystem.AddFile(filepath, content, true); - } - } -} diff --git a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs index eeacba2b7c..fbcc9a74cc 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs @@ -52,7 +52,6 @@ namespace Umbraco.Core.Runtime composition.Container.RegisterSingleton(factory => factory.GetInstance().StylesheetsFileSystem, Constants.Composing.FileSystems.StylesheetFileSystem); composition.Container.RegisterSingleton(factory => factory.GetInstance().MasterPagesFileSystem, Constants.Composing.FileSystems.MasterpageFileSystem); composition.Container.RegisterSingleton(factory => factory.GetInstance().MvcViewsFileSystem, Constants.Composing.FileSystems.ViewFileSystem); - composition.Container.RegisterSingleton(factory => factory.GetInstance().XsltFileSystem, Constants.Composing.FileSystems.XsltFileSystem); // register manifest parser, will be injected in collection builders where needed composition.Container.RegisterSingleton(); diff --git a/src/Umbraco.Core/Services/IFileService.cs b/src/Umbraco.Core/Services/IFileService.cs index 91ac7c25ea..1f938c8e27 100644 --- a/src/Umbraco.Core/Services/IFileService.cs +++ b/src/Umbraco.Core/Services/IFileService.cs @@ -18,8 +18,6 @@ namespace Umbraco.Core.Services IPartialView GetPartialView(string path); IPartialView GetPartialViewMacro(string path); IEnumerable GetPartialViewMacros(params string[] names); - IXsltFile GetXsltFile(string path); - IEnumerable GetXsltFiles(params string[] names); Attempt CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0); Attempt CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = 0); bool DeletePartialView(string path, int userId = 0); @@ -305,27 +303,6 @@ namespace Umbraco.Core.Services /// The size of the script file. long GetScriptFileSize(string filepath); - /// - /// Gets the content of a XSLT file as a stream. - /// - /// The filesystem path to the XSLT file. - /// The content of the XSLT file. - Stream GetXsltFileContentStream(string filepath); - - /// - /// Sets the content of a XSLT file. - /// - /// The filesystem path to the XSLT file. - /// The content of the XSLT file. - void SetXsltFileContent(string filepath, Stream content); - - /// - /// Gets the size of a XSLT file. - /// - /// The filesystem path to the XSLT file. - /// The size of the XSLT file. - long GetXsltFileSize(string filepath); - /// /// Gets the content of a macro partial view as a stream. /// diff --git a/src/Umbraco.Core/Services/Implement/FileService.cs b/src/Umbraco.Core/Services/Implement/FileService.cs index 8c1fa53880..09bd096f8e 100644 --- a/src/Umbraco.Core/Services/Implement/FileService.cs +++ b/src/Umbraco.Core/Services/Implement/FileService.cs @@ -24,7 +24,6 @@ namespace Umbraco.Core.Services.Implement private readonly ITemplateRepository _templateRepository; private readonly IPartialViewRepository _partialViewRepository; private readonly IPartialViewMacroRepository _partialViewMacroRepository; - private readonly IXsltFileRepository _xsltRepository; private readonly IAuditRepository _auditRepository; private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoViewPage"; @@ -33,7 +32,7 @@ namespace Umbraco.Core.Services.Implement public FileService(IScopeProvider uowProvider, ILogger logger, IEventMessagesFactory eventMessagesFactory, IStylesheetRepository stylesheetRepository, IScriptRepository scriptRepository, ITemplateRepository templateRepository, IPartialViewRepository partialViewRepository, IPartialViewMacroRepository partialViewMacroRepository, - IXsltFileRepository xsltRepository, IAuditRepository auditRepository) + IAuditRepository auditRepository) : base(uowProvider, logger, eventMessagesFactory) { _stylesheetRepository = stylesheetRepository; @@ -41,7 +40,6 @@ namespace Umbraco.Core.Services.Implement _templateRepository = templateRepository; _partialViewRepository = partialViewRepository; _partialViewMacroRepository = partialViewMacroRepository; - _xsltRepository = xsltRepository; _auditRepository = auditRepository; } @@ -724,22 +722,6 @@ namespace Umbraco.Core.Services.Implement } } - public IXsltFile GetXsltFile(string path) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _xsltRepository.Get(path); - } - } - - public IEnumerable GetXsltFiles(params string[] names) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _xsltRepository.GetMany(names).OrderBy(x => x.Name); - } - } - public Attempt CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0) { return CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId); @@ -1051,36 +1033,7 @@ namespace Umbraco.Core.Services.Implement } #endregion - - #region Xslt - - public Stream GetXsltFileContentStream(string filepath) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _xsltRepository.GetFileContentStream(filepath); - } - } - - public void SetXsltFileContent(string filepath, Stream content) - { - using (var scope = ScopeProvider.CreateScope()) - { - _xsltRepository.SetFileContent(filepath, content); - scope.Complete(); - } - } - - public long GetXsltFileSize(string filepath) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _xsltRepository.GetFileSize(filepath); - } - } - - #endregion - + private void Audit(AuditType type, string message, int userId, int objectId) { _auditRepository.Save(new AuditItem(objectId, message, type, userId)); diff --git a/src/Umbraco.Core/UdiEntityType.cs b/src/Umbraco.Core/UdiEntityType.cs index 34bd26b537..07bde1ba93 100644 --- a/src/Umbraco.Core/UdiEntityType.cs +++ b/src/Umbraco.Core/UdiEntityType.cs @@ -54,8 +54,7 @@ namespace Umbraco.Core { Script, UdiType.StringUdi}, { PartialView, UdiType.StringUdi}, { PartialViewMacro, UdiType.StringUdi}, - { Stylesheet, UdiType.StringUdi}, - { Xslt, UdiType.StringUdi}, + { Stylesheet, UdiType.StringUdi} }; } @@ -108,7 +107,6 @@ namespace Umbraco.Core public const string Stylesheet = "stylesheet"; public const string PartialView = "partial-view"; public const string PartialViewMacro = "partial-view-macro"; - public const string Xslt = "xslt"; public static string FromUmbracoObjectType(UmbracoObjectTypes umbracoObjectType) { diff --git a/src/Umbraco.Core/UdiGetterExtensions.cs b/src/Umbraco.Core/UdiGetterExtensions.cs index 3ba5fe6f65..5a5ccf5574 100644 --- a/src/Umbraco.Core/UdiGetterExtensions.cs +++ b/src/Umbraco.Core/UdiGetterExtensions.cs @@ -206,18 +206,7 @@ namespace Umbraco.Core return new StringUdi(entityType, entity.Path.TrimStart('/')).EnsureClosed(); } - - /// - /// Gets the entity identifier of the entity. - /// - /// The entity. - /// The entity identifier of the entity. - public static StringUdi GetUdi(this IXsltFile entity) - { - if (entity == null) throw new ArgumentNullException("entity"); - return new StringUdi(Constants.UdiEntityType.Xslt, entity.Path.TrimStart('/')).EnsureClosed(); - } - + /// /// Gets the entity identifier of the entity. /// @@ -317,9 +306,6 @@ namespace Umbraco.Core var partialView = entity as IPartialView; if (partialView != null) return partialView.GetUdi(); - var xsltFile = entity as IXsltFile; - if (xsltFile != null) return xsltFile.GetUdi(); - var contentBase = entity as IContentBase; if (contentBase != null) return contentBase.GetUdi(); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index bbb020f308..3f67f820e1 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -686,7 +686,6 @@ - @@ -844,7 +843,6 @@ - @@ -1178,7 +1176,6 @@ - @@ -1213,7 +1210,6 @@ - diff --git a/src/Umbraco.Tests/IO/IoHelperTests.cs b/src/Umbraco.Tests/IO/IoHelperTests.cs index fb3283718e..07436eff1a 100644 --- a/src/Umbraco.Tests/IO/IoHelperTests.cs +++ b/src/Umbraco.Tests/IO/IoHelperTests.cs @@ -47,7 +47,6 @@ namespace Umbraco.Tests.IO Assert.AreEqual(IOHelper.MapPath(SystemDirectories.UmbracoClient, true), IOHelper.MapPath(SystemDirectories.UmbracoClient, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.UserControls, true), IOHelper.MapPath(SystemDirectories.UserControls, false)); Assert.AreEqual(IOHelper.MapPath(SystemDirectories.WebServices, true), IOHelper.MapPath(SystemDirectories.WebServices, false)); - Assert.AreEqual(IOHelper.MapPath(SystemDirectories.Xslt, true), IOHelper.MapPath(SystemDirectories.Xslt, false)); } [Test] diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index b0676f2eb9..91002739d1 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -169,7 +169,7 @@ namespace Umbraco.Tests.TestHelpers var mediaService = GetLazyService(container, c => new MediaService(scopeProvider, mediaFileSystem, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var contentTypeService = GetLazyService(container, c => new ContentTypeService(scopeProvider, logger, eventMessagesFactory, contentService.Value, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var mediaTypeService = GetLazyService(container, c => new MediaTypeService(scopeProvider, logger, eventMessagesFactory, mediaService.Value, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); - var fileService = GetLazyService(container, c => new FileService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); + var fileService = GetLazyService(container, c => new FileService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c), GetRepo(c))); var localizationService = GetLazyService(container, c => new LocalizationService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c), GetRepo(c))); var memberTypeService = GetLazyService(container, c => new MemberTypeService(scopeProvider, logger, eventMessagesFactory, memberService.Value, GetRepo(c), GetRepo(c), GetRepo(c))); diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 451b5c5a32..0fb48f2d93 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -288,10 +288,6 @@ - - - - @@ -412,21 +408,6 @@ - - - - - - - - - - - - - - - @@ -442,7 +423,6 @@ - @@ -559,19 +539,12 @@ - - - - - - - @@ -592,22 +565,6 @@ - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx deleted file mode 100644 index 82708b940e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/editXslt.aspx +++ /dev/null @@ -1,68 +0,0 @@ -<%@ Page Title="Edit XSLT File" MasterPageFile="../../masterpages/umbracoPage.Master" - ValidateRequest="false" Language="c#" CodeBehind="editXslt.aspx.cs" AutoEventWireup="True" - Inherits="umbraco.cms.presentation.developer.editXslt" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" Assembly="Umbraco.Web" %> -<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/getXsltStatus.asmx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/getXsltStatus.asmx deleted file mode 100644 index 7d5385af8f..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/getXsltStatus.asmx +++ /dev/null @@ -1 +0,0 @@ -<%@ WebService Language="c#" Codebehind="getXsltStatus.asmx.cs" Class="umbraco.developer.getXsltStatus" %> diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltChooseExtension.aspx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltChooseExtension.aspx deleted file mode 100644 index dd64a4df9a..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltChooseExtension.aspx +++ /dev/null @@ -1,44 +0,0 @@ -<%@ Page Language="c#" Codebehind="xsltChooseExtension.aspx.cs" MasterPageFile="../../masterpages/umbracoDialog.Master" AutoEventWireup="True" - Inherits="umbraco.developer.xsltChooseExtension" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" Assembly="Umbraco.Web" %> -<%@ Import Namespace="Umbraco.Web" %> - - - - - - - - - - - - - - - - - - - -

    - <%= Services.TextService.Localize("or") %> <%= Services.TextService.Localize("cancel") %> -

    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltInsertValueOf.aspx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltInsertValueOf.aspx deleted file mode 100644 index 809361560b..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltInsertValueOf.aspx +++ /dev/null @@ -1,62 +0,0 @@ -<%@ Page Language="c#" MasterPageFile="../../masterpages/umbracoDialog.Master" Codebehind="xsltInsertValueOf.aspx.cs" AutoEventWireup="True" Inherits="umbraco.developer.xsltInsertValueOf" %> -<%@ Import Namespace="Umbraco.Web" %> -<%@ Register TagPrefix="umb" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %> -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" Assembly="Umbraco.Web" %> - - - - - - - - - - - - - - - - - - - - - - -

    - <%= Services.TextService.Localize("or") %> <%= Services.TextService.Localize("cancel") %> -

    -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltVisualize.aspx b/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltVisualize.aspx deleted file mode 100644 index 752edf16c2..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/Xslt/xsltVisualize.aspx +++ /dev/null @@ -1,70 +0,0 @@ -<%@ Page Language="C#" MasterPageFile="../../masterpages/umbracoDialog.Master" AutoEventWireup="true" - CodeBehind="xsltVisualize.aspx.cs" ValidateRequest="false" Inherits="umbraco.presentation.umbraco.developer.Xslt.xsltVisualize" %> - -<%@ Register TagPrefix="cc1" Namespace="Umbraco.Web._Legacy.Controls" Assembly="Umbraco.Web" %> -<%@ Register TagPrefix="cc2" Namespace="umbraco.controls" Assembly="Umbraco.Web" %> - - - - - - - - -
    - - - - - - -
    -
    -
    - - - - - - - -
    - - - - - - - - - - -
    -
    diff --git a/src/Umbraco.Web.UI/umbraco/developer/autoDoc.aspx b/src/Umbraco.Web.UI/umbraco/developer/autoDoc.aspx deleted file mode 100644 index 5fb02ef834..0000000000 --- a/src/Umbraco.Web.UI/umbraco/developer/autoDoc.aspx +++ /dev/null @@ -1,23 +0,0 @@ -<%@ Page language="c#" Codebehind="autoDoc.aspx.cs" AutoEventWireup="True" Inherits="umbraco.developer.autoDoc" %> - - - - autoDoc - - - - - - - -
    - -
    - - diff --git a/src/Umbraco.Web.UI/umbraco/xslt/Web.config b/src/Umbraco.Web.UI/umbraco/xslt/Web.config deleted file mode 100644 index fd6e3a816a..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/Web.config +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/xslt/macroGetCurrent.xsl b/src/Umbraco.Web.UI/umbraco/xslt/macroGetCurrent.xsl deleted file mode 100644 index da4854f40a..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/macroGetCurrent.xsl +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/xslt/macroGetSubs.xsl b/src/Umbraco.Web.UI/umbraco/xslt/macroGetSubs.xsl deleted file mode 100644 index 33ccc65125..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/macroGetSubs.xsl +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/xslt/searchResult.xslt b/src/Umbraco.Web.UI/umbraco/xslt/searchResult.xslt deleted file mode 100644 index 17809f223b..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/searchResult.xslt +++ /dev/null @@ -1,32 +0,0 @@ - - - - - -
      - -
    1. -

      - - - - - - - - - - Node Type: -

      -

      - Last updated on - -

      -
    2. - -
      -
    -
    -
    diff --git a/src/Umbraco.Web.UI/umbraco/xslt/sqlNodeHierachy.xslt b/src/Umbraco.Web.UI/umbraco/xslt/sqlNodeHierachy.xslt deleted file mode 100644 index db6001e784..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/sqlNodeHierachy.xslt +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - -<!DOCTYPE umbraco [ - <!ELEMENT nodes ANY> - <!ELEMENT node ANY> - <!ATTLIST node id ID #REQUIRED> -]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Breadcrumb.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Breadcrumb.xslt deleted file mode 100644 index ef870ffa0c..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Breadcrumb.xslt +++ /dev/null @@ -1,34 +0,0 @@ - -]> - - - - - - - - - - - -
      - -
    • - - - -
    • -
      - -
    • - -
    • -
    -
    -
    -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Clean.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Clean.xslt deleted file mode 100644 index ece30c8f4e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Clean.xslt +++ /dev/null @@ -1,21 +0,0 @@ - - ]> - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesAsThumbnails.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesAsThumbnails.xslt deleted file mode 100644 index 4d451b23c8..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesAsThumbnails.xslt +++ /dev/null @@ -1,33 +0,0 @@ - - ]> - - - - - - - - - - -
    - - - - -
    -
    -
    -
    - Photo(s) -
    -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDateAndLimit.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDateAndLimit.xslt deleted file mode 100644 index 9fffeabb8c..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDateAndLimit.xslt +++ /dev/null @@ -1,36 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDocumentType.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDocumentType.xslt deleted file mode 100644 index d3a24e854c..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByDocumentType.xslt +++ /dev/null @@ -1,32 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByLevel.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByLevel.xslt deleted file mode 100644 index a591f1644e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesByLevel.xslt +++ /dev/null @@ -1,32 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromAChangableSource.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromAChangableSource.xslt deleted file mode 100644 index f2186853fc..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromAChangableSource.xslt +++ /dev/null @@ -1,33 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromCurrentPage.xslt deleted file mode 100644 index cb0ec8c25e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListSubPagesFromCurrentPage.xslt +++ /dev/null @@ -1,29 +0,0 @@ - - ]> - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListThumbnailsFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListThumbnailsFromCurrentPage.xslt deleted file mode 100644 index 265678ee86..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListThumbnailsFromCurrentPage.xslt +++ /dev/null @@ -1,31 +0,0 @@ - - ]> - - - - - - - - - - - -
    - - - -
    -
    -
    -
    -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListWholeStructureFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/ListWholeStructureFromCurrentPage.xslt deleted file mode 100644 index 0edf12a302..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/ListWholeStructureFromCurrentPage.xslt +++ /dev/null @@ -1,30 +0,0 @@ - - ]> - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/NavigationPrototype.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/NavigationPrototype.xslt deleted file mode 100644 index 7ded577dea..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/NavigationPrototype.xslt +++ /dev/null @@ -1,40 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/RSSFeed.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/RSSFeed.xslt deleted file mode 100644 index 3043f44a68..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/RSSFeed.xslt +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <?xml version="1.0" encoding="UTF-8"?> - - - - - <xsl:value-of select="$RSSTitle"/> - - - - - - - - umbraco - - - - en - - - - - - - - - - - - - - <xsl:value-of select="@nodeName"/> - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/RelatedLinks.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/RelatedLinks.xslt deleted file mode 100644 index 92df3bb6ea..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/RelatedLinks.xslt +++ /dev/null @@ -1,51 +0,0 @@ - -]> - - - - - - - - - - - - - -
      - -
    • - - - _blank - - - - - - - - - - - - - - - -
    • -
      -
    - - - - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Breadcrumb.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Breadcrumb.xslt deleted file mode 100644 index ef8f2bdfdd..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Breadcrumb.xslt +++ /dev/null @@ -1,34 +0,0 @@ - -]> - - - - - - - - - - - -
      - -
    • - - - -
    • -
      - -
    • - -
    • -
    -
    -
    -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Clean.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Clean.xslt deleted file mode 100644 index ece30c8f4e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Clean.xslt +++ /dev/null @@ -1,21 +0,0 @@ - - ]> - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesAsThumbnails.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesAsThumbnails.xslt deleted file mode 100644 index b0d0890ad4..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesAsThumbnails.xslt +++ /dev/null @@ -1,33 +0,0 @@ - - ]> - - - - - - - - - - -
    - - - - -
    -
    -
    -
    - Photo(s) -
    -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDateAndLimit.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDateAndLimit.xslt deleted file mode 100644 index 289c42f61e..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDateAndLimit.xslt +++ /dev/null @@ -1,36 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDocumentType.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDocumentType.xslt deleted file mode 100644 index 4636b25885..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByDocumentType.xslt +++ /dev/null @@ -1,32 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByLevel.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByLevel.xslt deleted file mode 100644 index 96055df141..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesByLevel.xslt +++ /dev/null @@ -1,32 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromAChangableSource.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromAChangableSource.xslt deleted file mode 100644 index de1d1693ed..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromAChangableSource.xslt +++ /dev/null @@ -1,33 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromCurrentPage.xslt deleted file mode 100644 index d97c92b960..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListSubPagesFromCurrentPage.xslt +++ /dev/null @@ -1,29 +0,0 @@ - - ]> - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListThumbnailsFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListThumbnailsFromCurrentPage.xslt deleted file mode 100644 index 1c645dea3b..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListThumbnailsFromCurrentPage.xslt +++ /dev/null @@ -1,31 +0,0 @@ - - ]> - - - - - - - - - - - -
    - - - -
    -
    -
    -
    -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListWholeStructureFromCurrentPage.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListWholeStructureFromCurrentPage.xslt deleted file mode 100644 index 2cd59aa663..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/ListWholeStructureFromCurrentPage.xslt +++ /dev/null @@ -1,30 +0,0 @@ - - ]> - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/NavigationPrototype.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/NavigationPrototype.xslt deleted file mode 100644 index 7ff5d40bde..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/NavigationPrototype.xslt +++ /dev/null @@ -1,40 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RSSFeed.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RSSFeed.xslt deleted file mode 100644 index d068eb4cd5..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RSSFeed.xslt +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <?xml version="1.0" encoding="UTF-8"?> - - - - - <xsl:value-of select="$RSSTitle"/> - - - - - - - - umbraco - - - - en - - - - - - - - - - - - - - <xsl:value-of select="@nodeName"/> - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RelatedLinks.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RelatedLinks.xslt deleted file mode 100644 index cbf781b1df..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/RelatedLinks.xslt +++ /dev/null @@ -1,51 +0,0 @@ - -]> - - - - - - - - - - - - - -
      - -
    • - - - _blank - - - - - - - - - - - - - - - -
    • -
      -
    - - - - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Sitemap.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Sitemap.xslt deleted file mode 100644 index 980ac7380f..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/Sitemap.xslt +++ /dev/null @@ -1,42 +0,0 @@ - - ]> - - - - - - - - - - -
    - - - -
    -
    - - - - -
      -
    • - - - - - - - -
    • -
      -
    -
    -
    -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/TablePrototype.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/TablePrototype.xslt deleted file mode 100644 index 1307e75260..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Schema2/TablePrototype.xslt +++ /dev/null @@ -1,54 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - - - - - - - - background-color: - - - background-color: - - - - - - - -
    NameCreate DateCustom Property
    - - - - - - -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/Sitemap.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/Sitemap.xslt deleted file mode 100644 index e212aaa4a7..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/Sitemap.xslt +++ /dev/null @@ -1,42 +0,0 @@ - - ]> - - - - - - - - - - -
    - - - -
    -
    - - - - -
      -
    • - - - - - - - -
    • -
      -
    -
    -
    -
    \ No newline at end of file diff --git a/src/Umbraco.Web.UI/umbraco/xslt/templates/TablePrototype.xslt b/src/Umbraco.Web.UI/umbraco/xslt/templates/TablePrototype.xslt deleted file mode 100644 index 0d9471335b..0000000000 --- a/src/Umbraco.Web.UI/umbraco/xslt/templates/TablePrototype.xslt +++ /dev/null @@ -1,54 +0,0 @@ - - ]> - - - - - - - - - - - - - - - - - - - - - - - - - background-color: - - - background-color: - - - - - - - -
    NameCreate DateCustom Property
    - - - - - - -
    - -
    - -
    \ No newline at end of file diff --git a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs index 257e0c9731..f44781886d 100644 --- a/src/Umbraco.Web/Cache/ContentCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/ContentCacheRefresher.cs @@ -80,8 +80,7 @@ namespace Umbraco.Web.Cache // when a public version changes Current.ApplicationCache.ClearPartialViewCache(); MacroCacheRefresher.ClearMacroContentCache(CacheHelper); // just the content - ClearXsltCache(); - + Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.IdToKeyCacheKey); Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.KeyToIdCacheKey); } @@ -145,7 +144,6 @@ namespace Umbraco.Web.Cache cacheHelper.ClearPartialViewCache(); MacroCacheRefresher.ClearMacroContentCache(cacheHelper); // just the content - ClearXsltCache(); cacheHelper.IsolatedRuntimeCache.ClearCache(); cacheHelper.IsolatedRuntimeCache.ClearCache(); @@ -153,15 +151,5 @@ namespace Umbraco.Web.Cache #endregion - #region Helpers - - private static void ClearXsltCache() - { - // todo: document where this is coming from - if (UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration <= 0) return; - Current.ApplicationCache.ClearCacheObjectTypes("MS.Internal.Xml.XPath.XPathSelectionIterator"); - } - - #endregion } } diff --git a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs index 8d1a65f296..d7fd338965 100644 --- a/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/DataTypeCacheRefresher.cs @@ -53,9 +53,6 @@ namespace Umbraco.Web.Cache foreach (var payload in payloads) { - if (dataTypeCache) - dataTypeCache.Result.ClearCacheByKeySearch(CacheKeys.DataTypePreValuesCacheKey + "_" + payload.Id); - _idkMap.ClearCache(payload.Id); } diff --git a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs index 402151fdb9..c7157bf9dc 100644 --- a/src/Umbraco.Web/Cache/MacroCacheRefresher.cs +++ b/src/Umbraco.Web/Cache/MacroCacheRefresher.cs @@ -105,11 +105,6 @@ namespace Umbraco.Web.Cache { CacheKeys.MacroCacheKey, // umbraco.cms.businesslogic.macro.Macro objects cache CacheKeys.MacroContentCacheKey, // macro render cache - //CacheKeys.MacroControlCacheKey, - //CacheKeys.MacroHtmlCacheKey, - //CacheKeys.MacroHtmlDateAddedCacheKey, - //CacheKeys.MacroControlDateAddedCacheKey, - CacheKeys.MacroXsltCacheKey, // XsltMacroEngine transforms cache }; } diff --git a/src/Umbraco.Web/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs b/src/Umbraco.Web/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs index 86cef17b4c..b69e5edece 100644 --- a/src/Umbraco.Web/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs +++ b/src/Umbraco.Web/HealthCheck/Checks/Permissions/FolderAndFilePermissionsCheck.cs @@ -71,8 +71,7 @@ namespace Umbraco.Web.HealthCheck.Checks.Permissions { SystemDirectories.Umbraco, PermissionCheckRequirement.Optional }, { SystemDirectories.UmbracoClient, PermissionCheckRequirement.Optional }, { SystemDirectories.UserControls, PermissionCheckRequirement.Optional }, - { SystemDirectories.MvcViews, PermissionCheckRequirement.Optional }, - { SystemDirectories.Xslt, PermissionCheckRequirement.Optional }, + { SystemDirectories.MvcViews, PermissionCheckRequirement.Optional } }; //These are special paths to check that will restart an app domain if a file is written to them, diff --git a/src/Umbraco.Web/Install/FilePermissionHelper.cs b/src/Umbraco.Web/Install/FilePermissionHelper.cs index b9252c9e65..c58c2fd4fd 100644 --- a/src/Umbraco.Web/Install/FilePermissionHelper.cs +++ b/src/Umbraco.Web/Install/FilePermissionHelper.cs @@ -12,7 +12,7 @@ namespace Umbraco.Web.Install internal class FilePermissionHelper { // ensure that these directories exist and Umbraco can write to them - private static readonly string[] PermissionDirs = { SystemDirectories.Css, SystemDirectories.Config, SystemDirectories.Data, SystemDirectories.Media, SystemDirectories.Masterpages, SystemDirectories.Xslt, SystemDirectories.UserControls, SystemDirectories.Preview }; + private static readonly string[] PermissionDirs = { SystemDirectories.Css, SystemDirectories.Config, SystemDirectories.Data, SystemDirectories.Media, SystemDirectories.Masterpages, SystemDirectories.UserControls, SystemDirectories.Preview }; private static readonly string[] PackagesPermissionsDirs = { SystemDirectories.Bin, SystemDirectories.Umbraco, SystemDirectories.UserControls, SystemDirectories.Packages }; // ensure Umbraco can write to these files (the directories must exist) From 310a31b03e235ec33f43dc8f9913f910ae25ffec Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 01:01:24 +1000 Subject: [PATCH 51/58] More xslt removal and other file cleanup --- .../UmbracoSettings/DeveloperElement.cs | 47 --- .../UmbracoSettings/IDeveloperSection.cs | 9 - .../IUmbracoSettingsSection.cs | 5 +- .../UmbracoSettings/UmbracoSettingsSection.cs | 14 +- src/Umbraco.Core/Models/Macro.cs | 2 - src/Umbraco.Core/Umbraco.Core.csproj | 2 - .../DeveloperElementDefaultTests.cs | 13 - .../UmbracoSettings/DeveloperElementTests.cs | 17 -- .../TestHelpers/SettingsForTests.cs | 2 - src/Umbraco.Tests/Umbraco.Tests.csproj | 2 - src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 21 -- src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml | 10 +- src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml | 10 +- .../Umbraco/config/lang/zh_tw.xml | 8 - .../config/umbracoSettings.config | 9 - src/Umbraco.Web.UI/umbraco/config/lang/da.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/de.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/en.xml | 8 - .../umbraco/config/lang/en_us.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/es.xml | 11 - src/Umbraco.Web.UI/umbraco/config/lang/fr.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/he.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/it.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/ja.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/ko.xml | 10 +- src/Umbraco.Web.UI/umbraco/config/lang/nl.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/pl.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/pt.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/ru.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/sv.xml | 10 +- src/Umbraco.Web.UI/umbraco/config/lang/tr.xml | 8 - src/Umbraco.Web.UI/umbraco/config/lang/zh.xml | 8 - .../developer/Packages/editPackage.aspx | 2 +- .../umbraco/dialogs/search.aspx | 48 --- .../settings/modals/ShowUmbracoTags.aspx | 60 ---- .../umbraco/settings/scripts/editScript.aspx | 60 ---- .../settings/stylesheet/editstylesheet.aspx | 54 ---- .../stylesheet/editstylesheet.aspx.cs | 11 - .../editstylesheet.aspx.designer.cs | 15 - .../property/EditStyleSheetProperty.aspx | 67 ----- .../property/EditStyleSheetProperty.aspx.cs | 11 - .../EditStyleSheetProperty.aspx.designer.cs | 15 - .../umbraco/settings/views/EditView.aspx | 89 ------ .../umbraco/settings/views/EditView.aspx.cs | 281 ------------------ .../settings/views/EditView.aspx.designer.cs | 132 -------- .../umbraco_client/CodeArea/UmbracoEditor.js | 163 ---------- .../umbraco_client/CodeArea/javascript.js | 191 ------------ .../umbraco_client/CodeArea/styles.css | 8 - src/Umbraco.Web/Umbraco.Web.csproj | 18 -- src/Umbraco.Web/_Legacy/Controls/CodeArea.cs | 243 --------------- .../umbraco/dialogs/search.aspx | 48 --- .../umbraco/dialogs/search.aspx.cs | 119 -------- .../umbraco/dialogs/search.aspx.designer.cs | 60 ---- .../settings/modals/ShowUmbracoTags.aspx.cs | 33 -- .../stylesheet/editstylesheet.aspx.cs | 151 ---------- .../property/EditStyleSheetProperty.aspx.cs | 159 ---------- 56 files changed, 7 insertions(+), 2345 deletions(-) delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/DeveloperElement.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/IDeveloperSection.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementDefaultTests.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementTests.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/dialogs/search.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/modals/ShowUmbracoTags.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/scripts/editScript.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/editstylesheet.aspx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/settings/views/EditView.aspx.designer.cs delete mode 100644 src/Umbraco.Web.UI/umbraco_client/CodeArea/UmbracoEditor.js delete mode 100644 src/Umbraco.Web.UI/umbraco_client/CodeArea/javascript.js delete mode 100644 src/Umbraco.Web.UI/umbraco_client/CodeArea/styles.css delete mode 100644 src/Umbraco.Web/_Legacy/Controls/CodeArea.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/search.aspx delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/search.aspx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/search.aspx.designer.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/settings/modals/ShowUmbracoTags.aspx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/editstylesheet.aspx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/DeveloperElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/DeveloperElement.cs deleted file mode 100644 index 66531a1ab1..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/DeveloperElement.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class DeveloperElement : ConfigurationElement, IDeveloperSection - { - private AppCodeFileExtensionsElement _default; - - [ConfigurationProperty("appCodeFileExtensions")] - internal AppCodeFileExtensionsElement AppCodeFileExtensions - { - get - { - if (_default != null) - { - return _default; - } - - //here we need to check if this element is defined, if it is not then we'll setup the defaults - var prop = Properties["appCodeFileExtensions"]; - var autoFill = this[prop] as ConfigurationElement; - if (autoFill != null && autoFill.ElementInformation.IsPresent == false) - { - var collection = new AppCodeFileExtensionsCollection - { - new FileExtensionElement {RawValue = "cs"}, - new FileExtensionElement {RawValue = "vb"} - }; - _default = new AppCodeFileExtensionsElement - { - AppCodeFileExtensionsCollection = collection - }; - - return _default; - } - - return (AppCodeFileExtensionsElement)base["appCodeFileExtensions"]; - } - } - - IEnumerable IDeveloperSection.AppCodeFileExtensions - { - get { return AppCodeFileExtensions.AppCodeFileExtensionsCollection; } - } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IDeveloperSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IDeveloperSection.cs deleted file mode 100644 index 40aa6af0db..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IDeveloperSection.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IDeveloperSection : IUmbracoConfigurationSection - { - IEnumerable AppCodeFileExtensions { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs index 6bbfea49da..1776f1cbf2 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs @@ -14,10 +14,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings IRequestHandlerSection RequestHandler { get; } ITemplatesSection Templates { get; } - - IDeveloperSection Developer { get; } - - + ILoggingSection Logging { get; } IScheduledTasksSection ScheduledTasks { get; } diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs index f972c2c7b3..3b76a43c39 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs @@ -37,14 +37,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings { get { return (TemplatesElement)this["templates"]; } } - - [ConfigurationProperty("developer")] - internal DeveloperElement Developer - { - get { return (DeveloperElement)this["developer"]; } - } - - + [ConfigurationProperty("logging")] internal LoggingElement Logging { @@ -101,11 +94,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings get { return BackOffice; } } - IDeveloperSection IUmbracoSettingsSection.Developer - { - get { return Developer; } - } - ILoggingSection IUmbracoSettingsSection.Logging { get { return Logging; } diff --git a/src/Umbraco.Core/Models/Macro.cs b/src/Umbraco.Core/Models/Macro.cs index 6e72942b6e..a24d659ce3 100644 --- a/src/Umbraco.Core/Models/Macro.cs +++ b/src/Umbraco.Core/Models/Macro.cs @@ -96,9 +96,7 @@ namespace Umbraco.Core.Models private bool _cacheByMember; private bool _dontRender; private string _scriptFile; - private string _scriptAssembly; private string _scriptPath; - private string _xslt; private MacroPropertyCollection _properties; private List _addedProperties; private List _removedProperties; diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 3f67f820e1..448acce472 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -250,7 +250,6 @@ - @@ -259,7 +258,6 @@ - diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementDefaultTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementDefaultTests.cs deleted file mode 100644 index a3f8b79aa1..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementDefaultTests.cs +++ /dev/null @@ -1,13 +0,0 @@ -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class DeveloperElementDefaultTests : DeveloperElementTests - { - protected override bool TestingDefaults - { - get { return true; } - } - } -} diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementTests.cs deleted file mode 100644 index aa79ffd965..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/DeveloperElementTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Linq; -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class DeveloperElementTests : UmbracoSettingsTests - { - [Test] - public void AppCodeFileExtensions() - { - Assert.IsTrue(SettingsSection.Developer.AppCodeFileExtensions.Count() == 2); - Assert.IsTrue(SettingsSection.Developer.AppCodeFileExtensions.All( - x => "cs,vb".Split(',').Contains(x.Extension))); - } - } -} diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index f3b7eee50a..34c6a35833 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -56,7 +56,6 @@ namespace Umbraco.Tests.TestHelpers var security = new Mock(); var requestHandler = new Mock(); var templates = new Mock(); - var dev = new Mock(); var logging = new Mock(); var tasks = new Mock(); var distCall = new Mock(); @@ -67,7 +66,6 @@ namespace Umbraco.Tests.TestHelpers 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.Developer).Returns(dev.Object); settings.Setup(x => x.Logging).Returns(logging.Object); settings.Setup(x => x.ScheduledTasks).Returns(tasks.Object); settings.Setup(x => x.DistributedCall).Returns(distCall.Object); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 3eb6d8ae73..d39608c49c 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -282,8 +282,6 @@ - - diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 0fb48f2d93..20f75c30d4 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -228,20 +228,6 @@ umbracoPage.Master - - editstylesheet.aspx - ASPXCodeBehind - - - editstylesheet.aspx - - - EditStyleSheetProperty.aspx - ASPXCodeBehind - - - EditStyleSheetProperty.aspx - treeInit.aspx ASPXCodeBehind @@ -411,7 +397,6 @@ - @@ -425,7 +410,6 @@ - @@ -552,9 +536,6 @@ Form - - - @@ -565,8 +546,6 @@ - - diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml index d8c9f8570f..f9d7fc616e 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/cs.xml @@ -321,8 +321,6 @@ Žádne aktivní styly nejsou dostupné Umístěte, prosím, kurzor nalevo od těch dvou buňek, které chcete sloučit Nemužete rozdělit buňku, která nebyla sloučená. - Chyba ve zdroji XSLT - Soubor XSLT nebyl uložen, protože obsahoval chyby V nastavení datového typu použitého pro tuto vlastnost je chyba, zkontrolujte, prosím, datový typ @@ -817,11 +815,6 @@ Ujistěte se, prosím, že nemáte 2 šablony se stejným aliasem Šablona byla uložena Šablona byla uložena bez chyb! - XSLT nebyl uložen - XSLT obsahoval chybu - XSLT nemohl být uložen, zkontrolujte oprávnění k souboru - XSLT byl uložen - V XSLT nejsou žádné chyby Publikování obsahu bylo zrušeno Částečný pohled byl uložen Částečný pohled byl uložen bez chyb! @@ -990,7 +983,6 @@ Skripty Stylopisy Šablony - XSLT soubory Oprávnění Uživatele Typy Uživatelů Uživatelé @@ -1041,4 +1033,4 @@ Vaše nedávná historie Relace vyprší za - \ No newline at end of file + diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml index dee52cff5c..e3b58903d1 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/nb.xml @@ -337,8 +337,6 @@ Det er ingen aktive stiler eller formateringer på denne siden Sett markøren til venstre i de 2 cellene du ønsker å slå sammen Du kan ikke dele en celle som allerede er delt. - Feil i XSLT kode - XSLT ble ikke lagret på grunn av feil i koden Det er et problem dem datatypen som brukes til denne egenskapen. Kontroller innstillingene og prøv igjen. @@ -795,11 +793,6 @@ Vennlig hilsen Umbraco roboten Vennligst forviss deg om at du ikke har to maler med samme alias Malen ble lagret Malen ble lagret uten feil! - XSLT-koden ble ikke lagret - XSLT-koden inneholdt en feil - XSLT-koden ble ikke lagret, sjekk filrettigheter - XSLT lagret - Ingen feil i XSLT! Innhold avpublisert Delmal lagret Delmal lagret uten feil @@ -974,7 +967,6 @@ Vennlig hilsen Umbraco roboten Skript Stiler Maler - XSLT Filer Analytics Brukertillatelser Brukertyper typer @@ -1028,4 +1020,4 @@ Vennlig hilsen Umbraco roboten Din historikk Sesjonen utløper om - \ No newline at end of file + 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 c362f91df0..37c3dec60e 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/zh_tw.xml @@ -388,8 +388,6 @@ 沒有可用的樣式 請把游標放在您要合併的兩個儲存格中的左邊儲存格 非合併儲存格不能分離。 - XSLT源碼出錯 - XSLT未保存,因為包含錯誤。 這是此屬性所使用的資料類別設定錯誤,請檢查資料類別 @@ -957,11 +955,6 @@ 範本別名相同 範本已保存 範本保存,無錯誤。 - XSLT未保存 - XSLT有錯誤 - XSLT無法保存,請檢查許可權。 - XSLT已保存 - XSLT無錯誤 內容已取消發佈 片段視圖已保存 片段視圖保存,無錯誤。 @@ -1184,7 +1177,6 @@ 腳本 樣式表 範本 - XSLT文件 統計 diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.config b/src/Umbraco.Web.UI/config/umbracoSettings.config index 84b610b4af..fc7bcad135 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.config @@ -173,15 +173,6 @@ Mvc - - - - - cs - vb - - - ", ee); - } - } - /// /// Renders a template. /// @@ -791,37 +763,20 @@ namespace umbraco /// The rendered template as a string public static string RenderTemplate(int PageId, int TemplateId) { - if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) - { - using (var sw = new StringWriter()) - { - try - { - var altTemplate = TemplateId == -1 ? null : (int?)TemplateId; - var templateRenderer = new TemplateRenderer(Umbraco.Web.UmbracoContext.Current, PageId, altTemplate); - templateRenderer.Render(sw); - } - catch (Exception ee) - { - sw.Write("", PageId, ee); - } - - return sw.ToString(); - } - } - else - { - var p = new page(GetSafeContentCache().GetById(PageId)); - p.RenderPage(TemplateId); - var c = p.PageContentControl; - - using (var sw = new StringWriter()) - using(var hw = new HtmlTextWriter(sw)) - { - c.RenderControl(hw); - return sw.ToString(); - } - + using (var sw = new StringWriter()) + { + try + { + var altTemplate = TemplateId == -1 ? null : (int?)TemplateId; + var templateRenderer = new TemplateRenderer(Umbraco.Web.UmbracoContext.Current, PageId, altTemplate); + templateRenderer.Render(sw); + } + catch (Exception ee) + { + sw.Write("", PageId, ee); + } + + return sw.ToString(); } } diff --git a/src/Umbraco.Web/umbraco.presentation/page.cs b/src/Umbraco.Web/umbraco.presentation/page.cs index 89ac52949f..8fe05370ce 100644 --- a/src/Umbraco.Web/umbraco.presentation/page.cs +++ b/src/Umbraco.Web/umbraco.presentation/page.cs @@ -149,7 +149,7 @@ namespace umbraco void populatePageData(XmlNode node) { - String s; + string s; DateTime dt; Guid guid; int i; @@ -255,21 +255,6 @@ namespace umbraco #endregion - #region Wtf? - - public void RenderPage(int templateId) - { - if (templateId != 0) - { - template templateDesign = new template(templateId); - - _pageContentControl = templateDesign.ParseWithControls(this); - _pageContent.Append(templateDesign.TemplateContent); - } - } - - #endregion - #region Public properties public Control PageContentControl diff --git a/src/Umbraco.Web/umbraco.presentation/template.cs b/src/Umbraco.Web/umbraco.presentation/template.cs index 98747b9ad7..8fad4c8b55 100644 --- a/src/Umbraco.Web/umbraco.presentation/template.cs +++ b/src/Umbraco.Web/umbraco.presentation/template.cs @@ -35,7 +35,7 @@ namespace umbraco #endregion #region public properties - public String TemplateContent + public string TemplateContent { set { @@ -118,103 +118,6 @@ namespace umbraco return this._templateName; } - public Control ParseWithControls(page umbPage) - { - System.Web.HttpContext.Current.Trace.Write("umbracoTemplate", "Start parsing"); - - if (System.Web.HttpContext.Current.Items["macrosAdded"] == null) - System.Web.HttpContext.Current.Items.Add("macrosAdded", 0); - - StringBuilder tempOutput = _templateOutput; - - Control pageLayout = new Control(); - Control pageHeader = new Control(); - Control pageFooter = new Control(); - Control pageContent = new Control(); - System.Web.UI.HtmlControls.HtmlForm pageForm = new System.Web.UI.HtmlControls.HtmlForm(); - System.Web.UI.HtmlControls.HtmlHead pageAspNetHead = new System.Web.UI.HtmlControls.HtmlHead(); - - // Find header and footer of page if there is an aspnet-form on page - if (_templateOutput.ToString().ToLower().IndexOf("") > 0 || - _templateOutput.ToString().ToLower().IndexOf("") > 0) - { - pageForm.Attributes.Add("method", "post"); - pageForm.Attributes.Add("action", Convert.ToString(System.Web.HttpContext.Current.Items["VirtualUrl"])); - - // Find header and footer from tempOutput - int aspnetFormTagBegin = tempOutput.ToString().ToLower().IndexOf(""); - int aspnetFormTagLength = 14; - int aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf("") + 15; - - // check if we should disable the script manager - if (aspnetFormTagBegin == -1) - { - aspnetFormTagBegin = - _templateOutput.ToString().ToLower().IndexOf(""); - aspnetFormTagLength = 42; - } - else - { - ScriptManager sm = new ScriptManager(); - sm.ID = "umbracoScriptManager"; - pageForm.Controls.Add(sm); - } - - - StringBuilder header = new StringBuilder(tempOutput.ToString().Substring(0, aspnetFormTagBegin)); - - // Check if there's an asp.net head element in the header - if (header.ToString().ToLower().Contains("")) - { - StringBuilder beforeHeader = new StringBuilder(header.ToString().Substring(0, header.ToString().ToLower().IndexOf(""))); - header.Remove(0, header.ToString().ToLower().IndexOf("") + 14); - StringBuilder afterHeader = new StringBuilder(header.ToString().Substring(header.ToString().ToLower().IndexOf("") + 15, header.Length - header.ToString().ToLower().IndexOf("") - 15)); - header.Remove(header.ToString().ToLower().IndexOf(""), header.Length - header.ToString().ToLower().IndexOf("")); - - // Find the title from head - MatchCollection matches = Regex.Matches(header.ToString(), @"(.*?)", RegexOptions.IgnoreCase | RegexOptions.Multiline); - if (matches.Count > 0) - { - StringBuilder titleText = new StringBuilder(); - HtmlTextWriter titleTextTw = new HtmlTextWriter(new System.IO.StringWriter(titleText)); - parseStringBuilder(new StringBuilder(matches[0].Groups[1].Value), umbPage).RenderControl(titleTextTw); - pageAspNetHead.Title = titleText.ToString(); - header = new StringBuilder(header.ToString().Replace(matches[0].Value, "")); - } - - pageAspNetHead.Controls.Add(parseStringBuilder(header, umbPage)); - pageAspNetHead.ID = "head1"; - - // build the whole header part - pageHeader.Controls.Add(parseStringBuilder(beforeHeader, umbPage)); - pageHeader.Controls.Add(pageAspNetHead); - pageHeader.Controls.Add(parseStringBuilder(afterHeader, umbPage)); - - } - else - pageHeader.Controls.Add(parseStringBuilder(header, umbPage)); - - - pageFooter.Controls.Add(parseStringBuilder(new StringBuilder(tempOutput.ToString().Substring(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd)), umbPage)); - tempOutput.Remove(0, aspnetFormTagBegin + aspnetFormTagLength); - aspnetFormTagEnd = tempOutput.ToString().ToLower().IndexOf(""); - tempOutput.Remove(aspnetFormTagEnd, tempOutput.Length - aspnetFormTagEnd); - - - //throw new ArgumentException(tempOutput.ToString()); - pageForm.Controls.Add(parseStringBuilder(tempOutput, umbPage)); - - pageContent.Controls.Add(pageHeader); - pageContent.Controls.Add(pageForm); - pageContent.Controls.Add(pageFooter); - return pageContent; - - } - else - return parseStringBuilder(tempOutput, umbPage); - - } - public Control parseStringBuilder(StringBuilder tempOutput, page umbPage) { @@ -229,18 +132,18 @@ namespace umbraco int tagIndex = tempOutput.ToString().ToLower().IndexOf(" -1) { - String tempElementContent = ""; + string tempElementContent = ""; pageContent.Controls.Add(new LiteralControl(tempOutput.ToString().Substring(0, tagIndex))); tempOutput.Remove(0, tagIndex); - String tag = tempOutput.ToString().Substring(0, tempOutput.ToString().IndexOf(">") + 1); + string tag = tempOutput.ToString().Substring(0, tempOutput.ToString().IndexOf(">") + 1); Hashtable attributes = new Hashtable(XmlHelper.GetAttributesFromElement(tag)); // Check whether it's a single tag () or a tag with children (...) if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1) { - String closingTag = ""; + string closingTag = ""; // Tag with children are only used when a macro is inserted by the umbraco-editor, in the // following format: "", so we // need to delete extra information inserted which is the image-tag and the closing @@ -261,41 +164,14 @@ namespace umbraco if (debugMode) pageContent.Controls.Add(new LiteralControl("
    ")); - // NH: Switching to custom controls for macros - if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) - { - umbraco.presentation.templateControls.Macro macroControl = new umbraco.presentation.templateControls.Macro(); - macroControl.Alias = helper.FindAttribute(attributes, "macroalias"); - IDictionaryEnumerator ide = attributes.GetEnumerator(); - while (ide.MoveNext()) - if (macroControl.Attributes[ide.Key.ToString()] == null) - macroControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString()); - pageContent.Controls.Add(macroControl); - } - else - { - var macroId = helper.FindAttribute(attributes, "macroid"); - if (macroId == string.Empty) macroId = helper.FindAttribute(attributes, "macroalias"); - var tempMacro = GetMacro(macroId); - if (tempMacro != null) - { - - try - { - var renderer = new MacroRenderer(Current.ProfilingLogger); - var c = renderer.Render(tempMacro, umbPage.Elements, umbPage.PageID, attributes).GetAsControl(); - if (c != null) - pageContent.Controls.Add(c); - else - System.Web.HttpContext.Current.Trace.Warn("Template", "Result of macro " + tempMacro.Name + " is null"); - - } - catch (Exception e) - { - System.Web.HttpContext.Current.Trace.Warn("Template", "Error adding macro " + tempMacro.Name, e); - } - } - } + umbraco.presentation.templateControls.Macro macroControl = new umbraco.presentation.templateControls.Macro(); + macroControl.Alias = helper.FindAttribute(attributes, "macroalias"); + IDictionaryEnumerator ide = attributes.GetEnumerator(); + while (ide.MoveNext()) + if (macroControl.Attributes[ide.Key.ToString()] == null) + macroControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString()); + pageContent.Controls.Add(macroControl); + if (debugMode) pageContent.Controls.Add(new LiteralControl("
    ")); } @@ -303,60 +179,14 @@ namespace umbraco { if (tag.ToLower().IndexOf("umbraco_getitem") > -1) { - - // NH: Switching to custom controls for items - if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) - { - umbraco.presentation.templateControls.Item itemControl = new umbraco.presentation.templateControls.Item(); - itemControl.Field = helper.FindAttribute(attributes, "field"); - IDictionaryEnumerator ide = attributes.GetEnumerator(); - while (ide.MoveNext()) - if (itemControl.Attributes[ide.Key.ToString()] == null) - itemControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString()); - pageContent.Controls.Add(itemControl); - } - else - { - try - { - //TODO: Make this work again - but let's make sure this whole class is overhauled and useful - - //if (helper.FindAttribute(attributes, "nodeId") != "" && int.Parse(helper.FindAttribute(attributes, "nodeId")) != 0) - //{ - // cms.businesslogic.Content c = new umbraco.cms.businesslogic.Content(int.Parse(helper.FindAttribute(attributes, "nodeId"))); - // item umbItem = new item(c.getProperty(helper.FindAttribute(attributes, "field")).Value.ToString(), attributes); - // tempElementContent = umbItem.FieldContent; - - // // Check if the content is published - // if (c.nodeObjectType == cms.businesslogic.web.Document._objectType) - // { - // try - // { - // cms.businesslogic.web.Document d = (cms.businesslogic.web.Document)c; - // if (!d.Published) - // tempElementContent = ""; - // } - // catch { } - // } - - //} - //else - //{ - // // NH adds Live Editing test stuff - // item umbItem = new item(umbPage.Elements, attributes); - // // item umbItem = new item(umbPage.PageElements[helper.FindAttribute(attributes, "field")].ToString(), attributes); - // tempElementContent = umbItem.FieldContent; - //} - - if (debugMode) - tempElementContent = - "
    " + tempElementContent + "
    "; - } - catch (Exception e) - { - System.Web.HttpContext.Current.Trace.Warn("umbracoTemplate", "Error reading element (" + helper.FindAttribute(attributes, "field") + ")", e); - } - } + umbraco.presentation.templateControls.Item itemControl = new umbraco.presentation.templateControls.Item(); + itemControl.Field = helper.FindAttribute(attributes, "field"); + IDictionaryEnumerator ide = attributes.GetEnumerator(); + while (ide.MoveNext()) + if (itemControl.Attributes[ide.Key.ToString()] == null) + itemControl.Attributes.Add(ide.Key.ToString(), ide.Value.ToString()); + pageContent.Controls.Add(itemControl); + } } tempOutput.Remove(0, tempOutput.ToString().IndexOf(">") + 1); @@ -504,12 +334,6 @@ where nodeId = @templateID", this._masterTemplate = t._masterTemplate; this._templateName = t._templateName; - // Only check for master on legacy templates - can show error when using master pages. - if (!UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) - { - checkForMaster(tId); - } - } private void checkForMaster(int templateID) { @@ -556,7 +380,7 @@ where nodeId = @templateID", Current.DistributedCache.RefreshTemplateCache(templateID); } - public template(String templateContent) + public template(string templateContent) { _templateOutput.Append(templateContent); _masterTemplate = 0; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/umbracoField.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/umbracoField.aspx.cs index 93877b34d7..33728a19c5 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/umbracoField.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/umbracoField.aspx.cs @@ -34,10 +34,7 @@ namespace umbraco.dialogs pp_casing.Text = Services.TextService.Localize("templateEditor/casing"); pp_encode.Text = Services.TextService.Localize("templateEditor/encoding"); - if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) - { - tagName.Value = "umbraco:Item"; - } + tagName.Value = "umbraco:Item"; using (var scope = Current.ScopeProvider.CreateScope()) { From 6faa2ff1779efc6b9bdd87cd8e0909c20b01c502 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 01:27:25 +1000 Subject: [PATCH 53/58] Removes unused and obsoleted code --- .../Configuration/UmbracoSettings/ILink.cs | 20 --- .../UmbracoSettings/SecurityElement.cs | 2 +- src/Umbraco.Core/Constants-Web.cs | 7 - src/Umbraco.Core/IO/MasterPageHelper.cs | 8 +- .../Logging/ParallelForwardingAppender.cs | 21 --- src/Umbraco.Core/Media/IImageUrlProvider.cs | 17 -- src/Umbraco.Core/Media/IThumbnailProvider.cs | 16 -- src/Umbraco.Core/Models/Membership/IUser.cs | 16 +- .../Models/Membership/IUserType.cs | 17 -- src/Umbraco.Core/Models/Membership/User.cs | 156 ------------------ .../Models/Membership/UserType.cs | 78 --------- src/Umbraco.Core/Models/UmbracoObjectTypes.cs | 20 +-- src/Umbraco.Core/Models/UserExtensions.cs | 9 - src/Umbraco.Core/Umbraco.Core.csproj | 6 - .../UmbracoSettings/SecurityElementTests.cs | 2 +- .../Services/EntityServiceTests.cs | 1 - src/Umbraco.Web/Composing/Current.cs | 4 - src/Umbraco.Web/CompositionExtensions.cs | 8 - src/Umbraco.Web/Editors/EntityController.cs | 2 - src/Umbraco.Web/Editors/MediaController.cs | 25 +-- .../Editors/MediaTypeController.cs | 19 +-- src/Umbraco.Web/Media/ImageUrl.cs | 97 ----------- .../Media/ImageUrlProviderCollection.cs | 29 ---- .../ImageUrlProviderCollectionBuilder.cs | 14 -- .../ImageUrlProviders/ImageUrlProvider.cs | 93 ----------- .../AbstractThumbnailProvider.cs | 36 ---- .../FileExtensionIconThumbnailProvider.cs | 43 ----- .../ImageThumbnailProvider.cs | 62 ------- .../MediaTypeIconThumbnailProvider.cs | 44 ----- .../ContentEditing/UmbracoEntityTypes.cs | 9 +- .../Models/ContentEditing/UserDetail.cs | 8 +- .../Models/Mapping/UserMapperProfile.cs | 22 --- .../Runtime/WebRuntimeComponent.cs | 1 - src/Umbraco.Web/Umbraco.Web.csproj | 14 -- src/Umbraco.Web/UmbracoHelper.cs | 14 +- .../_Legacy/Actions/ActionNewFolder.cs | 89 ---------- src/Umbraco.Web/_Legacy/Packager/Package.cs | 145 ---------------- .../umbraco.presentation/library.cs | 13 -- .../umbraco.presentation/umbraco/ping.aspx.cs | 38 ----- .../umbraco/templateControls/Image.cs | 32 ---- 40 files changed, 11 insertions(+), 1246 deletions(-) delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/ILink.cs delete mode 100644 src/Umbraco.Core/Logging/ParallelForwardingAppender.cs delete mode 100644 src/Umbraco.Core/Media/IImageUrlProvider.cs delete mode 100644 src/Umbraco.Core/Media/IThumbnailProvider.cs delete mode 100644 src/Umbraco.Core/Models/Membership/IUserType.cs delete mode 100644 src/Umbraco.Core/Models/Membership/UserType.cs delete mode 100644 src/Umbraco.Web/Media/ImageUrl.cs delete mode 100644 src/Umbraco.Web/Media/ImageUrlProviderCollection.cs delete mode 100644 src/Umbraco.Web/Media/ImageUrlProviderCollectionBuilder.cs delete mode 100644 src/Umbraco.Web/Media/ImageUrlProviders/ImageUrlProvider.cs delete mode 100644 src/Umbraco.Web/Media/ThumbnailProviders/AbstractThumbnailProvider.cs delete mode 100644 src/Umbraco.Web/Media/ThumbnailProviders/FileExtensionIconThumbnailProvider.cs delete mode 100644 src/Umbraco.Web/Media/ThumbnailProviders/ImageThumbnailProvider.cs delete mode 100644 src/Umbraco.Web/Media/ThumbnailProviders/MediaTypeIconThumbnailProvider.cs delete mode 100644 src/Umbraco.Web/_Legacy/Actions/ActionNewFolder.cs delete mode 100644 src/Umbraco.Web/_Legacy/Packager/Package.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/ping.aspx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Image.cs diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ILink.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ILink.cs deleted file mode 100644 index c4b5781ca3..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ILink.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.ComponentModel; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This is no longer used and will be removed in future versions")] - public interface ILink - { - string Application { get; } - - string ApplicationUrl { get; } - - string Language { get; } - - string UserType { get; } - - string HelpUrl { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/SecurityElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/SecurityElement.cs index 8ae5816569..9ce88a8f75 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/SecurityElement.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/SecurityElement.cs @@ -41,7 +41,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings [ConfigurationProperty("authCookieName")] internal InnerTextConfigurationElement AuthCookieName { - get { return GetOptionalTextElement("authCookieName", Constants.Web.AuthCookieName); } + get { return GetOptionalTextElement("authCookieName", "UMB_UCONTEXT"); } } [ConfigurationProperty("authCookieDomain")] diff --git a/src/Umbraco.Core/Constants-Web.cs b/src/Umbraco.Core/Constants-Web.cs index a5f140ddba..0da5431e91 100644 --- a/src/Umbraco.Core/Constants-Web.cs +++ b/src/Umbraco.Core/Constants-Web.cs @@ -23,13 +23,6 @@ namespace Umbraco.Core public const string InstallerCookieName = "umb_installId"; - /// - /// The auth cookie name - /// - [Obsolete("DO NOT USE THIS, USE ISecuritySection.AuthCookieName, this will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public const string AuthCookieName = "UMB_UCONTEXT"; - } } } diff --git a/src/Umbraco.Core/IO/MasterPageHelper.cs b/src/Umbraco.Core/IO/MasterPageHelper.cs index e619ec98d8..049db04b9a 100644 --- a/src/Umbraco.Core/IO/MasterPageHelper.cs +++ b/src/Umbraco.Core/IO/MasterPageHelper.cs @@ -27,13 +27,7 @@ namespace Umbraco.Core.IO { return _masterPageFileSystem.FileExists(GetFilePath(t)); } - - [Obsolete("This is only used for legacy purposes and will be removed in future versions")] - internal string GetPhysicalFilePath(ITemplate t) - { - return _masterPageFileSystem.GetFullPath(GetFilePath(t.Alias)); - } - + private string GetFilePath(ITemplate t) { return GetFilePath(t.Alias); diff --git a/src/Umbraco.Core/Logging/ParallelForwardingAppender.cs b/src/Umbraco.Core/Logging/ParallelForwardingAppender.cs deleted file mode 100644 index e8dad743e1..0000000000 --- a/src/Umbraco.Core/Logging/ParallelForwardingAppender.cs +++ /dev/null @@ -1,21 +0,0 @@ -// fixme - remove this file -//using log4net.Core; -//using log4net.Util; -//using System; -//using System.Collections.Concurrent; -//using System.Threading; -//using System.Threading.Tasks; - -//namespace Umbraco.Core.Logging -//{ -// /// -// /// An asynchronous appender based on -// /// -// /// -// /// Borrowed from https://github.com/cjbhaines/Log4Net.Async - will reference Nuget packages directly in v8 -// /// -// [Obsolete("Use the Log4Net.Async.ParallelForwardingAppender instead this will be removed in future versions")] -// public class ParallelForwardingAppender : Log4Net.Async.ParallelForwardingAppender -// { -// } -//} diff --git a/src/Umbraco.Core/Media/IImageUrlProvider.cs b/src/Umbraco.Core/Media/IImageUrlProvider.cs deleted file mode 100644 index 4a51edd412..0000000000 --- a/src/Umbraco.Core/Media/IImageUrlProvider.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Umbraco.Core.Media -{ - // note: because this interface is obsolete is is *not* IDiscoverable, and in case the - // TypeLoader is asked to find types implementing this interface it will fall back - // to a complete scan. - - [Obsolete("IImageUrlProvider is no longer used and will be removed in future versions")] - public interface IImageUrlProvider // IDiscoverable - { - string Name { get; } - string GetImageUrlFromMedia(int mediaId, IDictionary parameters); - string GetImageUrlFromFileName(string specifiedSrc, IDictionary parameters); - } -} diff --git a/src/Umbraco.Core/Media/IThumbnailProvider.cs b/src/Umbraco.Core/Media/IThumbnailProvider.cs deleted file mode 100644 index 1e5a59bb39..0000000000 --- a/src/Umbraco.Core/Media/IThumbnailProvider.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace Umbraco.Core.Media -{ - // note: because this interface is obsolete is is *not* IDiscoverable, and in case the - // TypeLoader is asked to find types implementing this interface it will fall back - // to a complete scan. - - [Obsolete("Thumbnails are generated by ImageProcessor, use that instead")] - public interface IThumbnailProvider // : IDiscoverable - { - bool CanProvideThumbnail(string fileUrl); - string GetThumbnailUrl(string fileUrl); - } - -} diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index 8219af17b9..f3092a0106 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -18,11 +18,7 @@ namespace Umbraco.Core.Models.Membership int[] StartContentIds { get; set; } int[] StartMediaIds { get; set; } string Language { get; set; } - - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - IUserType UserType { get; set; } - + DateTime? EmailConfirmedDate { get; set; } DateTime? InvitedDate { get; set; } @@ -37,14 +33,6 @@ namespace Umbraco.Core.Models.Membership IEnumerable AllowedSections { get; } - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - void RemoveAllowedSection(string sectionAlias); - - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - void AddAllowedSection(string sectionAlias); - /// /// Exposes the basic profile data /// @@ -65,4 +53,4 @@ namespace Umbraco.Core.Models.Membership ///
    string TourData { get; set; } } -} \ No newline at end of file +} diff --git a/src/Umbraco.Core/Models/Membership/IUserType.cs b/src/Umbraco.Core/Models/Membership/IUserType.cs deleted file mode 100644 index 118d66074f..0000000000 --- a/src/Umbraco.Core/Models/Membership/IUserType.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using Umbraco.Core.Models.Entities; - -namespace Umbraco.Core.Models.Membership -{ - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public interface IUserType : IEntity - { - string Alias { get; set; } - string Name { get; set; } - IEnumerable Permissions { get; set; } - - } -} diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 0e3ab70e0a..cc91f5ed47 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -284,162 +284,6 @@ namespace Umbraco.Core.Models.Membership get { return _allowedSections ?? (_allowedSections = new List(_userGroups.SelectMany(x => x.AllowedSections).Distinct())); } } - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - IUserType IUser.UserType - { - get - { - //the best we can do here is to return the user's first user group as a IUserType object - //but we should attempt to return any group that is the built in ones first - var groups = Groups.ToArray(); - if (groups.Length == 0) - { - //In backwards compatibility land, a user type cannot be null! so we need to return a fake one. - return new UserType - { - Alias = "temp", - Id = int.MinValue, - Key = Guid.Empty, - CreateDate = default(DateTime), - DeleteDate = null, - Name = "Temp", - Permissions = new List(), - UpdateDate = default(DateTime) - }; - } - var builtIns = new[] { Constants.Security.AdminGroupAlias, "writer", "editor", "translator" }; - var foundBuiltIn = groups.FirstOrDefault(x => builtIns.Contains(x.Alias)); - IUserGroup realGroup; - if (foundBuiltIn != null) - { - //if the group isn't IUserGroup we'll need to look it up - realGroup = foundBuiltIn as IUserGroup ?? Current.Services.UserService.GetUserGroupById(foundBuiltIn.Id); - - //return a mapped version of the group - return new UserType - { - Alias = realGroup.Alias, - Id = realGroup.Id, - Key = realGroup.Key, - CreateDate = realGroup.CreateDate, - DeleteDate = realGroup.DeleteDate, - Name = realGroup.Name, - Permissions = realGroup.Permissions, - UpdateDate = realGroup.UpdateDate - }; - } - - //otherwise return the first - //if the group isn't IUserGroup we'll need to look it up - realGroup = groups[0] as IUserGroup ?? Current.Services.UserService.GetUserGroupById(groups[0].Id); - //return a mapped version of the group - return new UserType - { - Alias = realGroup.Alias, - Id = realGroup.Id, - Key = realGroup.Key, - CreateDate = realGroup.CreateDate, - DeleteDate = realGroup.DeleteDate, - Name = realGroup.Name, - Permissions = realGroup.Permissions, - UpdateDate = realGroup.UpdateDate - }; - } - set - { - //if old APIs are still using this lets first check if the user is part of the user group with the alias specified - if (Groups.Any(x => x.Alias == value.Alias)) - return; - - //the only other option we have here is to lookup the group (and we'll need to use singletons here :( ) - var found = Current.Services.UserService.GetUserGroupByAlias(value.Alias); - if (found == null) - throw new InvalidOperationException("No user group was found with the alias " + value.Alias + ", this API (IUser.UserType) is obsolete, use user groups instead"); - - //if it's found, all we can do is add it, we can't really replace them - AddGroup(found.ToReadOnlyGroup()); - } - } - - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - void IUser.RemoveAllowedSection(string sectionAlias) - { - //don't do anything if they aren't allowed it already - if (AllowedSections.Contains(sectionAlias) == false) - return; - - var groups = Groups.ToArray(); - //our only option here is to check if a custom group is created for this user, if so we can remove it from that group, otherwise we'll throw - //now we'll check if the user has a special 1:1 user group created for itself. This will occur if this method is used and also during an upgrade. - //this comes in the alias form of userName + 'Group' - var customUserGroup = groups.FirstOrDefault(x => x.Alias == (Username + "Group")); - if (customUserGroup != null) - { - //if the group isn't IUserGroup we'll need to look it up - var realGroup = customUserGroup as IUserGroup ?? Current.Services.UserService.GetUserGroupById(customUserGroup.Id); - realGroup.RemoveAllowedSection(sectionAlias); - //now we need to flag this for saving (hack!) - GroupsToSave.Add(realGroup); - } - else - { - throw new InvalidOperationException("Cannot remove the allowed section using this obsolete API. Modify the user's groups instead"); - } - - } - - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - void IUser.AddAllowedSection(string sectionAlias) - { - //don't do anything if they are allowed it already - if (AllowedSections.Contains(sectionAlias)) - return; - - //This is here for backwards compat only. - //First we'll check if the user is part of the 'admin' group. If so then we can ensure that the admin group has this section available to it. - //otherwise, the only thing we can do is create a custom user group for this user and add this section. - //We are checking for admin here because if the user is an admin and an allowed section is being added, then it's assumed it's to be added - //for the whole admin group (i.e. Forms installer does this for admins) - var groups = Groups.ToArray(); - var admin = groups.FirstOrDefault(x => x.Alias == Constants.Security.AdminGroupAlias); - if (admin != null) - { - //if the group isn't IUserGroup we'll need to look it up - var realGroup = admin as IUserGroup ?? Current.Services.UserService.GetUserGroupById(admin.Id); - realGroup.AddAllowedSection(sectionAlias); - //now we need to flag this for saving (hack!) - GroupsToSave.Add(realGroup); - } - else - { - //now we'll check if the user has a special 1:1 user group created for itself. This will occur if this method is used and also during an upgrade. - //this comes in the alias form of userName + 'Group' - var customUserGroup = groups.FirstOrDefault(x => x.Alias == (Username + "Group")); - if (customUserGroup != null) - { - //if the group isn't IUserGroup we'll need to look it up - var realGroup = customUserGroup as IUserGroup ?? Current.Services.UserService.GetUserGroupById(customUserGroup.Id); - realGroup.AddAllowedSection(sectionAlias); - //now we need to flag this for saving (hack!) - GroupsToSave.Add(realGroup); - } - - //ok, so the user doesn't have a 1:1 group, we'll need to flag it for creation - var newUserGroup = new UserGroup - { - Alias = Username + "Group", - Name = "Group for " + Username - }; - newUserGroup.AddAllowedSection(sectionAlias); - //add this user to this new group - AddGroup(newUserGroup); - GroupsToSave.Add(newUserGroup); - } - } - /// /// This used purely for hacking backwards compatibility into this class for < 7.7 compat /// diff --git a/src/Umbraco.Core/Models/Membership/UserType.cs b/src/Umbraco.Core/Models/Membership/UserType.cs deleted file mode 100644 index d2e4a8f6cb..0000000000 --- a/src/Umbraco.Core/Models/Membership/UserType.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Reflection; -using System.Runtime.Serialization; -using Umbraco.Core.Models.Entities; -using Umbraco.Core.Strings; - -namespace Umbraco.Core.Models.Membership -{ - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - [Serializable] - [DataContract(IsReference = true)] - internal class UserType : EntityBase, IUserType - { - private string _alias; - private string _name; - private IEnumerable _permissions; - private static readonly Lazy Ps = new Lazy(); - private class PropertySelectors - { - public readonly PropertyInfo NameSelector = ExpressionHelper.GetPropertyInfo(x => x.Name); - public readonly PropertyInfo AliasSelector = ExpressionHelper.GetPropertyInfo(x => x.Alias); - public readonly PropertyInfo PermissionsSelector = ExpressionHelper.GetPropertyInfo>(x => x.Permissions); - } - - public UserType(string name, string alias) - { - Name = name; - Alias = alias; - } - - public UserType() - { - } - - [DataMember] - public string Alias - { - get { return _alias; } - set - { - SetPropertyValueAndDetectChanges( - value.ToCleanString(CleanStringType.Alias | CleanStringType.UmbracoCase), - ref _alias, - Ps.Value.AliasSelector); - } - } - - [DataMember] - public string Name - { - get { return _name; } - set { SetPropertyValueAndDetectChanges(value, ref _name, Ps.Value.NameSelector); } - } - - /// - /// The set of default permissions for the user type - /// - /// - /// By default each permission is simply a single char but we've made this an enumerable{string} to support a more flexible permissions structure in the future. - /// - [DataMember] - public IEnumerable Permissions - { - get { return _permissions; } - set - { - SetPropertyValueAndDetectChanges(value, ref _permissions, Ps.Value.PermissionsSelector, - //Custom comparer for enumerable - new DelegateEqualityComparer>( - (enum1, enum2) => enum1.UnsortedSequenceEqual(enum2), - enum1 => enum1.GetHashCode())); - } - } - } -} diff --git a/src/Umbraco.Core/Models/UmbracoObjectTypes.cs b/src/Umbraco.Core/Models/UmbracoObjectTypes.cs index 31b5f2e513..817ef3ace8 100644 --- a/src/Umbraco.Core/Models/UmbracoObjectTypes.cs +++ b/src/Umbraco.Core/Models/UmbracoObjectTypes.cs @@ -14,14 +14,6 @@ namespace Umbraco.Core.Models ///
    Unknown, - /// - /// Content Item Type - /// - [UmbracoObjectType(Constants.ObjectTypes.Strings.ContentItemType)] - [FriendlyName("Content Item Type")] - [Obsolete("This is not used and will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - ContentItemType, /// /// Root @@ -69,17 +61,7 @@ namespace Umbraco.Core.Models [FriendlyName("Member Group")] [UmbracoUdiType(Constants.UdiEntityType.MemberGroup)] MemberGroup, - - //TODO: What is a 'Content Item' supposed to be??? - /// - /// Content Item - /// - [UmbracoObjectType(Constants.ObjectTypes.Strings.ContentItem)] - [FriendlyName("Content Item")] - [Obsolete("This is not used and will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - ContentItem, - + /// /// "Media Type /// diff --git a/src/Umbraco.Core/Models/UserExtensions.cs b/src/Umbraco.Core/Models/UserExtensions.cs index f78de43f01..00dd3273bf 100644 --- a/src/Umbraco.Core/Models/UserExtensions.cs +++ b/src/Umbraco.Core/Models/UserExtensions.cs @@ -112,15 +112,6 @@ namespace Umbraco.Core.Models } - public static void ClearAllowedSections(this IUser user) - { - var allowed = user.AllowedSections.ToArray(); - foreach (var s in allowed) - { - user.RemoveAllowedSection(s); - } - } - /// /// Returns the culture info associated with this user, based on the language they're assigned to in the back office /// diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 448acce472..411e4db1bf 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -261,7 +261,6 @@ - @@ -550,7 +549,6 @@ - @@ -597,9 +595,7 @@ - - @@ -703,7 +699,6 @@ - @@ -715,7 +710,6 @@ - diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/SecurityElementTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/SecurityElementTests.cs index d419d9d320..429aa28bb7 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/SecurityElementTests.cs +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/SecurityElementTests.cs @@ -33,7 +33,7 @@ namespace Umbraco.Tests.Configurations.UmbracoSettings [Test] public void AuthCookieName() { - Assert.IsTrue(SettingsSection.Security.AuthCookieName == Constants.Web.AuthCookieName); + Assert.IsTrue(SettingsSection.Security.AuthCookieName == "UMB_UCONTEXT"); } } } diff --git a/src/Umbraco.Tests/Services/EntityServiceTests.cs b/src/Umbraco.Tests/Services/EntityServiceTests.cs index 8d8e127131..0546eb3c7b 100644 --- a/src/Umbraco.Tests/Services/EntityServiceTests.cs +++ b/src/Umbraco.Tests/Services/EntityServiceTests.cs @@ -549,7 +549,6 @@ namespace Umbraco.Tests.Services var objectTypeId = Constants.ObjectTypes.ContentItem; Assert.Throws(() => service.GetAll()); - Assert.Throws(() => service.GetAll(UmbracoObjectTypes.ContentItem)); Assert.Throws(() => service.GetAll(objectTypeId)); } diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index e1317a902b..d327d1f70c 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -23,7 +23,6 @@ using Umbraco.Web.Cache; using Umbraco.Web.Editors; using Umbraco.Web.HealthCheck; using Umbraco.Web.Media; -using Umbraco.Web.Media.ThumbnailProviders; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; @@ -134,9 +133,6 @@ namespace Umbraco.Web.Composing public static FilteredControllerFactoryCollection FilteredControllerFactories => Container.GetInstance(); - internal static ImageUrlProviderCollection ImageUrlProviders - => Container.GetInstance(); - internal static IPublishedSnapshotService PublishedSnapshotService => Container.GetInstance(); diff --git a/src/Umbraco.Web/CompositionExtensions.cs b/src/Umbraco.Web/CompositionExtensions.cs index e172af7b8a..332380009d 100644 --- a/src/Umbraco.Web/CompositionExtensions.cs +++ b/src/Umbraco.Web/CompositionExtensions.cs @@ -6,7 +6,6 @@ using Umbraco.Core.Macros; using Umbraco.Web.Editors; using Umbraco.Web.HealthCheck; using Umbraco.Web.Media; -using Umbraco.Web.Media.ThumbnailProviders; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; @@ -65,13 +64,6 @@ namespace Umbraco.Core.Components public static HealthCheckCollectionBuilder HealthChecks(this Composition composition) => composition.Container.GetInstance(); - /// - /// Gets the image url providers collection builder. - /// - /// The composition. - internal static ImageUrlProviderCollectionBuilder ImageUrlProviders(this Composition composition) - => composition.Container.GetInstance(); - /// /// Gets the url providers collection builder. /// diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index a558648ffc..53689c9052 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -843,8 +843,6 @@ namespace Umbraco.Web.Editors return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.MemberGroup: return UmbracoObjectTypes.MemberGroup; - case UmbracoEntityTypes.ContentItem: - return UmbracoObjectTypes.ContentItem; case UmbracoEntityTypes.MediaType: return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.DocumentType: diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index fb09cefd03..5458070260 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -55,7 +55,7 @@ namespace Umbraco.Web.Editors { controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ParameterSwapControllerActionSelector( new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetById", "id", typeof(int), typeof(Guid), typeof(Udi)), - new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetChildren", "id", typeof(int), typeof(Guid), typeof(Udi), typeof(string)))); + new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetChildren", "id", typeof(int), typeof(Guid), typeof(Udi)))); } } @@ -369,29 +369,6 @@ namespace Umbraco.Web.Editors throw new HttpResponseException(HttpStatusCode.NotFound); } - [Obsolete("Do not use this method, use either the overload with INT or GUID instead, this will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - [UmbracoTreeAuthorize(Constants.Trees.MediaTypes, Constants.Trees.Media)] - public PagedResult> GetChildren(string id, - int pageNumber = 0, - int pageSize = 0, - string orderBy = "SortOrder", - Direction orderDirection = Direction.Ascending, - bool orderBySystemField = true, - string filter = "") - { - foreach (var type in new[] { typeof(int), typeof(Guid) }) - { - var parsed = id.TryConvertTo(type); - if (parsed) - { - //oooh magic! will auto select the right overload - return GetChildren((dynamic)parsed.Result); - } - } - - throw new HttpResponseException(HttpStatusCode.NotFound); - } #endregion /// diff --git a/src/Umbraco.Web/Editors/MediaTypeController.cs b/src/Umbraco.Web/Editors/MediaTypeController.cs index 0751faa217..a98a2183b2 100644 --- a/src/Umbraco.Web/Editors/MediaTypeController.cs +++ b/src/Umbraco.Web/Editors/MediaTypeController.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.Editors public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ParameterSwapControllerActionSelector( - new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetAllowedChildren", "contentId", typeof(int), typeof(Guid), typeof(Udi), typeof(string)))); + new ParameterSwapControllerActionSelector.ParameterSwapInfo("GetAllowedChildren", "contentId", typeof(int), typeof(Guid), typeof(Udi)))); } } @@ -260,23 +260,6 @@ namespace Umbraco.Web.Editors throw new HttpResponseException(HttpStatusCode.NotFound); } - [Obsolete("Do not use this method, use either the overload with INT, GUID or UDI instead, this will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - [UmbracoTreeAuthorize(Constants.Trees.MediaTypes, Constants.Trees.Media)] - public IEnumerable GetAllowedChildren(string contentId) - { - foreach (var type in new[] { typeof(int), typeof(Guid) }) - { - var parsed = contentId.TryConvertTo(type); - if (parsed) - { - //oooh magic! will auto select the right overload - return GetAllowedChildren((dynamic)parsed.Result); - } - } - - throw new HttpResponseException(HttpStatusCode.NotFound); - } #endregion /// diff --git a/src/Umbraco.Web/Media/ImageUrl.cs b/src/Umbraco.Web/Media/ImageUrl.cs deleted file mode 100644 index 3606af5eda..0000000000 --- a/src/Umbraco.Web/Media/ImageUrl.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Specialized; -using System.Globalization; -using System.Linq; -using System.Web; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Media; -using umbraco; -using Umbraco.Web.Composing; - -namespace Umbraco.Web.Media -{ - [Obsolete("This is no longer used and will be removed in future versions")] - public class ImageUrl - { - [Obsolete("Use TryGetImageUrl() instead")] - public static string GetImageUrl(string specifiedSrc, string field, string provider, string parameters, int? nodeId = null) - { - string url; - var found = TryGetImageUrl(specifiedSrc, field, provider, parameters, nodeId, out url); - - return found ? url : string.Empty; - } - - public static bool TryGetImageUrl(string specifiedSrc, string field, string provider, string parameters, int? nodeId, out string url) - { - var imageUrlProvider = GetProvider(provider); - - var parsedParameters = string.IsNullOrEmpty(parameters) ? new NameValueCollection() : HttpUtility.ParseQueryString(parameters); - - var queryValues = parsedParameters.Keys.Cast().ToDictionary(key => key, key => parsedParameters[key]); - - if (string.IsNullOrEmpty(field)) - { - url = imageUrlProvider.GetImageUrlFromFileName(specifiedSrc, queryValues); - return true; - } - else - { - var fieldValue = string.Empty; - if (nodeId.HasValue) - { - var contentFromCache = GetContentFromCache(nodeId.GetValueOrDefault(), field); - if (contentFromCache != null) - { - fieldValue = contentFromCache.ToString(); - } - else - { - var p = UmbracoContext.Current.ContentCache.GetById(nodeId.GetValueOrDefault()); - var v = p.Value(field); - fieldValue = v == null ? string.Empty : v.ToString(); - } - } - else - { - var context = HttpContext.Current; - if (context != null) - { - var elements = context.Items["pageElements"] as Hashtable; - if (elements != null) - { - var value = elements[field]; - fieldValue = value != null ? value.ToString() : string.Empty; - } - } - } - - if (!string.IsNullOrWhiteSpace(fieldValue)) - { - int mediaId; - url = int.TryParse(fieldValue, out mediaId) - ? imageUrlProvider.GetImageUrlFromMedia(mediaId, queryValues) - : imageUrlProvider.GetImageUrlFromFileName(fieldValue, queryValues); - return true; - } - } - - url = string.Empty; - return false; - } - - private static IImageUrlProvider GetProvider(string provider) - { - return Current.ImageUrlProviders[provider]; - } - - private static object GetContentFromCache(int nodeIdInt, string field) - { - var content = Current.ApplicationCache.RuntimeCache.GetCacheItem( - string.Format("{0}{1}_{2}", CacheKeys.ContentItemCacheKey, nodeIdInt.ToString(CultureInfo.InvariantCulture), field)); - return content; - } - } -} diff --git a/src/Umbraco.Web/Media/ImageUrlProviderCollection.cs b/src/Umbraco.Web/Media/ImageUrlProviderCollection.cs deleted file mode 100644 index 5d20fbda4f..0000000000 --- a/src/Umbraco.Web/Media/ImageUrlProviderCollection.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.Media; -using Umbraco.Web.Media.ImageUrlProviders; - -namespace Umbraco.Web.Media -{ - // fixme - kill entirely we should not use this anymore - internal class ImageUrlProviderCollection : BuilderCollectionBase - { - public ImageUrlProviderCollection(IEnumerable items) - : base(items) - { } - - public IImageUrlProvider this[string name] - { - get - { - if (string.IsNullOrWhiteSpace(name)) name = ImageUrlProvider.DefaultName; - var provider = this.FirstOrDefault(x => x.Name.InvariantEquals(name)); - if (provider == null) throw new InvalidOperationException($"No provider exists with name \"{name}\"."); - return provider; - } - } - } -} diff --git a/src/Umbraco.Web/Media/ImageUrlProviderCollectionBuilder.cs b/src/Umbraco.Web/Media/ImageUrlProviderCollectionBuilder.cs deleted file mode 100644 index 79fb489e40..0000000000 --- a/src/Umbraco.Web/Media/ImageUrlProviderCollectionBuilder.cs +++ /dev/null @@ -1,14 +0,0 @@ -using LightInject; -using Umbraco.Core.Composing; -using Umbraco.Core.Media; - -namespace Umbraco.Web.Media -{ - internal class ImageUrlProviderCollectionBuilder : OrderedCollectionBuilderBase - { - public ImageUrlProviderCollectionBuilder(IServiceContainer container) : base(container) - {} - - protected override ImageUrlProviderCollectionBuilder This => this; - } -} diff --git a/src/Umbraco.Web/Media/ImageUrlProviders/ImageUrlProvider.cs b/src/Umbraco.Web/Media/ImageUrlProviders/ImageUrlProvider.cs deleted file mode 100644 index fa2209b278..0000000000 --- a/src/Umbraco.Web/Media/ImageUrlProviders/ImageUrlProvider.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml.XPath; -using Umbraco.Core.Configuration; -using Umbraco.Core.Media; -using umbraco; -using Umbraco.Core; - -namespace Umbraco.Web.Media.ImageUrlProviders -{ - [Obsolete("IImageUrlProvider is no longer used and will be removed in future versions")] - public class ImageUrlProvider : IImageUrlProvider - { - public const string DefaultName = "umbracoUpload"; - - public string Name - { - get { return DefaultName; } - } - - public string GetImageUrlFromMedia(int mediaId, IDictionary parameters) - { - var url = string.Empty; - - var nodeIterator = library.GetMedia(mediaId, false); - - if (nodeIterator.Current != null) - { - var filename = GetProperty(nodeIterator, Constants.Conventions.Media.File); - var withThumb = AddThumbInfo(filename, parameters); - url = AddCropInfo(withThumb, parameters); - } - - return url; - } - - public string GetImageUrlFromFileName(string specifiedSrc, IDictionary parameters) - { - var withThumb = AddThumbInfo(specifiedSrc, parameters); - return AddCropInfo(withThumb, parameters); - } - - private static string AddThumbInfo(string filename, IDictionary parameters) - { - var thumb = string.Empty; - if (parameters.ContainsKey("thumb")) - thumb = parameters["thumb"]; - - if (!string.IsNullOrEmpty(thumb) && filename.Contains(".")) - { - var lastIndexOf = filename.LastIndexOf('.'); - var name = filename.Substring(0, lastIndexOf); - var extension = filename.Substring(lastIndexOf, filename.Length - lastIndexOf); - return string.Format("{0}_thumb_{1}{2}", name, thumb, extension); - } - return filename; - } - - private static string AddCropInfo(string filename, IDictionary parameters) - { - var crop = string.Empty; - if (parameters.ContainsKey("crop")) - crop = parameters["crop"]; - - if (!string.IsNullOrEmpty(crop) && filename.Contains(".")) - { - var lastIndexOf = filename.LastIndexOf('.'); - var name = filename.Substring(0, lastIndexOf); - - //var extension = filename.Substring(lastIndexOf, filename.Length - lastIndexOf); - //Built in cropper currently always uses jpg as an extension - - const string extension = ".jpg"; - return string.Format("{0}_{1}{2}", name, crop, extension); - } - - return filename; - } - - - private static string GetProperty(XPathNodeIterator nodeIterator, string fileProp) - { - var xpath = string.Format(".//{0}", fileProp); - - var file = string.Empty; - var selectSingleNode = nodeIterator.Current.SelectSingleNode(xpath); - if (selectSingleNode != null) - file = selectSingleNode.InnerXml; - - return file; - } - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/AbstractThumbnailProvider.cs b/src/Umbraco.Web/Media/ThumbnailProviders/AbstractThumbnailProvider.cs deleted file mode 100644 index 5ed103fe9b..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/AbstractThumbnailProvider.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Umbraco.Core; -using Umbraco.Core.Media; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - public abstract class AbstractThumbnailProvider : IThumbnailProvider - { - protected abstract IEnumerable SupportedExtensions { get; } - - public bool CanProvideThumbnail(string fileUrl) - { - string thumbUrl; - return TryGetThumbnailUrl(fileUrl, out thumbUrl); - } - - public string GetThumbnailUrl(string fileUrl) - { - string thumbUrl; - TryGetThumbnailUrl(fileUrl, out thumbUrl); - return thumbUrl; - } - - protected bool IsSupportedExtension(string ext) - { - return SupportedExtensions.InvariantContains(ext) || - SupportedExtensions.InvariantContains("*"); - } - - protected abstract bool TryGetThumbnailUrl(string fileUrl, out string thumbUrl); - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/FileExtensionIconThumbnailProvider.cs b/src/Umbraco.Web/Media/ThumbnailProviders/FileExtensionIconThumbnailProvider.cs deleted file mode 100644 index ea3a13a3c2..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/FileExtensionIconThumbnailProvider.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - [Weight(2000)] - public class FileExtensionIconThumbnailProvider : AbstractThumbnailProvider - { - protected override IEnumerable SupportedExtensions - { - get { return new List { "*" }; } - } - - protected override bool TryGetThumbnailUrl(string fileUrl, out string thumbUrl) - { - // Set thumbnail url to empty strin initially - thumbUrl = string.Empty; - - // Make sure file has an extension - var ext = Path.GetExtension(fileUrl); - if (string.IsNullOrEmpty(ext)) - return false; - - // Make sure it has a supported file extension - if (!IsSupportedExtension(ext)) - return false; - - // Make sure the thumbnail exists - var tmpThumbUrl = IOHelper.ResolveUrl(SystemDirectories.Umbraco + "/images/mediaThumbnails/"+ ext.TrimStart('.') +".png"); - if (!File.Exists(IOHelper.MapPath(tmpThumbUrl))) - return false; - - // We've got this far, so thumbnail must exist - thumbUrl = tmpThumbUrl; - return true; - } - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/ImageThumbnailProvider.cs b/src/Umbraco.Web/Media/ThumbnailProviders/ImageThumbnailProvider.cs deleted file mode 100644 index 4fea0a6b5f..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/ImageThumbnailProvider.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Umbraco.Core; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - [Weight(1000)] - public class ImageThumbnailProvider : AbstractThumbnailProvider - { - private readonly MediaFileSystem _mediaFileSystem; - - public ImageThumbnailProvider(MediaFileSystem mediaFileSystem) - { - _mediaFileSystem = mediaFileSystem; - } - - protected override IEnumerable SupportedExtensions - { - get { return new List { ".jpeg", ".jpg", ".gif", ".bmp", ".png", ".tiff", ".tif" }; } - } - - protected override bool TryGetThumbnailUrl(string fileUrl, out string thumbUrl) - { - // Set thumbnail url to empty strin initially - thumbUrl = string.Empty; - - // Make sure file has an extension - var ext = Path.GetExtension(fileUrl); - if (string.IsNullOrEmpty(ext)) - return false; - - // Make sure it has a supported file extension - if (!IsSupportedExtension(ext)) - return false; - - // Make sure the thumbnail exists - var tmpThumbUrl = fileUrl.Replace(ext, "_thumb" + ext); - - try - { - var fs = _mediaFileSystem; - var relativeThumbPath = fs.GetRelativePath(tmpThumbUrl); - if (!fs.FileExists(relativeThumbPath)) - return false; - } - catch (Exception) - { - // If something odd happens, just return false and move on - return false; - } - - // We've got this far, so thumbnail must exist - thumbUrl = tmpThumbUrl; - return true; - } - } -} diff --git a/src/Umbraco.Web/Media/ThumbnailProviders/MediaTypeIconThumbnailProvider.cs b/src/Umbraco.Web/Media/ThumbnailProviders/MediaTypeIconThumbnailProvider.cs deleted file mode 100644 index 0ecaaf8ff3..0000000000 --- a/src/Umbraco.Web/Media/ThumbnailProviders/MediaTypeIconThumbnailProvider.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Umbraco.Core.Composing; -using Umbraco.Core.IO; - -namespace Umbraco.Web.Media.ThumbnailProviders -{ - [Weight(3000)] - public class MediaTypeIconThumbnailProvider : AbstractThumbnailProvider - { - - protected override IEnumerable SupportedExtensions - { - get { return new List { "*" }; } - } - - protected override bool TryGetThumbnailUrl(string fileUrl, out string thumbUrl) - { - // Set thumbnail url to empty strin initially - thumbUrl = string.Empty; - - // Make sure file has an extension - var ext = Path.GetExtension(fileUrl); - if (string.IsNullOrEmpty(ext)) - return false; - - // Make sure it has a supported file extension - if (!IsSupportedExtension(ext)) - return false; - - // Make sure the thumbnail exists - var tmpThumbUrl = IOHelper.ResolveUrl(SystemDirectories.Umbraco + "/images/mediaThumbnails/"+ ext.TrimStart('.') +".png"); - if (!File.Exists(IOHelper.MapPath(tmpThumbUrl))) - return false; - - // We've got this far, so thumbnail must exist - thumbUrl = tmpThumbUrl; - return true; - } - } -} diff --git a/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs b/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs index 5f4414d919..2d778ca61c 100644 --- a/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs +++ b/src/Umbraco.Web/Models/ContentEditing/UmbracoEntityTypes.cs @@ -52,14 +52,7 @@ namespace Umbraco.Web.Models.ContentEditing /// Member Group /// MemberGroup, - - /// - /// Content Item - /// - [Obsolete("This is not used and will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - ContentItem, - + /// /// "Media Type /// diff --git a/src/Umbraco.Web/Models/ContentEditing/UserDetail.cs b/src/Umbraco.Web/Models/ContentEditing/UserDetail.cs index dc240bfb78..232dee818e 100644 --- a/src/Umbraco.Web/Models/ContentEditing/UserDetail.cs +++ b/src/Umbraco.Web/Models/ContentEditing/UserDetail.cs @@ -25,13 +25,7 @@ namespace Umbraco.Web.Models.ContentEditing /// [DataMember(Name = "emailHash")] public string EmailHash { get; set; } - - [Obsolete("This should not be used it exists for legacy reasons only, use user groups instead, it will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - [ReadOnly(true)] - [DataMember(Name = "userType")] - public string UserType { get; set; } - + [ReadOnly(true)] [DataMember(Name = "userGroups")] public string[] UserGroups { get; set; } diff --git a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index ad4eaa5b52..213a1a5e3a 100644 --- a/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -47,7 +47,6 @@ namespace Umbraco.Web.Models.Mapping .ForMember(detail => detail.TourData, opt => opt.Ignore()) .ForMember(dest => dest.SessionTimeout, opt => opt.Ignore()) .ForMember(dest => dest.EmailConfirmedDate, opt => opt.Ignore()) - .ForMember(dest => dest.UserType, opt => opt.Ignore()) .ForMember(dest => dest.InvitedDate, opt => opt.Ignore()) .ForMember(dest => dest.SecurityStamp, opt => opt.Ignore()) .ForMember(dest => dest.Avatar, opt => opt.Ignore()) @@ -79,7 +78,6 @@ namespace Umbraco.Web.Models.Mapping .ForMember(detail => detail.TourData, opt => opt.Ignore()) .ForMember(dest => dest.StartContentIds, opt => opt.Ignore()) .ForMember(dest => dest.StartMediaIds, opt => opt.Ignore()) - .ForMember(dest => dest.UserType, opt => opt.Ignore()) .ForMember(dest => dest.Language, opt => opt.Ignore()) .ForMember(dest => dest.Username, opt => opt.Ignore()) .ForMember(dest => dest.PasswordQuestion, opt => opt.Ignore()) @@ -332,26 +330,6 @@ namespace Umbraco.Web.Models.Mapping var groups = user.Groups.ToArray(); detail.UserGroups = user.Groups.Select(x => x.Alias).ToArray(); - if (groups.Length == 0) - { - //In backwards compatibility land, a user type cannot be null! so we need to return a fake one. - detail.UserType = "temp"; - } - else - { - var builtIns = new[] { Constants.Security.AdminGroupAlias, "writer", "editor", Constants.Security.TranslatorGroupAlias }; - var foundBuiltIn = groups.FirstOrDefault(x => builtIns.Contains(x.Alias)); - if (foundBuiltIn != null) - { - detail.UserType = foundBuiltIn.Alias; - } - else - { - //otherwise return the first - detail.UserType = groups[0].Alias; - } - } - }); CreateMap() diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index e408a46db5..196fd10650 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -38,7 +38,6 @@ using Umbraco.Web.Features; using Umbraco.Web.HealthCheck; using Umbraco.Web.Install; using Umbraco.Web.Media; -using Umbraco.Web.Media.ThumbnailProviders; using Umbraco.Web.Mvc; using Umbraco.Web.PublishedCache; using Umbraco.Web.Routing; diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index d1ebf54a87..efb94856b9 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -206,7 +206,6 @@ - @@ -215,7 +214,6 @@ - @@ -467,7 +465,6 @@ - @@ -940,8 +937,6 @@ - - @@ -1123,7 +1118,6 @@ - @@ -1163,9 +1157,6 @@ ASPXCodeBehind - - ASPXCodeBehind - ASPXCodeBehind @@ -1181,7 +1172,6 @@ ASPXCodeBehind - @@ -1210,10 +1200,6 @@ - - - - diff --git a/src/Umbraco.Web/UmbracoHelper.cs b/src/Umbraco.Web/UmbracoHelper.cs index fca5c200b7..043584e6d9 100644 --- a/src/Umbraco.Web/UmbracoHelper.cs +++ b/src/Umbraco.Web/UmbracoHelper.cs @@ -890,19 +890,7 @@ namespace Umbraco.Web { return StringUtilities.ReplaceLineBreaksForHtml(text); } - - /// - /// Returns an MD5 hash of the string specified - /// - /// The text to create a hash from - /// Md5 has of the string - [Obsolete("Please use the CreateHash method instead. This may be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public string CreateMd5Hash(string text) - { - return text.ToMd5(); - } - + /// /// Generates a hash based on the text string passed in. This method will detect the /// security requirements (is FIPS enabled) and return an appropriate hash. diff --git a/src/Umbraco.Web/_Legacy/Actions/ActionNewFolder.cs b/src/Umbraco.Web/_Legacy/Actions/ActionNewFolder.cs deleted file mode 100644 index b4f16b3dd0..0000000000 --- a/src/Umbraco.Web/_Legacy/Actions/ActionNewFolder.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using Umbraco.Web.UI.Pages; - -namespace Umbraco.Web._Legacy.Actions -{ - /// - /// This action is invoked upon creation of a document - /// - [Obsolete("This class is no longer used and will be removed in future versions")] - public class ActionNewFolder : IAction - { - //create singleton -#pragma warning disable 612,618 - private static readonly ActionNewFolder m_instance = new ActionNewFolder(); -#pragma warning restore 612,618 - - /// - /// A public constructor exists ONLY for backwards compatibility in regards to 3rd party add-ons. - /// All Umbraco assemblies should use the singleton instantiation (this.Instance) - /// When this applicatio is refactored, this constuctor should be made private. - /// - [Obsolete("Use the singleton instantiation instead of a constructor")] - public ActionNewFolder() { } - - public static ActionNewFolder Instance - { - get { return m_instance; } - } - - #region IAction Members - - public char Letter - { - get - { - return '!'; - } - } - - public string JsFunctionName - { - get - { - return string.Format("{0}.actionNewFolder()", ClientTools.Scripts.GetAppActions); - } - } - - public string JsSource - { - get - { - return null; - } - } - - public string Alias - { - get - { - return "createFolder"; - } - } - - public string Icon - { - get - { - return "plus-sign-alt"; - } - } - - public bool ShowInNotifier - { - get - { - return false; - } - } - public bool CanBePermissionAssigned - { - get - { - return false; - } - } - - #endregion - } -} diff --git a/src/Umbraco.Web/_Legacy/Packager/Package.cs b/src/Umbraco.Web/_Legacy/Packager/Package.cs deleted file mode 100644 index 2116e64ea1..0000000000 --- a/src/Umbraco.Web/_Legacy/Packager/Package.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.ComponentModel; -using System.Linq; -using System.Runtime.CompilerServices; -using Umbraco.Core.Composing; -using Umbraco.Core.Models.Membership; - -namespace umbraco.cms.businesslogic.packager -{ - [Obsolete("This class is not used and will be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public class Package - { - public Package() - { - } - - /// - /// Initialize package install status object by specifying the internal id of the installation. - /// The id is specific to the local umbraco installation and cannot be used to identify the package in general. - /// Use the Package(Guid) constructor to check whether a package has been installed - /// - /// The internal id. - public Package(int Id) - { - Initialize(Id); - } - - public Package(Guid Id) - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - int installStatusId = scope.Database.ExecuteScalar( - "select id from umbracoInstalledPackages where package = @package and upgradeId = 0", new { package = Id}); - - if (installStatusId > 0) - Initialize(installStatusId); - else - throw new ArgumentException("Package with id '" + Id.ToString() + "' is not installed"); - - scope.Complete(); - } - } - - private void Initialize(int id) - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - var f = scope.Database.Fetch( - "select id, uninstalled, upgradeId, installDate, userId, package, versionMajor, versionMinor, versionPatch from umbracoInstalledPackages where id = @id", - new { id }).FirstOrDefault(); - if (f != null) - { - Id = id; - Uninstalled = f.uninstalled; - UpgradeId = f.upgradeId; - InstallDate = f.installDate; - User = Current.Services.UserService.GetUserById(f.userId); - PackageId = f.package; - VersionMajor = f.versionMajor; - VersionMinor = f.versionMinor; - VersionPatch = f.versionPatch; - } - - scope.Complete(); - } - } - - [MethodImpl(MethodImplOptions.Synchronized)] // ;-(( - public void Save() - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - // check if package status exists - if (Id == 0) - { - // The method is synchronized - scope.Database.Execute("INSERT INTO umbracoInstalledPackages (uninstalled, upgradeId, installDate, userId, versionMajor, versionMinor, versionPatch) VALUES (@uninstalled, @upgradeId, @installDate, @userId, @versionMajor, @versionMinor, @versionPatch)", - new - { - uninstalled = Uninstalled, - upgradeId = UpgradeId, - installData = InstallDate, - userId = User.Id, - versionMajor = VersionMajor, - versionMinor = VersionMinor, - versionPath = VersionPatch, - id = Id - }); - Id = scope.Database.ExecuteScalar("SELECT MAX(id) FROM umbracoInstalledPackages"); - } - - scope.Database.Execute( - "update umbracoInstalledPackages set " + - "uninstalled = @uninstalled, " + - "upgradeId = @upgradeId, " + - "installDate = @installDate, " + - "userId = @userId, " + - "versionMajor = @versionMajor, " + - "versionMinor = @versionMinor, " + - "versionPatch = @versionPatch " + - "where id = @id", - new - { - uninstalled = Uninstalled, - upgradeId = UpgradeId, - installData = InstallDate, - userId = User.Id, - versionMajor = VersionMajor, - versionMinor = VersionMinor, - versionPath = VersionPatch, - id = Id - }); - - scope.Complete(); - } - } - - public bool Uninstalled { get; set; } - - - public IUser User { get; set; } - - - public DateTime InstallDate { get; set; } - - - public int Id { get; set; } - - - public int UpgradeId { get; set; } - - - public Guid PackageId { get; set; } - - - public int VersionPatch { get; set; } - - - public int VersionMinor { get; set; } - - - public int VersionMajor { get; set; } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/library.cs b/src/Umbraco.Web/umbraco.presentation/library.cs index 4f8084e409..9b9d4df938 100644 --- a/src/Umbraco.Web/umbraco.presentation/library.cs +++ b/src/Umbraco.Web/umbraco.presentation/library.cs @@ -398,19 +398,6 @@ namespace umbraco return GetUmbracoHelper().MemberHasAccess(NodeId, Path); } - - /// - /// Returns an MD5 hash of the string specified - /// - /// The text to create a hash from - /// Md5 hash of the string - [Obsolete("Please use the CreateHash method instead. This may be removed in future versions")] - [EditorBrowsable(EditorBrowsableState.Never)] - public static string md5(string text) - { - return text.ToMd5(); - } - /// /// Generates a hash based on the text string passed in. This method will detect the /// security requirements (is FIPS enabled) and return an appropriate hash. diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/ping.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/ping.aspx.cs deleted file mode 100644 index 3d8f80ef97..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/ping.aspx.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Web; -using System.Web.SessionState; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; - -namespace umbraco.presentation -{ - - [Obsolete("This class will be removed in future versions.")] - [EditorBrowsable(EditorBrowsableState.Never)] - public partial class ping : System.Web.UI.Page - { - #region Web Form Designer generated code - override protected void OnInit(EventArgs e) - { - // - // CODEGEN: This call is required by the ASP.NET Web Form Designer. - // - InitializeComponent(); - base.OnInit(e); - } - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - } - #endregion - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Image.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Image.cs deleted file mode 100644 index 020a555fbc..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Image.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Web.UI; -using System.Web.UI.HtmlControls; -using Umbraco.Core.Media; -using Umbraco.Web.Media; - -namespace umbraco.presentation.templateControls -{ - [Obsolete("This is no longer used and will be removed in future versions")] - public class Image : HtmlImage - { - public string NodeId { get; set; } - public string Field { get; set; } - public string Provider { get; set; } - public string Parameters { get; set; } - - protected override void Render(HtmlTextWriter writer) - { - int id; - bool hasid = int.TryParse(NodeId, out id); - int? nodeId = hasid ? id : (int?)null; - - string url; - bool imageFound = ImageUrl.TryGetImageUrl(Src, Field, Provider, Parameters, nodeId, out url); - Src = url; - if (imageFound) - { - base.Render(writer); - } - } - } -} From 19edfdb2a4ff3ec8a2ccb98c2ccce2bc14a9cd42 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 01:30:36 +1000 Subject: [PATCH 54/58] Removes unused and obsoleted code --- src/Umbraco.Core/Models/File.cs | 8 +- src/Umbraco.Core/Models/IFile.cs | 4 +- .../Persistence/Dtos/StylesheetDto.cs | 24 - .../Persistence/Dtos/StylesheetPropertyDto.cs | 28 - src/Umbraco.Core/Umbraco.Core.csproj | 2 - .../Persistence/SqlCeTableByTableTest.cs | 30 +- src/Umbraco.Web/Models/RegisterModel.cs | 7 +- .../Mvc/SurfaceControllerFactory.cs | 68 -- src/Umbraco.Web/Umbraco.Web.csproj | 3 - src/Umbraco.Web/_Legacy/Actions/ActionQuit.cs | 88 --- .../umbraco/controls/ContentControl.cs | 699 ------------------ 11 files changed, 4 insertions(+), 957 deletions(-) delete mode 100644 src/Umbraco.Core/Persistence/Dtos/StylesheetDto.cs delete mode 100644 src/Umbraco.Core/Persistence/Dtos/StylesheetPropertyDto.cs delete mode 100644 src/Umbraco.Web/Mvc/SurfaceControllerFactory.cs delete mode 100644 src/Umbraco.Web/_Legacy/Actions/ActionQuit.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentControl.cs diff --git a/src/Umbraco.Core/Models/File.cs b/src/Umbraco.Core/Models/File.cs index cf202ea54f..41aff25a81 100644 --- a/src/Umbraco.Core/Models/File.cs +++ b/src/Umbraco.Core/Models/File.cs @@ -146,13 +146,7 @@ namespace Umbraco.Core.Models /// Gets or sets the file's virtual path (i.e. the file path relative to the root of the website) /// public string VirtualPath { get; set; } - - [Obsolete("This is no longer used and will be removed from the codebase in future versions")] - public virtual bool IsValid() - { - return true; - } - + // this exists so that class that manage name and alias differently, eg Template, // can implement their own cloning - (though really, not sure it's even needed) protected virtual void DeepCloneNameAndAlias(File clone) diff --git a/src/Umbraco.Core/Models/IFile.cs b/src/Umbraco.Core/Models/IFile.cs index 9b974276c1..109d65f554 100644 --- a/src/Umbraco.Core/Models/IFile.cs +++ b/src/Umbraco.Core/Models/IFile.cs @@ -43,8 +43,6 @@ namespace Umbraco.Core.Models /// Gets or sets the file's virtual path (i.e. the file path relative to the root of the website) /// string VirtualPath { get; set; } - - [Obsolete("This is no longer used and will be removed from the codebase in future versions")] - bool IsValid(); + } } diff --git a/src/Umbraco.Core/Persistence/Dtos/StylesheetDto.cs b/src/Umbraco.Core/Persistence/Dtos/StylesheetDto.cs deleted file mode 100644 index f340d34d16..0000000000 --- a/src/Umbraco.Core/Persistence/Dtos/StylesheetDto.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using NPoco; -using Umbraco.Core.Persistence.DatabaseAnnotations; - -namespace Umbraco.Core.Persistence.Dtos -{ - [Obsolete("This is no longer used and will be removed from Umbraco in future versions")] - internal class StylesheetDto - { - [Column("nodeId")] - [PrimaryKeyColumn(AutoIncrement = false)] - [ForeignKey(typeof(NodeDto))] - public int NodeId { get; set; } - - [Column("filename")] - [Length(100)] - public string Filename { get; set; } - - [Column("content")] - [SpecialDbType(SpecialDbTypes.NTEXT)] - [NullSetting(NullSetting = NullSettings.Null)] - public string Content { get; set; } - } -} diff --git a/src/Umbraco.Core/Persistence/Dtos/StylesheetPropertyDto.cs b/src/Umbraco.Core/Persistence/Dtos/StylesheetPropertyDto.cs deleted file mode 100644 index 5ef1aed9cc..0000000000 --- a/src/Umbraco.Core/Persistence/Dtos/StylesheetPropertyDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using NPoco; -using Umbraco.Core.Persistence.DatabaseAnnotations; - -namespace Umbraco.Core.Persistence.Dtos -{ - [Obsolete("This is no longer used and will be removed from Umbraco in future versions")] - internal class StylesheetPropertyDto - { - [Column("nodeId")] - [PrimaryKeyColumn(AutoIncrement = false)] - public int NodeId { get; set; } - - [Column("stylesheetPropertyEditor")] - [NullSetting(NullSetting = NullSettings.Null)] - public bool? Editor { get; set; } - - [Column("stylesheetPropertyAlias")] - [NullSetting(NullSetting = NullSettings.Null)] - [Length(50)] - public string Alias { get; set; } - - [Column("stylesheetPropertyValue")] - [NullSetting(NullSetting = NullSettings.Null)] - [Length(400)] - public string Value { get; set; } - } -} diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 411e4db1bf..18d51d6507 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -797,8 +797,6 @@ - - diff --git a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs index 9d2c574743..f52bfdaa59 100644 --- a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs +++ b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs @@ -415,35 +415,7 @@ namespace Umbraco.Tests.Persistence scope.Complete(); } } - - [Test] - public void Can_Create_cmsStylesheet_Table() - { - using (var scope = ScopeProvider.CreateScope()) - { - var helper = new DatabaseSchemaCreator(scope.Database, Mock.Of()); - - helper.CreateTable(); - helper.CreateTable(); - - scope.Complete(); - } - } - - [Test] - public void Can_Create_cmsStylesheetProperty_Table() - { - using (var scope = ScopeProvider.CreateScope()) - { - var helper = new DatabaseSchemaCreator(scope.Database, Mock.Of()); - - helper.CreateTable(); - helper.CreateTable(); - - scope.Complete(); - } - } - + [Test] public void Can_Create_cmsTags_Table() { diff --git a/src/Umbraco.Web/Models/RegisterModel.cs b/src/Umbraco.Web/Models/RegisterModel.cs index 971cb8b916..2851db54a4 100644 --- a/src/Umbraco.Web/Models/RegisterModel.cs +++ b/src/Umbraco.Web/Models/RegisterModel.cs @@ -25,7 +25,6 @@ namespace Umbraco.Web.Models private RegisterModel(bool doLookup) { MemberTypeAlias = Constants.Conventions.MemberTypes.DefaultAlias; - RedirectOnSucces = false; UsernameIsEmail = true; MemberProperties = new List(); LoginOnSuccess = true; @@ -69,11 +68,7 @@ namespace Umbraco.Web.Models /// [Required] public string Password { get; set; } - - [ReadOnly(true)] - [Obsolete("This is no longer used and will be removed from the codebase in future versions")] - public bool RedirectOnSucces { get; set; } - + /// /// The username of the model, if UsernameIsEmail is true then this is ignored. /// diff --git a/src/Umbraco.Web/Mvc/SurfaceControllerFactory.cs b/src/Umbraco.Web/Mvc/SurfaceControllerFactory.cs deleted file mode 100644 index abccbf648b..0000000000 --- a/src/Umbraco.Web/Mvc/SurfaceControllerFactory.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Web.Mvc; -using System.Web.Routing; - -namespace Umbraco.Web.Mvc -{ - /// - /// Creates SurfaceControllers - /// - [Obsolete("This is not used in the codebase and will be removed from the core in future versions")] - public class SurfaceControllerFactory : RenderControllerFactory - { - /// - /// Check if the correct data tokens are in the route values so that we know its a surface controller route - /// - /// - /// - public override bool CanHandle(RequestContext request) - { - var area = request.RouteData.DataTokens["area"]; - - //if its a non-area route don't handle, all surface controllers will be in the 'umbraco' area - if (area == null || string.IsNullOrWhiteSpace(area.ToString())) - return false; - - //ensure there is an umbraco token set - var umbracoToken = request.RouteData.DataTokens[Core.Constants.Web.UmbracoDataToken]; - if (umbracoToken == null || string.IsNullOrWhiteSpace(umbracoToken.ToString())) - return false; - - return true; - } - - /// - /// Create the controller - /// - /// - /// - /// - public override IController CreateController(RequestContext requestContext, string controllerName) - { - //first try to instantiate with the DependencyResolver, if that fails, try with the UmbracoContext as a param, if that fails try with no params. - var controllerType = GetControllerType(requestContext, controllerName); - if (controllerType == null) - throw new InvalidOperationException("Could not find a controller type for the controller name " + controllerName); - - object controllerObject; - try - { - controllerObject = DependencyResolver.Current.GetService(controllerType); - } - catch (Exception) - { - try - { - controllerObject = Activator.CreateInstance(controllerType, UmbracoContext.Current); - } - catch (Exception) - { - //if this throws an exception, we'll let it - controllerObject = Activator.CreateInstance(controllerType); - } - } - //if an exception is thrown here, we want it to be thrown as its an invalid cast. - return (IController)controllerObject; - } - } -} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index efb94856b9..8477662cae 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -471,7 +471,6 @@ - @@ -1058,7 +1057,6 @@ - @@ -1231,7 +1229,6 @@ Code - diff --git a/src/Umbraco.Web/_Legacy/Actions/ActionQuit.cs b/src/Umbraco.Web/_Legacy/Actions/ActionQuit.cs deleted file mode 100644 index 6e8fe64c4b..0000000000 --- a/src/Umbraco.Web/_Legacy/Actions/ActionQuit.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using Umbraco.Web.UI.Pages; - -namespace Umbraco.Web._Legacy.Actions -{ - /// - /// This action is invoked when a user logs out - /// - [Obsolete("This should not be used and will be removed from the codebase in future versions")] - public class ActionQuit : IAction - { - //create singleton -#pragma warning disable 612,618 - private static readonly ActionQuit m_instance = new ActionQuit(); -#pragma warning restore 612,618 - - /// - /// A public constructor exists ONLY for backwards compatibility in regards to 3rd party add-ons. - /// All Umbraco assemblies should use the singleton instantiation (this.Instance) - /// When this applicatio is refactored, this constuctor should be made private. - /// - [Obsolete("Use the singleton instantiation instead of a constructor")] - public ActionQuit() { } - - public static ActionQuit Instance - { - get { return m_instance; } - } - - #region IAction Members - - public char Letter - { - get - { - return 'Q'; - } - } - - public string JsFunctionName - { - get - { - return string.Format("{0}.actionQuit()", ClientTools.Scripts.GetAppActions); - } - } - - public string JsSource - { - get - { - return null; - } - } - - public string Alias - { - get - { - return "logout"; - } - } - - public string Icon - { - get - { - return "signout"; - } - } - - public bool ShowInNotifier - { - get - { - return false; - } - } - public bool CanBePermissionAssigned - { - get - { - return false; - } - } - #endregion - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentControl.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentControl.cs deleted file mode 100644 index 2619747074..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentControl.cs +++ /dev/null @@ -1,699 +0,0 @@ -//TODO: This needs a full rewrite in angular! kept here for reference for now - -//using System; -//using System.Collections; -//using System.Collections.Generic; -//using System.ComponentModel; -//using System.Globalization; -//using System.Linq; -//using System.Web; -//using System.Web.UI; -//using System.Web.UI.WebControls; -//using Umbraco.Core; -//using Umbraco.Core.Configuration; -//using Umbraco.Core.IO; -//using Umbraco.Core.Models; -// -//using umbraco.cms.businesslogic.web; -//using umbraco.interfaces; -//using Umbraco.Web._Legacy.Controls; -//using Content = umbraco.cms.businesslogic.Content; -//using ContentType = umbraco.cms.businesslogic.ContentType; -//using Media = umbraco.cms.businesslogic.media.Media; -//using Property = umbraco.cms.businesslogic.property.Property; -//using StylesheetProperty = umbraco.cms.businesslogic.web.StylesheetProperty; - -//namespace umbraco.controls -//{ -// public class ContentControlLoadEventArgs : CancelEventArgs { } - -// /// -// /// Summary description for ContentControl. -// /// -// public class ContentControl : TabView -// { - - -// internal Dictionary DataTypes = new Dictionary(); -// private readonly Content _content; -// private UmbracoEnsuredPage _prntpage; -// public event EventHandler SaveAndPublish; -// public event EventHandler SaveToPublish; -// public event EventHandler Save; -// private readonly publishModes _canPublish = publishModes.NoPublish; -// public TabPage tpProp; -// public bool DoesPublish = false; -// public TextBox NameTxt = new TextBox(); -// public PlaceHolder NameTxtHolder = new PlaceHolder(); -// public RequiredFieldValidator NameTxtValidator = new RequiredFieldValidator(); -// private readonly CustomValidator _nameTxtCustomValidator = new CustomValidator(); -// private static readonly string UmbracoPath = SystemDirectories.Umbraco; -// public Pane PropertiesPane = new Pane(); -// // zb-00036 #29889 : load it only once -// List _virtualTabs; -// //default to true! -// private bool _savePropertyDataWhenInvalid = true; -// private ContentType _contentType; - - -// public Content ContentObject -// { -// get { return _content; } -// } - -// /// -// /// This property controls whether the content property values are persisted even if validation -// /// fails. If set to false, then the values will not be persisted. -// /// -// /// -// /// This is required because when we are editing content we should be persisting invalid values to the database -// /// as this makes it easier for editors to come back and fix up their changes before they publish. Of course we -// /// don't publish if the page is invalid. In the case of media and members, we don't want to persist the values -// /// to the database when the page is invalid because there is no published state. -// /// Relates to: http://issues.umbraco.org/issue/U4-227 -// /// -// public bool SavePropertyDataWhenInvalid -// { -// get { return _savePropertyDataWhenInvalid; } -// set { _savePropertyDataWhenInvalid = value; } -// } - -// [Obsolete("This is no longer used and will be removed from the codebase in future versions")] -// private string _errorMessage = ""; - -// [Obsolete("This is no longer used and will be removed from the codebase in future versions")] -// public string ErrorMessage -// { -// set { _errorMessage = value; } -// } - -// [Obsolete("This is no longer used and will be removed from the codebase in future versions")] -// protected void standardSaveAndPublishHandler(object sender, EventArgs e) -// { -// } - - -// /// -// /// Constructor to set default properties. -// /// -// /// -// /// -// /// -// /// -// /// This method used to create all of the child controls too which is BAD since -// /// the page hasn't started initializing yet. Control IDs were not being named -// /// correctly, etc... I've moved the child control setup/creation to the CreateChildControls -// /// method where they are suposed to be. -// /// -// public ContentControl(Content c, publishModes CanPublish, string Id) -// { -// ID = Id; -// this._canPublish = CanPublish; -// _content = c; - -// Width = 350; -// Height = 350; - -// _prntpage = (UmbracoEnsuredPage)Page; - -// // zb-00036 #29889 : load it only once -// if (_virtualTabs == null) -// _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); - -// foreach (ContentType.TabI t in _virtualTabs) -// { -// TabPage tp = NewTabPage(t.Caption); -// AddSaveAndPublishButtons(ref tp); -// } -// } - -// /// -// /// Create and setup all of the controls child controls. -// /// -// protected override void CreateChildControls() -// { -// base.CreateChildControls(); - - -// _prntpage = (UmbracoEnsuredPage)Page; -// int i = 0; -// Hashtable inTab = new Hashtable(); - -// // zb-00036 #29889 : load it only once -// if (_virtualTabs == null) -// _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); - -// if(_contentType == null) -// _contentType = ContentType.GetContentType(_content.ContentType.Id); - -// foreach (ContentType.TabI tab in _virtualTabs) -// { -// var tabPage = this.Panels[i] as TabPage; -// if (tabPage == null) -// { -// throw new ArgumentException("Unable to load tab \"" + tab.Caption + "\""); -// } - -// tabPage.Style.Add("text-align", "center"); - -// //Legacy vs New API loading of PropertyTypes -// if (_contentType.ContentTypeItem != null) -// { -// LoadPropertyTypes(_contentType.ContentTypeItem, tabPage, inTab, tab.Id, tab.Caption); -// } -// else -// { -// LoadPropertyTypes(tab, tabPage, inTab); -// } - -// i++; -// } - -// // Add property pane -// tpProp = NewTabPage(Services.TextService.Localize("general/properties")); -// AddSaveAndPublishButtons(ref tpProp); -// tpProp.Controls.Add( -// new LiteralControl("
    There were errors - data has not been saved!
    ")); - -// //if the property is not in a tab, add it to the general tab -// var props = _content.GenericProperties; -// foreach (Property p in props.OrderBy(x => x.PropertyType.SortOrder)) -// { -// if (inTab[p.PropertyType.Id.ToString()] == null) -// AddControlNew(p, tpProp, Services.TextService.Localize("general/properties")); -// } - -// } - -// /// -// /// Loades PropertyTypes by Tab/PropertyGroup using the new API. -// /// -// /// -// /// -// /// -// /// -// /// -// private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption) -// { -// var propertyGroups = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId); -// var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple(y.Id, y.Alias, y.SortOrder))); -// foreach (var items in propertyTypeAliases) -// { -// var property = _content.getProperty(items.Item2); -// if (property != null) -// { -// AddControlNew(property, tabPage, tabCaption); - -// if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture))) -// inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true); -// } -// else -// { -// throw new ArgumentNullException( -// string.Format( -// "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", -// items.Item2, items.Item1, _content.ContentType.Alias, _content.Id, -// tabCaption)); -// } -// } -// } - -// /// -// /// Loades PropertyTypes by Tab using the Legacy API. -// /// -// /// -// /// -// /// -// private void LoadPropertyTypes(ContentType.TabI tab, TabPage tabPage, Hashtable inTab) -// { -// // Iterate through the property types and add them to the tab -// // zb-00036 #29889 : fix property types getter to get the right set of properties -// // ge : had a bit of a corrupt db and got weird NRE errors so rewrote this to catch the error and rethrow with detail -// var propertyTypes = tab.GetPropertyTypes(_content.ContentType.Id); -// foreach (var propertyType in propertyTypes.OrderBy(x => x.SortOrder)) -// { -// var property = _content.getProperty(propertyType); -// if (property != null && tabPage != null) -// { -// AddControlNew(property, tabPage, tab.Caption); - -// // adding this check, as we occasionally get an already in dictionary error, though not sure why -// if (!inTab.ContainsKey(propertyType.Id.ToString(CultureInfo.InvariantCulture))) -// inTab.Add(propertyType.Id.ToString(CultureInfo.InvariantCulture), true); -// } -// else -// { -// throw new ArgumentNullException( -// string.Format( -// "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", -// propertyType.Alias, propertyType.Id, _content.ContentType.Alias, _content.Id, tab.Caption)); -// } -// } -// } - -// /// -// /// Initializes the control and ensures child controls are setup -// /// -// /// -// protected override void OnInit(EventArgs e) -// { -// base.OnInit(e); - -// EnsureChildControls(); - -// // Add extras for the property tabpage. . -// ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); -// FireBeforeContentControlLoad(contentcontrolEvent); - -// if (!contentcontrolEvent.Cancel) -// { - -// NameTxt.ID = "NameTxt"; -// if (!Page.IsPostBack) -// { -// NameTxt.Text = _content.Text; -// } - -// // Name validation -// NameTxtValidator.ControlToValidate = NameTxt.ID; -// _nameTxtCustomValidator.ControlToValidate = NameTxt.ID; -// string[] errorVars = { Services.TextService.Localize("name") }; -// NameTxtValidator.ErrorMessage = " " + ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars) + "
    "; -// NameTxtValidator.EnableClientScript = false; -// NameTxtValidator.Display = ValidatorDisplay.Dynamic; -// _nameTxtCustomValidator.EnableClientScript = false; -// _nameTxtCustomValidator.Display = ValidatorDisplay.Dynamic; -// _nameTxtCustomValidator.ServerValidate += NameTxtCustomValidatorServerValidate; -// _nameTxtCustomValidator.ValidateEmptyText = false; - -// NameTxtHolder.Controls.Add(NameTxt); -// NameTxtHolder.Controls.Add(NameTxtValidator); -// NameTxtHolder.Controls.Add(_nameTxtCustomValidator); -// PropertiesPane.addProperty(Services.TextService.Localize("general/name"), NameTxtHolder); - -// Literal ltt = new Literal(); -// ltt.Text = _content.User.Name; -// PropertiesPane.addProperty(Services.TextService.Localize("content/createBy"), ltt); - -// ltt = new Literal(); -// ltt.Text = _content.CreateDateTime.ToString(); -// PropertiesPane.addProperty(Services.TextService.Localize("content/createDate"), ltt); - -// ltt = new Literal(); -// ltt.Text = _content.Id.ToString(); -// PropertiesPane.addProperty("Id", ltt); - -// if (_content is Media) -// { -// PropertiesPane.addProperty(Services.TextService.Localize("content/mediatype"), new LiteralControl(_content.ContentType.Alias)); -// } - -// tpProp.Controls.AddAt(0, PropertiesPane); -// tpProp.Style.Add("text-align", "center"); -// } -// } - -// /// -// /// Custom validates the content name field -// /// -// /// -// /// -// /// -// /// We need to ensure people are not entering XSS attacks on this field -// /// http://issues.umbraco.org/issue/U4-485 -// /// -// /// This doesn't actually 'validate' but changes the text field value and strips html -// /// -// void NameTxtCustomValidatorServerValidate(object source, ServerValidateEventArgs args) -// { -// NameTxt.Text = NameTxt.Text.StripHtml(); -// args.IsValid = true; -// } - -// protected override void OnLoad(EventArgs e) -// { -// base.OnLoad(e); - -// ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); -// FireAfterContentControlLoad(contentcontrolEvent); -// } - -// /// -// /// Sets the name (text) and values on the data types of the document -// /// -// private void SetNameAndDataTypeValues() -// { -// //we only continue saving anything if: -// // SavePropertyDataWhenInvalid == true -// // OR if the page is actually valid. -// if (SavePropertyDataWhenInvalid || Page.IsValid) -// { - -// foreach (var property in DataTypes) -// { -// var defaultData = property.Value.Data as DefaultData; -// if (defaultData != null) -// { -// defaultData.PropertyTypeAlias = property.Key; -// defaultData.NodeId = _content.Id; -// } -// property.Value.DataEditor.Save(); -// } - -// //don't update if the name is empty -// if (!NameTxt.Text.IsNullOrWhiteSpace()) -// { -// _content.Text = NameTxt.Text; -// } -// } -// } - -// private void SaveClick(object sender, ImageClickEventArgs e) -// { -// SetNameAndDataTypeValues(); - -// if (Save != null) -// { -// Save(this, new EventArgs()); -// } -// } - -// private void DoSaveAndPublish(object sender, ImageClickEventArgs e) -// { -// DoesPublish = true; - -// SetNameAndDataTypeValues(); - -// //NOTE: This is only here to keep backwards compatibility. -// // see: http://issues.umbraco.org/issue/U4-1660 -// Save(this, new EventArgs()); - -// if (SaveAndPublish != null) -// { -// SaveAndPublish(this, new EventArgs()); -// } -// } - -// private void DoSaveToPublish(object sender, ImageClickEventArgs e) -// { -// SaveClick(sender, e); -// if (SaveToPublish != null) -// { -// SaveToPublish(this, new EventArgs()); -// } -// } - -// private void AddSaveAndPublishButtons(ref TabPage tp) -// { -// MenuImageButton menuSave = tp.Menu.NewImageButton(); -// menuSave.ID = tp.ID + "_save"; -// menuSave.ImageUrl = UmbracoPath + "/images/editor/save.gif"; -// menuSave.Click += new ImageClickEventHandler(SaveClick); -// menuSave.OnClickCommand = "invokeSaveHandlers();"; -// menuSave.AltText = Services.TextService.Localize("buttons/save"); -// if (_canPublish == publishModes.Publish) -// { -// MenuImageButton menuPublish = tp.Menu.NewImageButton(); -// menuPublish.ID = tp.ID + "_publish"; -// menuPublish.ImageUrl = UmbracoPath + "/images/editor/saveAndPublish.gif"; -// menuPublish.OnClickCommand = "invokeSaveHandlers();"; -// menuPublish.Click += new ImageClickEventHandler(DoSaveAndPublish); -// menuPublish.AltText = Services.TextService.Localize("buttons/saveAndPublish"); -// } -// else if (_canPublish == publishModes.SendToPublish) -// { -// MenuImageButton menuToPublish = tp.Menu.NewImageButton(); -// menuToPublish.ID = tp.ID + "_topublish"; -// menuToPublish.ImageUrl = UmbracoPath + "/images/editor/saveToPublish.gif"; -// menuToPublish.OnClickCommand = "invokeSaveHandlers();"; -// menuToPublish.Click += new ImageClickEventHandler(DoSaveToPublish); -// menuToPublish.AltText = Services.TextService.Localize("buttons/saveToPublish"); -// } -// } - - -// private void AddControlNew(Property p, TabPage tp, string cap) -// { -// IDataType dt = p.PropertyType.DataTypeDefinition.DataType; - -// //check that property editor has been set for the data type used by this property -// if (dt != null) -// { -// dt.DataEditor.Editor.ID = string.Format("prop_{0}", p.PropertyType.Alias); - -// dt.Data.PropertyId = p.Id; - -// //Add the DataType to an internal dictionary, which will be used to call the save method on the IDataEditor -// //and to retrieve the value from IData in editContent.aspx.cs, so that it can be set on the legacy Document class. -// DataTypes.Add(p.PropertyType.Alias, dt); - -// // check for buttons -// IDataFieldWithButtons df1 = dt.DataEditor.Editor as IDataFieldWithButtons; -// if (df1 != null) -// { -// ((Control)df1).ID = p.PropertyType.Alias; - - -// if (df1.MenuIcons.Length > 0) -// tp.Menu.InsertSplitter(); - - -// // Add buttons -// int c = 0; -// bool atEditHtml = false; -// bool atSplitter = false; -// foreach (object o in df1.MenuIcons) -// { -// try -// { -// MenuIconI m = (MenuIconI)o; -// MenuIconI mi = tp.Menu.NewIcon(); -// mi.ImageURL = m.ImageURL; -// mi.OnClickCommand = m.OnClickCommand; -// mi.AltText = m.AltText; -// mi.ID = tp.ID + "_" + m.ID; - -// if (m.ID == "html") -// atEditHtml = true; -// else -// atEditHtml = false; - -// atSplitter = false; -// } -// catch -// { -// tp.Menu.InsertSplitter(); -// atSplitter = true; -// } - -// // Testing custom styles in editor -// if (atSplitter && atEditHtml && dt.DataEditor.TreatAsRichTextEditor) -// { -// DropDownList ddl = tp.Menu.NewDropDownList(); - -// ddl.Style.Add("margin-bottom", "5px"); -// ddl.Items.Add(Services.TextService.Localize("buttons/styleChoose")); -// ddl.ID = tp.ID + "_editorStyle"; -// if (StyleSheet.GetAll().Length > 0) -// { -// foreach (StyleSheet s in StyleSheet.GetAll()) -// { -// foreach (StylesheetProperty sp in s.Properties) -// { -// ddl.Items.Add(new ListItem(sp.Text, sp.Alias)); -// } -// } -// } -// ddl.Attributes.Add("onChange", "addStyle(this, '" + p.PropertyType.Alias + "');"); -// atEditHtml = false; -// } -// c++; -// } -// } - -// // check for element additions -// IMenuElement menuElement = dt.DataEditor.Editor as IMenuElement; -// if (menuElement != null) -// { -// // add separator -// tp.Menu.InsertSplitter(); - -// // add the element -// tp.Menu.NewElement(menuElement.ElementName, menuElement.ElementIdPreFix + p.Id.ToString(), -// menuElement.ElementClass, menuElement.ExtraMenuWidth); -// } - -// Pane pp = new Pane(); -// Control holder = new Control(); -// holder.Controls.Add(dt.DataEditor.Editor); -// if (p.PropertyType.DataTypeDefinition.DataType.DataEditor.ShowLabel) -// { -// string caption = p.PropertyType.Name; -// if (p.PropertyType.Description != null && p.PropertyType.Description != String.Empty) -// switch (UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption) -// { -// case "icon": -// caption += " \"""; -// break; -// case "text": -// caption += "
    " + umbraco.library.ReplaceLineBreaks(p.PropertyType.Description) + ""; -// break; -// } -// pp.addProperty(caption, holder); -// } -// else -// pp.addProperty(holder); - -// // Validation -// if (p.PropertyType.Mandatory) -// { -// try -// { -// var rq = new RequiredFieldValidator -// { -// ControlToValidate = dt.DataEditor.Editor.ID, -// CssClass = "error" -// }; -// rq.Style.Add(HtmlTextWriterStyle.Display, "block"); -// rq.Style.Add(HtmlTextWriterStyle.Padding, "2px"); -// var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); -// var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; -// PropertyDescriptor pd = null; -// if (attribute != null) -// { -// pd = TypeDescriptor.GetProperties(component, null)[attribute.Name]; -// } -// if (pd != null) -// { -// rq.EnableClientScript = false; -// rq.Display = ValidatorDisplay.Dynamic; -// string[] errorVars = { p.PropertyType.Name, cap }; -// rq.ErrorMessage = ui.Text("errorHandling", "errorMandatory", errorVars) + "
    "; -// holder.Controls.AddAt(0, rq); -// } -// } -// catch (Exception valE) -// { -// HttpContext.Current.Trace.Warn("contentControl", -// "EditorControl (" + dt.DataTypeName + ") does not support validation", -// valE); -// } -// } - -// // RegExp Validation -// if (p.PropertyType.ValidationRegExp != "") -// { -// try -// { -// var rv = new RegularExpressionValidator -// { -// ControlToValidate = dt.DataEditor.Editor.ID, -// CssClass = "error" -// }; -// rv.Style.Add(HtmlTextWriterStyle.Display, "block"); -// rv.Style.Add(HtmlTextWriterStyle.Padding, "2px"); -// var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); -// var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; -// PropertyDescriptor pd = null; -// if (attribute != null) -// { -// pd = TypeDescriptor.GetProperties(component, null)[attribute.Name]; -// } -// if (pd != null) -// { -// rv.ValidationExpression = p.PropertyType.ValidationRegExp; -// rv.EnableClientScript = false; -// rv.Display = ValidatorDisplay.Dynamic; -// string[] errorVars = { p.PropertyType.Name, cap }; -// rv.ErrorMessage = ui.Text("errorHandling", "errorRegExp", errorVars) + "
    "; -// holder.Controls.AddAt(0, rv); -// } -// } -// catch (Exception valE) -// { -// HttpContext.Current.Trace.Warn("contentControl", -// "EditorControl (" + dt.DataTypeName + ") does not support validation", -// valE); -// } -// } - -// // This is once again a nasty nasty hack to fix gui when rendering wysiwygeditor -// if (dt.DataEditor.TreatAsRichTextEditor) -// { -// tp.Controls.Add(dt.DataEditor.Editor); -// } -// else -// { -// Panel ph = new Panel(); -// ph.Attributes.Add("style", "padding: 0; position: relative;"); // NH 4.7.1, latest styles added to support CP item: 30363 -// ph.Controls.Add(pp); - -// tp.Controls.Add(ph); -// } -// } -// else -// { - -// var ph = new Panel(); - -// var pp = new Pane(); - -// var missingPropertyEditorLabel = new Literal -// { -// Text = Services.TextService.Localize("errors/missingPropertyEditorErrorMessage") -// }; - -// pp.addProperty(p.PropertyType.Name, missingPropertyEditorLabel); - -// ph.Attributes.Add("style", "padding: 0; position: relative;"); - -// ph.Controls.Add(pp); - -// tp.Controls.Add(ph); -// } - - -// } - -// public enum publishModes -// { -// Publish, -// SendToPublish, -// NoPublish -// } - -// // EVENTS -// public delegate void BeforeContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); -// public delegate void AfterContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); - - -// /// -// /// Occurs when [before content control load]. -// /// -// public static event BeforeContentControlLoadEventHandler BeforeContentControlLoad; -// /// -// /// Fires the before content control load. -// /// -// /// The instance containing the event data. -// protected virtual void FireBeforeContentControlLoad(ContentControlLoadEventArgs e) -// { -// if (BeforeContentControlLoad != null) -// BeforeContentControlLoad(this, e); -// } - -// /// -// /// Occurs when [before content control load]. -// /// -// public static event AfterContentControlLoadEventHandler AfterContentControlLoad; -// /// -// /// Fires the before content control load. -// /// -// /// The instance containing the event data. -// protected virtual void FireAfterContentControlLoad(ContentControlLoadEventArgs e) -// { -// if (AfterContentControlLoad != null) -// AfterContentControlLoad(this, e); -// } -// } -//} From 2afd2578382deb0cc794611157777d819b9b8406 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 01:55:40 +1000 Subject: [PATCH 55/58] more cleanup of unused files --- .../UmbracoSettings/umbracoSettings.config | 2 - src/Umbraco.Tests/UI/LegacyDialogTests.cs | 6 +- src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 1 - .../config/umbracoSettings.config | 5 - .../umbraco/controls/ProgressBar.ascx | 2 - src/Umbraco.Web/Umbraco.Web.csproj | 20 - .../umbraco/controls/ContentTypeControl.cs | 581 ------------------ .../umbraco/controls/ProgressBar.ascx | 2 - .../umbraco/controls/ProgressBar.ascx.cs | 23 - .../controls/ProgressBar.ascx.designer.cs | 15 - .../umbraco/controls/SaveClickEventArgs.cs | 30 - .../umbraco/create/CreatedPackageTasks.cs | 9 +- .../umbraco/create/StylesheetTasks.cs | 51 -- .../umbraco/create/language.ascx.cs | 91 --- .../umbraco/create/languageTasks.cs | 42 -- .../umbraco/create/macroTasks.cs | 2 +- .../umbraco/create/stylesheetPropertyTasks.cs | 58 -- 17 files changed, 8 insertions(+), 932 deletions(-) delete mode 100644 src/Umbraco.Web.UI/umbraco/controls/ProgressBar.ascx delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControl.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.designer.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/controls/SaveClickEventArgs.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/create/language.ascx.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/create/languageTasks.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config index f8d9e0b86e..c278a99e95 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config @@ -147,8 +147,6 @@ - true - true Mvc diff --git a/src/Umbraco.Tests/UI/LegacyDialogTests.cs b/src/Umbraco.Tests/UI/LegacyDialogTests.cs index 13503e4223..bcc3805c7b 100644 --- a/src/Umbraco.Tests/UI/LegacyDialogTests.cs +++ b/src/Umbraco.Tests/UI/LegacyDialogTests.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using umbraco; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Web; using Umbraco.Web._Legacy.UI; namespace Umbraco.Tests.UI @@ -21,13 +22,10 @@ namespace Umbraco.Tests.UI Assert.IsTrue(TypeHelper.IsTypeAssignableFrom(t), "The type " + t + " is not of type " + typeof(LegacyDialogTask)); } } - - [TestCase(typeof(StylesheetTasks), Constants.Applications.Settings)] - [TestCase(typeof(stylesheetPropertyTasks), Constants.Applications.Settings)] + [TestCase(typeof(MemberGroupTasks), Constants.Applications.Members)] [TestCase(typeof(dictionaryTasks), Constants.Applications.Settings)] [TestCase(typeof(macroTasks), Constants.Applications.Developer)] - [TestCase(typeof(languageTasks), Constants.Applications.Settings)] [TestCase(typeof(CreatedPackageTasks), Constants.Applications.Developer)] public void Check_Assigned_Apps_For_Tasks(Type taskType, string app) { diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 20f75c30d4..7dbced3167 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -395,7 +395,6 @@ - diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.config b/src/Umbraco.Web.UI/config/umbracoSettings.config index fc7bcad135..a809c1ef8c 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.config @@ -164,12 +164,7 @@ - - - true - - Mvc diff --git a/src/Umbraco.Web.UI/umbraco/controls/ProgressBar.ascx b/src/Umbraco.Web.UI/umbraco/controls/ProgressBar.ascx deleted file mode 100644 index 6331a3a293..0000000000 --- a/src/Umbraco.Web.UI/umbraco/controls/ProgressBar.ascx +++ /dev/null @@ -1,2 +0,0 @@ -<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ProgressBar.ascx.cs" Inherits="umbraco.presentation.umbraco.controls.ProgressBar" %> -<%#Services.TextService.Localize("publish/inProgress")%>
    \ No newline at end of file diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 8477662cae..0dd6ef73f1 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -799,9 +799,6 @@ ASPXCodeBehind - - ASPXCodeBehind - @@ -1230,16 +1227,7 @@ Code - - - ProgressBar.ascx - ASPXCodeBehind - - - ProgressBar.ascx - - ASPXCodeBehind @@ -1255,8 +1243,6 @@ - - FeedProxy.aspx ASPXCodeBehind @@ -1320,9 +1306,6 @@ Code - - Code - editPackage.aspx ASPXCodeBehind @@ -1523,9 +1506,6 @@ ASPXCodeBehind
    - - ASPXCodeBehind - ASPXCodeBehind diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControl.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControl.cs deleted file mode 100644 index fde87a7646..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControl.cs +++ /dev/null @@ -1,581 +0,0 @@ -//TODO: This needs a full rewrite in angular! kept here for reference for now - -//using System; -//using System.Web.UI.HtmlControls; -//using System.Web.UI.WebControls; -//using System.Collections; -//using System.ComponentModel; -//using System.IO; -//using Umbraco.Core.IO; -//using System.Linq; - -//namespace umbraco.controls -//{ -// /// -// /// Summary description for ContentTypeControl. -// /// -// [Obsolete("No longer used, will be removed in v8")] -// [EditorBrowsable(EditorBrowsableState.Never)] -// public class ContentTypeControl : Umbraco.Web._Legacy.Controls.TabView -// { -// public event System.EventHandler OnSave; -// public event System.EventHandler OnPropertyTypeCreate; -// public event System.EventHandler OnPropertyTypeDelete; -// private cms.businesslogic.ContentType docType; -// protected TextBox NameTxt = new TextBox(); -// protected TextBox AliasTxt = new TextBox(); -// protected DropDownList IconDDL = new DropDownList(); -// protected TextBox TabTxt = new TextBox(); -// protected Umbraco.Web._Legacy.Controls.Pane GenericPropertyTypes; -// private Umbraco.Web._Legacy.Controls.Pane TabsPane = new Umbraco.Web._Legacy.Controls.Pane(); -// private NodeTypeAddPropertyTypeControl AddPropertyTypeCtrl; -// private System.Collections.ArrayList tabDDLs = new ArrayList(); -// private HtmlGenericControl br = new HtmlGenericControl(); -// private NodeTypeEditorControl NodeTypeEditorCtrl; -// private Umbraco.Web._Legacy.Controls.Pane pp; -// private Umbraco.Web._Legacy.Controls.TabPage Panel1; -// private Umbraco.Web._Legacy.Controls.TabPage Panel2; -// private Umbraco.Web._Legacy.Controls.TabPage Panel3; -// private Umbraco.Web._Legacy.Controls.TabPage Panel4; -// private BasePages.BasePage prnt; -// private ListBox AllowedContentTypes; -// private ArrayList extraPropertyPanes = new ArrayList(); - -// public void addPropertyPaneToGeneralTab(Umbraco.Web._Legacy.Controls.Pane pp) { -// extraPropertyPanes.Add(pp); -// } -// public ContentTypeControl(cms.businesslogic.ContentType ct, string id) { -// this.ID = id; -// this.OnSave +=new EventHandler(tmp_OnSave); -// this.OnPropertyTypeCreate += new EventHandler(this.tmp_OnSave); -// this.OnPropertyTypeDelete += new EventHandler(this.tmp_OnSave); -// docType = ct; -// this.Width = Unit.Pixel(600); -// this.Height = Unit.Pixel(600); -// string UmbracoPath = SystemDirectories.Umbraco; -// Panel1 = this.NewTabPage("Generelt"); -// Umbraco.Web._Legacy.Controls.MenuImageButton Save = Panel1.Menu.NewImageButton(); -// Save.Click += new System.Web.UI.ImageClickEventHandler(save_click); -// Save.ID = "Panel1Save"; -// Save.ImageUrl = UmbracoPath + "/images/editor/save.gif"; - - -// Panel2 = this.NewTabPage("Faneblade"); -// Save = Panel2.Menu.NewImageButton(); -// Save.ID = "Panel2Save"; -// Save.Click += new System.Web.UI.ImageClickEventHandler(save_click); -// Save.ImageUrl = UmbracoPath + "/images/editor/save.gif"; - - -// Panel3 = this.NewTabPage("Struktur"); -// Save = Panel3.Menu.NewImageButton(); -// Save.ID = "Panel3Save"; -// Save.Click += new System.Web.UI.ImageClickEventHandler(save_click); -// Save.ImageUrl = UmbracoPath + "/images/editor/save.gif"; - -// Panel4 = this.NewTabPage("Generiske egenskaber"); -// Save = Panel4.Menu.NewImageButton(); -// Save.ID = "Panel4Save"; -// Save.Click += new System.Web.UI.ImageClickEventHandler(save_click); -// Save.ImageUrl = UmbracoPath + "/images/editor/save.gif"; - -// Panel1.Attributes.Add("align","center"); -// Panel2.Attributes.Add("align","center"); -// Panel3.Attributes.Add("align","center"); -// Panel4.Attributes.Add("align","center"); - -// br = new HtmlGenericControl(); -// br.TagName = "br"; -// Panel1.Controls.Add(br); - -// br = new HtmlGenericControl(); -// br.TagName = "br"; -// Panel2.Controls.Add(br); - -// br = new HtmlGenericControl(); -// br.TagName = "br"; -// Panel3.Controls.Add(br); - -// br = new HtmlGenericControl(); -// br.TagName = "br"; -// Panel4.Controls.Add(br); - -// } - -// protected void tmp_OnSave(object sender, System.EventArgs e) -// { - -// } - -// protected override void OnLoad(EventArgs e) -// { -// base.OnLoad (e); -// Page_Load(new object(), e); -// } - -// protected void Page_Load(object sender, System.EventArgs e) -// { -// prnt = (BasePages.BasePage) this.Page; -// // Setup tab 1 -// setupGeneralInfoTab(); -// setupTabTab(); -// setupGenericPropertyTypesTab(); - -// AllowedContentTypes = new ListBox(); -// AllowedContentTypes.ID = "AllowedContentTypes"; -// AllowedContentTypes.SelectionMode = ListSelectionMode.Multiple; - - -// int[] allowedIds = docType.AllowedChildContentTypeIDs; - -// foreach (cms.businesslogic.ContentType ct in docType.GetAll()) -// { -// ListItem li = new ListItem(ct.Text,ct.Id.ToString()); -// AllowedContentTypes.Items.Add(li); -// if (!Page.IsPostBack) -// {foreach (int i in allowedIds) if (i == ct.Id) li.Selected= true;} -// } - -// pp = new Umbraco.Web._Legacy.Controls.Pane(); -// pp.addProperty("Tilladte indholdstyper",AllowedContentTypes); -// Panel3.Controls.Add(pp); -// } - - - -// public void save_click(object sender, System.Web.UI.ImageClickEventArgs e) -// { -// OnSave(this, new System.EventArgs()); -// docType.Text = NameTxt.Text; -// docType.Alias = AliasTxt.Text; -// docType.IconUrl = IconDDL.SelectedValue; - - -// string xtra = ""; -// if (TabTxt.Text.Trim() != "") -// { -// docType.AddVirtualTab(TabTxt.Text); -// xtra = Services.TextService.Localize("speechBubbles/contentTypeTabCreated"); -// populateTabDDLs(); -// TabsPane.Controls.Clear(); -// LoadExistingTabsOnTabsPane(); -// TabTxt.Text = ""; -// } - -// // Save allowed ChildTypes -// SaveAllowedChildTypes(); - -// NodeTypeEditorCtrl.Save(); -// prnt.ClientTools.ShowSpeechBubble( BasePages.BasePage.SpeechBubbleIcon.Save, Services.TextService.Localize("speechBubbles/contentTypeSavedHeader"),"" + xtra); -// } - -// private void SaveAllowedChildTypes() { -// ArrayList tmp = new ArrayList(); -// foreach (ListItem li in AllowedContentTypes.Items) -// { -// if (li.Selected) -// tmp.Add(int.Parse(li.Value)); -// } -// int[] ids = new int[tmp.Count]; -// for (int i = 0;i = 0) selVal = ddl.SelectedValue; - -// ddl.Items.Clear(); -// foreach (cms.businesslogic.web.DocumentType.TabI t in docType.getVirtualTabs.ToList()) -// { -// ListItem li = new ListItem(); -// li.Text = t.Caption; -// li.Value = t.Id.ToString(); -// ddl.Items.Add(li); -// } -// ddl.Items.Add(new ListItem("Egenskaber","0")); -// try -// { -// ddl.SelectedValue = selVal; -// } -// catch -// { -// this.Page.Trace.Warn("Tab could not be selected"); -// } -// } -// } - - -// #endregion - -// #region "Custom controls" -// private class NodeTypeAddPropertyTypeControl : System.Web.UI.HtmlControls.HtmlTable -// { -// private TextBox NameTxt = new TextBox(); -// private TextBox AliasTxt = new TextBox(); -// private DropDownList DataTypeDDL = new DropDownList(); -// public DropDownList TabDDL = new DropDownList(); -// private cms.businesslogic.ContentType _dt; -// private ContentTypeControl ctctrl; -// public NodeTypeAddPropertyTypeControl(cms.businesslogic.ContentType dt, ContentTypeControl parent) -// { -// ctctrl = parent; -// this.Attributes.Add("width","100%"); -// HtmlTableRow tr = new HtmlTableRow(); -// HtmlTableCell td = new HtmlTableCell(); -// td.InnerText = "Alias"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Navn"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Type"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Fane"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// tr.Cells.Add(td); - -// this.Rows.Add(tr); -// tr = new HtmlTableRow(); - -// td = new HtmlTableCell(); -// td.Controls.Add(AliasTxt); -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.Controls.Add(NameTxt); -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.Controls.Add(DataTypeDDL); -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.Controls.Add(TabDDL); -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// Button btn = new Button(); - -// td.Controls.Add(btn); -// btn.Text = "Opret"; -// tr.Cells.Add(td); -// this.Rows.Add(tr); - -// // Add create new PropertyType eventhandler -// btn.Click += new System.EventHandler(this.AddPropertyType); - - -// foreach (cms.businesslogic.ContentType.TabI t in dt.getVirtualTabs.ToList()) -// { -// ListItem li = new ListItem(); -// li.Value = t.Id.ToString(); -// li.Text = t.Caption; -// TabDDL.Items.Add(li); -// } -// ListItem lie = new ListItem(); -// lie.Text = "Egenskaber"; -// lie.Value = "0"; -// TabDDL.Items.Add(lie); - -// foreach(cms.businesslogic.datatype.DataTypeDefinition DataType in cms.businesslogic.datatype.DataTypeDefinition.GetAll()) -// { -// ListItem li = new ListItem(); -// li.Value = DataType.Id.ToString(); -// li.Text = DataType.Text; -// DataTypeDDL.Items.Add(li); -// } -// _dt = dt; -// } - - -// private void AddPropertyType(object sender, System.EventArgs e) -// { - -// if (NameTxt.Text.Trim() != "" && AliasTxt.Text.Trim() != "") -// { -// string[] info = {NameTxt.Text, DataTypeDDL.SelectedItem.Value}; -// ctctrl.prnt.ClientTools.ShowSpeechBubble(BasePages.BasePage.speechBubbleIcon.info, Services.TextService.Localize("speechBubbles/contentTypePropertyTypeCreated"), ui.Text("speechBubbles", "contentTypePropertyTypeCreatedText", info)); -// _dt.AddPropertyType(cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(int.Parse(DataTypeDDL.SelectedValue)),AliasTxt.Text,NameTxt.Text); - -// if (int.Parse(TabDDL.SelectedValue) != 0) -// { -// _dt.SetTabOnPropertyType(_dt.getPropertyType(AliasTxt.Text),int.Parse(TabDDL.SelectedValue)); -// } -// ctctrl.GenericPropertyTypes.Controls.Clear(); -// ctctrl.loadGenericPropertyTypesOnPane(); -// NameTxt.Text = ""; -// AliasTxt.Text = ""; -// // fire event to tell that a new propertytype is created!! -// ctctrl.OnPropertyTypeCreate(this, new System.EventArgs()); -// } -// else -// { - -// ctctrl.prnt.ClientTools.ShowSpeechBubble(BasePages.BasePage.speechBubbleIcon.error, Services.TextService.Localize("error"), Services.TextService.Localize("errors/contentTypeAliasAndNameNotNull")); -// } -// } -// } - - -// private class NodeTypeEditorControl : System.Web.UI.HtmlControls.HtmlTable -// { -// private System.Collections.ArrayList PropertyTypes = new System.Collections.ArrayList(); -// private ContentTypeControl prnt; -// public NodeTypeEditorControl(ContentTypeControl parent) -// { -// prnt = parent; -// this.Attributes.Add("width","100%"); -// HtmlTableRow tr = new HtmlTableRow(); -// HtmlTableCell td = new HtmlTableCell(); -// td.InnerText = "Alias"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Navn"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Type"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = "Fane"; -// tr.Cells.Add(td); - -// td = new HtmlTableCell(); -// tr.Cells.Add(td); - -// this.Rows.Add(tr); - -// cms.businesslogic.ContentType.TabI[] tbs = prnt.docType.getVirtualTabs; - - -// foreach (cms.businesslogic.propertytype.PropertyType pt in prnt.docType.PropertyTypes) -// { -// editor e = new editor(pt,prnt); -// PropertyTypes.Add(e); -// this.Controls.Add(e); -// } - -// } - -// public string Save() -// { - -// foreach (editor e in PropertyTypes) -// { -// e.save(); -// } -// return "2 egenskabstyper �ndret"; -// } - - - -// private class editor : System.Web.UI.HtmlControls.HtmlTableRow -// { -// private DropDownList TabDDL = new DropDownList(); -// private cms.businesslogic.propertytype.PropertyType pt; -// ContentTypeControl ent; -// public editor(cms.businesslogic.propertytype.PropertyType pt,ContentTypeControl parent) -// { -// this.pt = pt; -// ent = parent; -// } - -// protected override void OnLoad(EventArgs e) -// { -// base.OnLoad (e); - - -// ent.tabDDLs.Add(TabDDL); - -// foreach (cms.businesslogic.ContentType.TabI t in ent.docType.getVirtualTabs.ToList()) -// TabDDL.Items.Add(new ListItem(t.Caption,t.Id.ToString())); -// TabDDL.Items.Add(new ListItem("Egenskaber","0")); -// if (!Parent.Page.IsPostBack) -// { -// int tabID = cms.businesslogic.ContentType.getTabIdFromPropertyType(pt); -// TabDDL.SelectedValue = tabID.ToString(); -// } - -// HtmlTableCell td = new HtmlTableCell(); - -// td.InnerText = pt.Alias; -// this.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = pt.Name; -// this.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.InnerText = pt.DataTypeDefinition.Text; -// this.Cells.Add(td); - -// td = new HtmlTableCell(); -// td.Controls.Add(TabDDL); -// this.Cells.Add(td); - -// td = new HtmlTableCell(); -// Button btn = new Button(); -// btn.Text = "Slet"; -// btn.ID = "propertytype" + pt.Id; -// btn.Click += new EventHandler(deletepropertytype_click); - -// td.Controls.Add(btn); -// this.Cells.Add(td); -// } - -// public void deletepropertytype_click(object sender, System.EventArgs e) -// { -// Button s = (Button) sender; -// int propertytypeId = int.Parse(s.ID.Replace("propertytype","")); -// cms.businesslogic.propertytype.PropertyType.GetPropertyType(propertytypeId).delete(); - -// ent.GenericPropertyTypes.Controls.Clear(); -// ent.loadGenericPropertyTypesOnPane(); - -// BasePages.BasePage bp = (BasePages.BasePage) this.Page; -// bp.ClientTools.ShowSpeechBubble(BasePages.BasePage.speechBubbleIcon.info, Services.TextService.Localize("speechBubbles/contentTypePropertyTypeDeleted"), ""); -// ent.OnPropertyTypeDelete(this, new System.EventArgs()); -// } - -// public void save() -// { -// if (int.Parse(TabDDL.SelectedValue) > 0) -// { -// ent.docType.SetTabOnPropertyType(pt,int.Parse(TabDDL.SelectedValue)); -// } -// else -// { -// ent.docType.removePropertyTypeFromTab(pt); -// } -// } -// } -// } - -// #endregion - -// } -//} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx deleted file mode 100644 index 7b4a239210..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx +++ /dev/null @@ -1,2 +0,0 @@ -<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ProgressBar.ascx.cs" Inherits="umbraco.presentation.umbraco.controls.ProgressBar" %> -<%#Services.TextService.Localize("publish/inProgress")%>
    diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.cs deleted file mode 100644 index 9c39639785..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.UI; -using System.Web.UI.WebControls; - -namespace umbraco.presentation.umbraco.controls -{ - public partial class ProgressBar : System.Web.UI.UserControl - { - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - EnableViewState = false; - } - - protected void Page_Load(object sender, EventArgs e) - { - DataBind(); - } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.designer.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.designer.cs deleted file mode 100644 index 8c9893a1d6..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ProgressBar.ascx.designer.cs +++ /dev/null @@ -1,15 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace umbraco.presentation.umbraco.controls { - - - public partial class ProgressBar { - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/SaveClickEventArgs.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/SaveClickEventArgs.cs deleted file mode 100644 index 239125f137..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/SaveClickEventArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.IO; -using System; -using System.Data; -using System.Drawing; -using System.Web; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.Collections; -using System.Web.UI; -using ClientDependency.Core; -using Umbraco.Core.IO; -using umbraco.presentation; -using System.Collections.Generic; -using System.Linq; -using Umbraco.Web.UI; - -namespace umbraco.controls -{ - public class SaveClickEventArgs : EventArgs - { - public string Message { get; set; } - public SpeechBubbleIcon IconType { get; set; } - - public SaveClickEventArgs(string message) - { - Message = message; - IconType = SpeechBubbleIcon.Success; - } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs index c8888288b8..149cac110a 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/CreatedPackageTasks.cs @@ -4,8 +4,9 @@ using Umbraco.Core; using Umbraco.Web; using Umbraco.Web.Composing; using Umbraco.Web._Legacy.UI; - -namespace umbraco +using umbraco.cms.businesslogic.packager; + +namespace Umbraco.Web { public class CreatedPackageTasks : LegacyDialogTask { @@ -13,7 +14,7 @@ namespace umbraco public override bool PerformSave() { Current.Logger.Info("Xml save started"); - int id = cms.businesslogic.packager.CreatedPackage.MakeNew(Alias).Data.Id; + int id = CreatedPackage.MakeNew(Alias).Data.Id; _returnUrl = string.Format("developer/packages/editPackage.aspx?id={0}", id); return true; } @@ -25,7 +26,7 @@ namespace umbraco { ParentID = int.Parse(Alias.Substring("package_".Length)); } - cms.businesslogic.packager.CreatedPackage.GetById(ParentID).Delete(); + CreatedPackage.GetById(ParentID).Delete(); return true; } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs deleted file mode 100644 index 2a2d34303e..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Web; -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web.UI; -using Umbraco.Web._Legacy.UI; - -namespace umbraco -{ - public class StylesheetTasks : LegacyDialogTask - { - public override bool PerformSave() - { - //normalize path - Alias = Alias.Replace("/", "\\"); - - var sheet = Current.Services.FileService.GetStylesheetByName(Alias); - if (sheet == null) - { - sheet = new Stylesheet(Alias.EnsureEndsWith(".css")); - Current.Services.FileService.SaveStylesheet(sheet); - } - - _returnUrl = string.Format("settings/stylesheet/editStylesheet.aspx?id={0}", HttpUtility.UrlEncode(sheet.Path)); - return true; - } - - public override bool PerformDelete() - { - //var s = cms.businesslogic.web.StyleSheet.GetByName(Alias); - var s = Current.Services.FileService.GetStylesheetByName(Alias); - //s.delete(); - if (s!=null) - Current.Services.FileService.DeleteStylesheet(s.Path); - return true; - } - - private string _returnUrl = ""; - - public override string ReturnUrl - { - get { return _returnUrl; } - } - - public override string AssignedApp - { - get { return Constants.Applications.Settings.ToString(); } - } - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/language.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/language.ascx.cs deleted file mode 100644 index 9e3b16e7a3..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/language.ascx.cs +++ /dev/null @@ -1,91 +0,0 @@ -using Umbraco.Core.Services; -using System; -using System.Collections; -using System.Globalization; -using System.Web; -using System.Web.UI.WebControls; -using Umbraco.Web.UI; -using Umbraco.Web; -using Umbraco.Web._Legacy.UI; - -namespace umbraco.cms.presentation.create.controls -{ - /// - /// Summary description for language. - /// - public partial class language : global::Umbraco.Web.UI.Controls.UmbracoUserControl - { - protected void Page_Load(object sender, EventArgs e) - { - // get all existing languages - - pp1.Text = Services.TextService.Localize("choose") + " " + Services.TextService.Localize("language"); - sbmt.Text = Services.TextService.Localize("create"); - - var sortedCultures = new SortedList(); - Cultures.Items.Clear(); - Cultures.Items.Add(new ListItem(Services.TextService.Localize("choose") + "...", "")); - foreach (var cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures)) - sortedCultures.Add(cultureInfo.DisplayName + "|||" + Guid.NewGuid(), cultureInfo.Name); - - var dictionaryEnumerator = sortedCultures.GetEnumerator(); - while (dictionaryEnumerator.MoveNext()) - { - var language = dictionaryEnumerator.Key.ToString().Substring(0, dictionaryEnumerator.Key.ToString().IndexOf("|||", StringComparison.Ordinal)); - var listItem = new ListItem(string.Format("{0} [{1}]", language, dictionaryEnumerator.Value), dictionaryEnumerator.Value.ToString()); - Cultures.Items.Add(listItem); - } - } - - protected void sbmt_Click(object sender, EventArgs e) - { - LegacyDialogHandler.Create( - new HttpContextWrapper(Context), - Security.CurrentUser, - Request.GetItemAsString("nodeType"), - -1, - Cultures.SelectedValue); - - ClientTools - .ReloadActionNode(false, true) - .CloseModalWindow(); - } - - /// - /// pp1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.PropertyPanel pp1; - - /// - /// Cultures control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList Cultures; - - /// - /// RequiredFieldValidator1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; - - /// - /// sbmt control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Button sbmt; - - } -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/languageTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/languageTasks.cs deleted file mode 100644 index d50949311a..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/languageTasks.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Globalization; -using Umbraco.Web.UI; -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Web.Composing; -using Umbraco.Web._Legacy.UI; - -namespace umbraco -{ - public class languageTasks : LegacyDialogTask - { - - public override bool PerformSave() - { - //cms.businesslogic.language.Language.MakeNew(Alias); - var culture = new CultureInfo(Alias); - var l = new Language(Alias) { CultureName = culture.DisplayName }; - Current.Services.LocalizationService.Save(l); - return true; - } - - public override bool PerformDelete() - { - //new cms.businesslogic.language.Language(ParentID).Delete(); - var l = Current.Services.LocalizationService.GetLanguageById(ParentID); - if (l != null) - Current.Services.LocalizationService.Delete(l); - return false; - } - - public override string ReturnUrl - { - get { return string.Empty; } - } - - public override string AssignedApp - { - get { return Constants.Applications.Settings.ToString(); } - } - } - -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs index 79a203355a..2b34bb0d04 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs @@ -3,7 +3,7 @@ using Umbraco.Core.Models; using Umbraco.Web.Composing; using Umbraco.Web._Legacy.UI; -namespace umbraco +namespace Umbraco.Web { public class macroTasks : LegacyDialogTask { diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs deleted file mode 100644 index 3697e09da3..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Linq; -using System.Web; -using Umbraco.Core; -using Umbraco.Core.Models; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web.UI; -using Umbraco.Web._Legacy.UI; - -namespace umbraco -{ - public class stylesheetPropertyTasks : LegacyDialogTask - { - public override bool PerformSave() - { - var stylesheetName = AdditionalValues["nodeId"].ToString(); - - var s = Current.Services.FileService.GetStylesheetByName(stylesheetName.EnsureEndsWith(".css")); - s.AddProperty(new StylesheetProperty(Alias, "." + Alias.ToSafeAlias(), "")); - Current.Services.FileService.SaveStylesheet(s); - - // SJ - Note: The Alias is NOT in fact the alias but the name of the new property, need to UrlEncode it! - _returnUrl = string.Format("settings/stylesheet/property/EditStyleSheetProperty.aspx?id={0}&prop={1}", HttpUtility.UrlEncode(s.Path), HttpUtility.UrlEncode(Alias)); - return true; - } - - public override bool PerformDelete() - { - var parts = Alias.Split('_'); - - var stylesheet = Current.Services.FileService.GetStylesheetByName(parts[0].EnsureEndsWith(".css")); - if (stylesheet == null) throw new InvalidOperationException("No stylesheet found by name: " + parts[0]); - - var property = HttpUtility.UrlDecode(parts[1]); - var prop = stylesheet.Properties.FirstOrDefault(x => x.Name == property); - if (prop == null) throw new InvalidOperationException("No stylesheet property found by name: " + property); - - stylesheet.RemoveProperty(prop.Name); - - Current.Services.FileService.SaveStylesheet(stylesheet); - - return true; - } - - private string _returnUrl = ""; - - public override string ReturnUrl - { - get { return _returnUrl; } - } - - public override string AssignedApp - { - get { return Constants.Applications.Settings.ToString(); } - } - } -} From 1bdf064437762a721527424d606441ad521f310a Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 10:39:04 +1000 Subject: [PATCH 56/58] Removes the DistributedCall section along with CacheRefresher and the ConfigServerRegistrar, changes IServerMessenger to not have any servers parameters since we don't use that. --- .../UmbracoSettings/DistributedCallElement.cs | 48 --- .../IDistributedCallSection.cs | 13 - .../Configuration/UmbracoSettings/IServer.cs | 12 - .../IUmbracoSettingsSection.cs | 2 - .../UmbracoSettings/ServerCollection.cs | 31 -- .../UmbracoSettings/ServerElement.cs | 49 --- .../UmbracoSettings/UmbracoSettingsSection.cs | 14 +- src/Umbraco.Core/IO/FileSystems.cs | 2 +- .../Runtime/CoreRuntimeComponent.cs | 5 +- src/Umbraco.Core/RuntimeState.cs | 14 +- src/Umbraco.Core/Sync/ApplicationUrlHelper.cs | 8 +- .../Sync/BatchedWebServiceServerMessenger.cs | 81 ---- src/Umbraco.Core/Sync/ConfigServerAddress.cs | 32 -- .../Sync/ConfigServerRegistrar.cs | 93 ----- .../Sync/DatabaseServerMessenger.cs | 3 +- .../Sync/DatabaseServerRegistrarOptions.cs | 7 +- src/Umbraco.Core/Sync/IServerMessenger.cs | 27 +- .../Sync/RefreshInstructionEnvelope.cs | 4 +- src/Umbraco.Core/Sync/ServerMessengerBase.cs | 95 ++--- .../Sync/WebServiceServerMessenger.cs | 383 ------------------ src/Umbraco.Core/Umbraco.Core.csproj | 9 - .../Cache/CacheRefresherTests.cs | 29 -- .../DistributedCache/DistributedCacheTests.cs | 20 +- .../Composing/TypeFinderTests.cs | 2 +- .../Composing/TypeLoaderTests.cs | 4 +- .../DistributedCallElementDefaultTests.cs | 27 -- .../DistributedCallElementTests.cs | 32 -- .../UmbracoSettings/umbracoSettings.config | 21 - .../umbracoSettings.minimal.config | 6 - .../IO/AbstractFileSystemTests.cs | 8 +- .../Integration/ContentEventsTests.cs | 16 +- src/Umbraco.Tests/Macros/MacroTests.cs | 1 - .../Misc/ApplicationUrlHelperTests.cs | 222 +++------- .../Routing/UmbracoModuleTests.cs | 17 +- .../Scoping/ScopedRepositoryTests.cs | 2 +- src/Umbraco.Tests/Scoping/ScopedXmlTests.cs | 2 +- .../TestHelpers/SettingsForTests.cs | 2 - src/Umbraco.Tests/Umbraco.Tests.csproj | 3 - src/Umbraco.Web.UI/Umbraco.Web.UI.csproj | 3 - .../config/umbracoSettings.Release.config | 44 -- .../config/umbracoSettings.config | 45 -- .../umbraco/webservices/CacheRefresher.asmx | 1 - .../BatchedDatabaseServerMessenger.cs | 7 +- .../BatchedWebServiceServerMessenger.cs | 78 ---- src/Umbraco.Web/Cache/DistributedCache.cs | 9 - ...aseServerRegistrarAndMessengerComponent.cs | 5 - ...acyServerRegistrarAndMessengerComponent.cs | 52 --- src/Umbraco.Web/Umbraco.Web.csproj | 9 - src/Umbraco.Web/UmbracoModule.cs | 2 +- .../umbraco/webservices/CacheRefresher.asmx | 1 - .../webservices/CacheRefresher.asmx.cs | 192 --------- 51 files changed, 166 insertions(+), 1628 deletions(-) delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/DistributedCallElement.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/IDistributedCallSection.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/IServer.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/ServerCollection.cs delete mode 100644 src/Umbraco.Core/Configuration/UmbracoSettings/ServerElement.cs delete mode 100644 src/Umbraco.Core/Sync/BatchedWebServiceServerMessenger.cs delete mode 100644 src/Umbraco.Core/Sync/ConfigServerAddress.cs delete mode 100644 src/Umbraco.Core/Sync/ConfigServerRegistrar.cs delete mode 100644 src/Umbraco.Core/Sync/WebServiceServerMessenger.cs delete mode 100644 src/Umbraco.Tests/Cache/CacheRefresherTests.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementDefaultTests.cs delete mode 100644 src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementTests.cs delete mode 100644 src/Umbraco.Web.UI/umbraco/webservices/CacheRefresher.asmx delete mode 100644 src/Umbraco.Web/BatchedWebServiceServerMessenger.cs delete mode 100644 src/Umbraco.Web/Components/LegacyServerRegistrarAndMessengerComponent.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/DistributedCallElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/DistributedCallElement.cs deleted file mode 100644 index af035d2e0e..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/DistributedCallElement.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class DistributedCallElement : ConfigurationElement, IDistributedCallSection - { - [ConfigurationProperty("enable", DefaultValue = false)] - internal bool Enabled - { - get { return (bool)base["enable"]; } - } - - [ConfigurationProperty("user")] - internal InnerTextConfigurationElement UserId - { - get - { - return new OptionalInnerTextConfigurationElement( - (InnerTextConfigurationElement)this["user"], - //set the default - 0); - } - } - - [ConfigurationCollection(typeof(ServerCollection), AddItemName = "server")] - [ConfigurationProperty("servers", IsDefaultCollection = true)] - internal ServerCollection Servers - { - get { return (ServerCollection)base["servers"]; } - } - - bool IDistributedCallSection.Enabled - { - get { return Enabled; } - } - - int IDistributedCallSection.UserId - { - get { return UserId; } - } - - IEnumerable IDistributedCallSection.Servers - { - get { return Servers; } - } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IDistributedCallSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IDistributedCallSection.cs deleted file mode 100644 index 96f695c8c7..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IDistributedCallSection.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Collections.Generic; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IDistributedCallSection : IUmbracoConfigurationSection - { - bool Enabled { get; } - - int UserId { get; } - - IEnumerable Servers { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IServer.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IServer.cs deleted file mode 100644 index 26b1db056e..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IServer.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - public interface IServer - { - string ForcePortnumber { get; } - string ForceProtocol { get; } - string ServerAddress { get; } - - string AppId { get; } - string ServerName { get; } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs index 1776f1cbf2..09cc698756 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/IUmbracoSettingsSection.cs @@ -19,8 +19,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings IScheduledTasksSection ScheduledTasks { get; } - IDistributedCallSection DistributedCall { get; } - IProvidersSection Providers { get; } IWebRoutingSection WebRouting { get; } diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ServerCollection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ServerCollection.cs deleted file mode 100644 index dfaa5c5247..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ServerCollection.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Collections.Generic; -using System.Configuration; - -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ServerCollection : ConfigurationElementCollection, IEnumerable - { - protected override ConfigurationElement CreateNewElement() - { - return new ServerElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((ServerElement)element).Value; - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (var i = 0; i < Count; i++) - { - yield return BaseGet(i) as IServer; - } - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ServerElement.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ServerElement.cs deleted file mode 100644 index 30c836bc07..0000000000 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ServerElement.cs +++ /dev/null @@ -1,49 +0,0 @@ -namespace Umbraco.Core.Configuration.UmbracoSettings -{ - internal class ServerElement : InnerTextConfigurationElement, IServer - { - public string ForcePortnumber - { - get - { - return RawXml.Attribute("forcePortnumber") == null - ? null - : RawXml.Attribute("forcePortnumber").Value; - } - } - - public string ForceProtocol - { - get - { - return RawXml.Attribute("forceProtocol") == null - ? null - : RawXml.Attribute("forceProtocol").Value; - } - } - - string IServer.ServerAddress - { - get { return Value; } - } - - public string AppId - { - get - { - return RawXml.Attribute("appId") == null - ? null - : RawXml.Attribute("appId").Value; - } - } - public string ServerName - { - get - { - return RawXml.Attribute("serverName") == null - ? null - : RawXml.Attribute("serverName").Value; - } - } - } -} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs index 3b76a43c39..7a08ec3b18 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/UmbracoSettingsSection.cs @@ -50,13 +50,6 @@ namespace Umbraco.Core.Configuration.UmbracoSettings get { return (ScheduledTasksElement)this["scheduledTasks"]; } } - [ConfigurationProperty("distributedCall")] - internal DistributedCallElement DistributedCall - { - get { return (DistributedCallElement)this["distributedCall"]; } - } - - [ConfigurationProperty("providers")] internal ProvidersElement Providers { @@ -103,12 +96,7 @@ namespace Umbraco.Core.Configuration.UmbracoSettings { get { return ScheduledTasks; } } - - IDistributedCallSection IUmbracoSettingsSection.DistributedCall - { - get { return DistributedCall; } - } - + IProvidersSection IUmbracoSettingsSection.Providers { get { return Providers; } diff --git a/src/Umbraco.Core/IO/FileSystems.cs b/src/Umbraco.Core/IO/FileSystems.cs index 2366bde7e2..33989122b8 100644 --- a/src/Umbraco.Core/IO/FileSystems.cs +++ b/src/Umbraco.Core/IO/FileSystems.cs @@ -354,7 +354,7 @@ namespace Umbraco.Core.IO if (Volatile.Read(ref _wkfsInitialized) == false) EnsureWellKnownFileSystems(); var typed = _wrappers.ToArray(); - var wrappers = new ShadowWrapper[typed.Length + 7]; + var wrappers = new ShadowWrapper[typed.Length + 6]; var i = 0; while (i < typed.Length) wrappers[i] = typed[i++]; wrappers[i++] = _macroPartialFileSystem; diff --git a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs index fbcc9a74cc..a90d5b5b4c 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs @@ -71,12 +71,9 @@ namespace Umbraco.Core.Runtime composition.Container.RegisterSingleton(); composition.Container.RegisterSingleton(); - // register a server registrar, by default it's the db registrar unless the dev - // has the legacy dist calls enabled - fixme - should obsolete the legacy thing + // register a server registrar, by default it's the db registrar composition.Container.RegisterSingleton(f => { - if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled) - return new ConfigServerRegistrar(f.GetInstance(), f.GetInstance(), f.GetInstance()); if ("true".InvariantEquals(ConfigurationManager.AppSettings["umbracoDisableElectionForSingleServer"])) return new SingleServerRegistrar(f.GetInstance()); return new DatabaseServerRegistrar( diff --git a/src/Umbraco.Core/RuntimeState.cs b/src/Umbraco.Core/RuntimeState.cs index a1401e035a..53a474cef7 100644 --- a/src/Umbraco.Core/RuntimeState.cs +++ b/src/Umbraco.Core/RuntimeState.cs @@ -19,6 +19,8 @@ namespace Umbraco.Core private readonly ILogger _logger; private readonly Lazy _serverRegistrar; private readonly Lazy _mainDom; + private readonly IUmbracoSettingsSection _settings; + private readonly IGlobalSettings _globalSettings; private readonly HashSet _applicationUrls = new HashSet(); private RuntimeLevel _level; @@ -28,11 +30,13 @@ namespace Umbraco.Core /// A logger. /// A (lazy) server registrar. /// A (lazy) MainDom. - public RuntimeState(ILogger logger, Lazy serverRegistrar, Lazy mainDom) + public RuntimeState(ILogger logger, Lazy serverRegistrar, Lazy mainDom, IUmbracoSettingsSection settings, IGlobalSettings globalSettings) { _logger = logger; _serverRegistrar = serverRegistrar; _mainDom = mainDom; + _settings = settings; + _globalSettings = globalSettings; } private IServerRegistrar ServerRegistrar => _serverRegistrar.Value; @@ -103,15 +107,13 @@ namespace Umbraco.Core /// /// Ensures that the property has a value. /// - /// /// - /// - internal void EnsureApplicationUrl(IUmbracoSettingsSection settings, IGlobalSettings globalSettings, HttpRequestBase request = null) + internal void EnsureApplicationUrl(HttpRequestBase request = null) { // see U4-10626 - in some cases we want to reset the application url // (this is a simplified version of what was in 7.x) // note: should this be optional? is it expensive? - var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request, globalSettings); + var url = request == null ? null : ApplicationUrlHelper.GetApplicationUrlFromCurrentRequest(request, _globalSettings); var change = url != null && !_applicationUrls.Contains(url); if (change) { @@ -120,7 +122,7 @@ namespace Umbraco.Core } if (ApplicationUrl != null && !change) return; - ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, globalSettings, settings, request)); + ApplicationUrl = new Uri(ApplicationUrlHelper.GetApplicationUrl(_logger, _globalSettings, _settings, ServerRegistrar, request)); } private readonly ManualResetEventSlim _runLevel = new ManualResetEventSlim(false); diff --git a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs index 691a325eaa..4628271625 100644 --- a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs +++ b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs @@ -29,9 +29,9 @@ namespace Umbraco.Core.Sync // FIXME need another way to do it, eg an interface, injected! public static Func ApplicationUrlProvider { get; set; } - internal static string GetApplicationUrl(ILogger logger, IGlobalSettings globalSettings, IUmbracoSettingsSection settings, HttpRequestBase request = null) + internal static string GetApplicationUrl(ILogger logger, IGlobalSettings globalSettings, IUmbracoSettingsSection settings, IServerRegistrar serverRegistrar, HttpRequestBase request = null) { - var umbracoApplicationUrl = TryGetApplicationUrl(settings, logger, globalSettings); + var umbracoApplicationUrl = TryGetApplicationUrl(settings, logger, globalSettings, serverRegistrar); if (umbracoApplicationUrl != null) return umbracoApplicationUrl; @@ -50,7 +50,7 @@ namespace Umbraco.Core.Sync return umbracoApplicationUrl; } - internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings) + internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings, IServerRegistrar serverRegistrar) { // try umbracoSettings:settings/web.routing/@umbracoApplicationUrl // which is assumed to: @@ -88,7 +88,7 @@ namespace Umbraco.Core.Sync // - contain a scheme // - end or not with a slash, it will be taken care of // eg "http://www.mysite.com/umbraco" - url = Current.ServerRegistrar.GetCurrentServerUmbracoApplicationUrl(); + url = serverRegistrar.GetCurrentServerUmbracoApplicationUrl(); if (url.IsNullOrWhiteSpace() == false) { var umbracoApplicationUrl = url.TrimEnd('/'); diff --git a/src/Umbraco.Core/Sync/BatchedWebServiceServerMessenger.cs b/src/Umbraco.Core/Sync/BatchedWebServiceServerMessenger.cs deleted file mode 100644 index a0357111d1..0000000000 --- a/src/Umbraco.Core/Sync/BatchedWebServiceServerMessenger.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Umbraco.Core.Cache; - -namespace Umbraco.Core.Sync -{ - /// - /// An that works by messaging servers via web services. - /// - /// - /// Abstract because it needs to be inherited by a class that will - /// - implement ProcessBatch() - /// - trigger FlushBatch() when appropriate - /// - internal abstract class BatchedWebServiceServerMessenger : WebServiceServerMessenger - { - internal BatchedWebServiceServerMessenger() - { - } - - internal BatchedWebServiceServerMessenger(string login, string password) - : base(login, password) - { - } - - internal BatchedWebServiceServerMessenger(string login, string password, bool useDistributedCalls) - : base(login, password, useDistributedCalls) - { - } - - protected BatchedWebServiceServerMessenger(Func> getLoginAndPassword) - : base(getLoginAndPassword) - { - } - - protected abstract ICollection GetBatch(bool ensureHttpContext); - - protected void FlushBatch() - { - var batch = GetBatch(false); - if (batch == null) return; - - var batcha = batch.ToArray(); - batch.Clear(); - if (batcha.Length == 0) return; - - ProcessBatch(batcha); - } - - // needs to be overriden to actually do something - protected abstract void ProcessBatch(RefreshInstructionEnvelope[] batch); - - protected override void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) - { - var idsA = ids == null ? null : ids.ToArray(); - - Type arrayType; - if (GetArrayType(idsA, out arrayType) == false) - throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids"); - - BatchMessage(servers, refresher, messageType, idsA, arrayType, json); - } - - protected void BatchMessage( - IEnumerable servers, - ICacheRefresher refresher, - MessageType messageType, - IEnumerable ids = null, - Type idType = null, - string json = null) - { - var batch = GetBatch(true); - if (batch == null) - throw new Exception("Failed to get a batch."); - - batch.Add(new RefreshInstructionEnvelope(servers, refresher, - RefreshInstruction.GetInstructions(refresher, messageType, ids, idType, json))); - } - } -} diff --git a/src/Umbraco.Core/Sync/ConfigServerAddress.cs b/src/Umbraco.Core/Sync/ConfigServerAddress.cs deleted file mode 100644 index be00544344..0000000000 --- a/src/Umbraco.Core/Sync/ConfigServerAddress.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; - -namespace Umbraco.Core.Sync -{ - /// - /// Provides the address of a server based on the Xml configuration. - /// - internal class ConfigServerAddress : IServerAddress - { - public ConfigServerAddress(IServer n, IGlobalSettings globalSettings) - { - var webServicesUrl = IOHelper.ResolveUrl(SystemDirectories.WebServices); - - var protocol = globalSettings.UseHttps ? "https" : "http"; - if (n.ForceProtocol.IsNullOrWhiteSpace() == false) - protocol = n.ForceProtocol; - var domain = n.ServerAddress; - if (n.ForcePortnumber.IsNullOrWhiteSpace() == false) - domain += $":{n.ForcePortnumber}"; - ServerAddress = $"{protocol}://{domain}{webServicesUrl}/cacheRefresher.asmx"; - } - - public string ServerAddress { get; private set; } - - public override string ToString() - { - return ServerAddress; - } - } -} diff --git a/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs b/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs deleted file mode 100644 index 83e085b324..0000000000 --- a/src/Umbraco.Core/Sync/ConfigServerRegistrar.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Web; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; - -namespace Umbraco.Core.Sync -{ - /// - /// Provides server registrations to the distributed cache by reading the legacy Xml configuration - /// in umbracoSettings to get the list of (manually) configured server nodes. - /// - internal class ConfigServerRegistrar : IServerRegistrar - { - private readonly List _addresses; - private readonly ServerRole _serverRole; - private readonly string _umbracoApplicationUrl; - - public ConfigServerRegistrar(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings) - : this(settings.DistributedCall, logger, globalSettings) - { } - - // for tests - internal ConfigServerRegistrar(IDistributedCallSection settings, ILogger logger, IGlobalSettings globalSettings) - { - if (settings.Enabled == false) - { - _addresses = new List(); - _serverRole = ServerRole.Single; - _umbracoApplicationUrl = null; // unspecified - return; - } - - var serversA = settings.Servers.ToArray(); - - _addresses = serversA - .Select(x => new ConfigServerAddress(x, globalSettings)) - .Cast() - .ToList(); - - if (serversA.Length == 0) - { - _serverRole = ServerRole.Unknown; // config error, actually - logger.Debug("Server Role Unknown: DistributedCalls are enabled but no servers are listed."); - } - else - { - var master = serversA[0]; // first one is master - var appId = master.AppId; - var serverName = master.ServerName; - - if (appId.IsNullOrWhiteSpace() && serverName.IsNullOrWhiteSpace()) - { - _serverRole = ServerRole.Unknown; // config error, actually - logger.Debug("Server Role Unknown: Server Name or AppId missing from Server configuration in DistributedCalls settings."); - } - else - { - _serverRole = IsCurrentServer(appId, serverName) - ? ServerRole.Master - : ServerRole.Slave; - } - } - - var currentServer = serversA.FirstOrDefault(x => IsCurrentServer(x.AppId, x.ServerName)); - if (currentServer != null) - { - // match, use the configured url - // ReSharper disable once UseStringInterpolation - _umbracoApplicationUrl = string.Format("{0}://{1}:{2}/{3}", - currentServer.ForceProtocol.IsNullOrWhiteSpace() ? "http" : currentServer.ForceProtocol, - currentServer.ServerAddress, - currentServer.ForcePortnumber.IsNullOrWhiteSpace() ? "80" : currentServer.ForcePortnumber, - IOHelper.ResolveUrl(SystemDirectories.Umbraco).TrimStart('/')); - } - } - - private static bool IsCurrentServer(string appId, string serverName) - { - // match by appId or computer name - return (appId.IsNullOrWhiteSpace() == false && appId.Trim().InvariantEquals(HttpRuntime.AppDomainAppId)) - || (serverName.IsNullOrWhiteSpace() == false && serverName.Trim().InvariantEquals(NetworkHelper.MachineName)); - } - - public IEnumerable Registrations => _addresses; - - public ServerRole GetCurrentServerRole() => _serverRole; - - public string GetCurrentServerUmbracoApplicationUrl() => _umbracoApplicationUrl; - } -} diff --git a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs index 0fcb7036f7..a1b89e58bc 100644 --- a/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs +++ b/src/Umbraco.Core/Sync/DatabaseServerMessenger.cs @@ -71,7 +71,7 @@ namespace Umbraco.Core.Sync #region Messenger - protected override bool RequiresDistributed(IEnumerable servers, ICacheRefresher refresher, MessageType dispatchType) + protected override bool RequiresDistributed(ICacheRefresher refresher, MessageType dispatchType) { // we don't care if there's servers listed or not, // if distributed call is enabled we will make the call @@ -79,7 +79,6 @@ namespace Umbraco.Core.Sync } protected override void DeliverRemote( - IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, diff --git a/src/Umbraco.Core/Sync/DatabaseServerRegistrarOptions.cs b/src/Umbraco.Core/Sync/DatabaseServerRegistrarOptions.cs index 6f019e7104..58b66ca8e6 100644 --- a/src/Umbraco.Core/Sync/DatabaseServerRegistrarOptions.cs +++ b/src/Umbraco.Core/Sync/DatabaseServerRegistrarOptions.cs @@ -14,14 +14,9 @@ namespace Umbraco.Core.Sync public DatabaseServerRegistrarOptions() { StaleServerTimeout = TimeSpan.FromMinutes(2); // 2 minutes - ThrottleSeconds = 30; // 30 seconds RecurringSeconds = 60; // do it every minute } - - [Obsolete("This is no longer used")] - [EditorBrowsable(EditorBrowsableState.Never)] - public int ThrottleSeconds { get; set; } - + /// /// The amount of seconds to wait between calls to the database on the background thread /// diff --git a/src/Umbraco.Core/Sync/IServerMessenger.cs b/src/Umbraco.Core/Sync/IServerMessenger.cs index 1df4ce9710..b3e5ef862d 100644 --- a/src/Umbraco.Core/Sync/IServerMessenger.cs +++ b/src/Umbraco.Core/Sync/IServerMessenger.cs @@ -13,78 +13,69 @@ namespace Umbraco.Core.Sync /// /// Notifies the distributed cache, for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// The notification content. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, TPayload[] payload); + void PerformRefresh(ICacheRefresher refresher, TPayload[] payload); /// /// Notifies the distributed cache, for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// The notification content. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, string jsonPayload); + void PerformRefresh(ICacheRefresher refresher, string jsonPayload); /// /// Notifies the distributed cache of specifieds item invalidation, for a specified . /// /// The type of the invalidated items. - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// A function returning the unique identifier of items. /// The invalidated items. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances); + void PerformRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances); /// /// Notifies the distributed cache of specifieds item invalidation, for a specified . /// /// The type of the invalidated items. - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// A function returning the unique identifier of items. /// The invalidated items. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getGuidId, params T[] instances); + void PerformRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances); /// /// Notifies all servers of specified items removal, for a specified . /// /// The type of the removed items. - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// A function returning the unique identifier of items. /// The removed items. - void PerformRemove(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances); + void PerformRemove(ICacheRefresher refresher, Func getNumericId, params T[] instances); /// /// Notifies all servers of specified items removal, for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// The unique identifiers of the removed items. - void PerformRemove(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds); + void PerformRemove(ICacheRefresher refresher, params int[] numericIds); /// /// Notifies all servers of specified items invalidation, for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// The unique identifiers of the invalidated items. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds); + void PerformRefresh(ICacheRefresher refresher, params int[] numericIds); /// /// Notifies all servers of specified items invalidation, for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. /// The unique identifiers of the invalidated items. - void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params Guid[] guidIds); + void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds); /// /// Notifies all servers of a global invalidation for a specified . /// - /// The servers that compose the load balanced environment. /// The ICacheRefresher. - void PerformRefreshAll(IEnumerable servers, ICacheRefresher refresher); + void PerformRefreshAll(ICacheRefresher refresher); } } diff --git a/src/Umbraco.Core/Sync/RefreshInstructionEnvelope.cs b/src/Umbraco.Core/Sync/RefreshInstructionEnvelope.cs index ac51e14a30..9cd442da2d 100644 --- a/src/Umbraco.Core/Sync/RefreshInstructionEnvelope.cs +++ b/src/Umbraco.Core/Sync/RefreshInstructionEnvelope.cs @@ -9,14 +9,12 @@ namespace Umbraco.Core.Sync /// public sealed class RefreshInstructionEnvelope { - public RefreshInstructionEnvelope(IEnumerable servers, ICacheRefresher refresher, IEnumerable instructions) + public RefreshInstructionEnvelope(ICacheRefresher refresher, IEnumerable instructions) { - Servers = servers; Refresher = refresher; Instructions = instructions; } - public IEnumerable Servers { get; set; } public ICacheRefresher Refresher { get; set; } public IEnumerable Instructions { get; set; } } diff --git a/src/Umbraco.Core/Sync/ServerMessengerBase.cs b/src/Umbraco.Core/Sync/ServerMessengerBase.cs index d16c88eca3..68223a40e6 100644 --- a/src/Umbraco.Core/Sync/ServerMessengerBase.cs +++ b/src/Umbraco.Core/Sync/ServerMessengerBase.cs @@ -27,9 +27,9 @@ namespace Umbraco.Core.Sync /// The cache refresher. /// The message type. /// true if distributed calls are required; otherwise, false, all we have is the local server. - protected virtual bool RequiresDistributed(IEnumerable servers, ICacheRefresher refresher, MessageType messageType) + protected virtual bool RequiresDistributed(ICacheRefresher refresher, MessageType messageType) { - return DistributedEnabled && servers.Any(); + return DistributedEnabled; } // ensures that all items in the enumerable are of the same type, either int or Guid. @@ -56,98 +56,97 @@ namespace Umbraco.Core.Sync #region IServerMessenger - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, TPayload[] payload) + public void PerformRefresh(ICacheRefresher refresher, TPayload[] payload) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (payload == null) throw new ArgumentNullException(nameof(payload)); - Deliver(servers, refresher, payload); + Deliver(refresher, payload); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, string jsonPayload) + public void PerformRefresh(ICacheRefresher refresher, string jsonPayload) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (jsonPayload == null) throw new ArgumentNullException(nameof(jsonPayload)); - Deliver(servers, refresher, MessageType.RefreshByJson, json: jsonPayload); + Deliver(refresher, MessageType.RefreshByJson, json: jsonPayload); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances) + public void PerformRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getNumericId == null) throw new ArgumentNullException(nameof(getNumericId)); if (instances == null || instances.Length == 0) return; Func getId = x => getNumericId(x); - Deliver(servers, refresher, MessageType.RefreshByInstance, getId, instances); + Deliver(refresher, MessageType.RefreshByInstance, getId, instances); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getGuidId, params T[] instances) + public void PerformRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getGuidId == null) throw new ArgumentNullException(nameof(getGuidId)); if (instances == null || instances.Length == 0) return; Func getId = x => getGuidId(x); - Deliver(servers, refresher, MessageType.RefreshByInstance, getId, instances); + Deliver(refresher, MessageType.RefreshByInstance, getId, instances); } - public void PerformRemove(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances) + public void PerformRemove(ICacheRefresher refresher, Func getNumericId, params T[] instances) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (getNumericId == null) throw new ArgumentNullException(nameof(getNumericId)); if (instances == null || instances.Length == 0) return; Func getId = x => getNumericId(x); - Deliver(servers, refresher, MessageType.RemoveByInstance, getId, instances); + Deliver(refresher, MessageType.RemoveByInstance, getId, instances); } - public void PerformRemove(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds) + public void PerformRemove(ICacheRefresher refresher, params int[] numericIds) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (numericIds == null || numericIds.Length == 0) return; - Deliver(servers, refresher, MessageType.RemoveById, numericIds.Cast()); + Deliver(refresher, MessageType.RemoveById, numericIds.Cast()); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds) + public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (numericIds == null || numericIds.Length == 0) return; - Deliver(servers, refresher, MessageType.RefreshById, numericIds.Cast()); + Deliver(refresher, MessageType.RefreshById, numericIds.Cast()); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params Guid[] guidIds) + public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); if (guidIds == null || guidIds.Length == 0) return; - Deliver(servers, refresher, MessageType.RefreshById, guidIds.Cast()); + Deliver(refresher, MessageType.RefreshById, guidIds.Cast()); } - public void PerformRefreshAll(IEnumerable servers, ICacheRefresher refresher) + public void PerformRefreshAll(ICacheRefresher refresher) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - Deliver(servers, refresher, MessageType.RefreshAll); + Deliver(refresher, MessageType.RefreshAll); } - //public void PerformNotify(IEnumerable servers, ICacheRefresher refresher, object payload) + //public void PerformNotify(ICacheRefresher refresher, object payload) //{ // if (servers == null) throw new ArgumentNullException("servers"); // if (refresher == null) throw new ArgumentNullException("refresher"); - // Deliver(servers, refresher, payload); + // Deliver(refresher, payload); //} #endregion @@ -283,61 +282,57 @@ namespace Umbraco.Core.Sync // refresher.Notify(payload); //} - protected abstract void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null); + protected abstract void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null); - //protected abstract void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, object payload); + //protected abstract void DeliverRemote(ICacheRefresher refresher, object payload); - protected virtual void Deliver(IEnumerable servers, ICacheRefresher refresher, TPayload[] payload) + protected virtual void Deliver(ICacheRefresher refresher, TPayload[] payload) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - var serversA = servers.ToArray(); - // deliver local DeliverLocal(refresher, payload); // distribute? - if (RequiresDistributed(serversA, refresher, MessageType.RefreshByJson) == false) + if (RequiresDistributed(refresher, MessageType.RefreshByJson) == false) return; // deliver remote var json = JsonConvert.SerializeObject(payload); - DeliverRemote(serversA, refresher, MessageType.RefreshByJson, null, json); + DeliverRemote(refresher, MessageType.RefreshByJson, null, json); } - protected virtual void Deliver(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) + protected virtual void Deliver(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - var serversA = servers.ToArray(); var idsA = ids?.ToArray(); // deliver local DeliverLocal(refresher, messageType, idsA, json); // distribute? - if (RequiresDistributed(serversA, refresher, messageType) == false) + if (RequiresDistributed(refresher, messageType) == false) return; // deliver remote - DeliverRemote(serversA, refresher, messageType, idsA, json); + DeliverRemote(refresher, messageType, idsA, json); } - protected virtual void Deliver(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, Func getId, IEnumerable instances) + protected virtual void Deliver(ICacheRefresher refresher, MessageType messageType, Func getId, IEnumerable instances) { - if (servers == null) throw new ArgumentNullException(nameof(servers)); + if (refresher == null) throw new ArgumentNullException(nameof(refresher)); - var serversA = servers.ToArray(); var instancesA = instances.ToArray(); // deliver local DeliverLocal(refresher, messageType, getId, instancesA); // distribute? - if (RequiresDistributed(serversA, refresher, messageType) == false) + if (RequiresDistributed(refresher, messageType) == false) return; // deliver remote @@ -349,10 +344,10 @@ namespace Umbraco.Core.Sync // convert instances to identifiers var idsA = instancesA.Select(getId).ToArray(); - DeliverRemote(serversA, refresher, messageType, idsA); + DeliverRemote(refresher, messageType, idsA); } - //protected virtual void Deliver(IEnumerable servers, ICacheRefresher refresher, object payload) + //protected virtual void Deliver(ICacheRefresher refresher, object payload) //{ // if (servers == null) throw new ArgumentNullException("servers"); // if (refresher == null) throw new ArgumentNullException("refresher"); diff --git a/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs b/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs deleted file mode 100644 index dff839fe6f..0000000000 --- a/src/Umbraco.Core/Sync/WebServiceServerMessenger.cs +++ /dev/null @@ -1,383 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Net; -using System.Threading; -using Newtonsoft.Json; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; -using Umbraco.Core.Cache; -using Umbraco.Core.Composing; - -namespace Umbraco.Core.Sync -{ - /// - /// An that works by messaging servers via web services. - /// - /// - /// this messenger sends ALL instructions to ALL servers, including the local server. - /// the CacheRefresher web service will run ALL instructions, so there may be duplicated, - /// except for "bulk" refresh, where it excludes those coming from the local server - /// - // - // TODO see Message() method: stop sending to local server! - // just need to figure out WebServerUtility permissions issues, if any - // - internal class WebServiceServerMessenger : ServerMessengerBase - { - private readonly Func> _getLoginAndPassword; - private volatile bool _hasLoginAndPassword; - private readonly object _locker = new object(); - - protected string Login { get; private set; } - protected string Password{ get; private set; } - - /// - /// Initializes a new instance of the class. - /// - /// Distribution is disabled. - internal WebServiceServerMessenger() - : base(false) - { } - - /// - /// Initializes a new instance of the class with a login and a password. - /// - /// The login. - /// The password. - /// Distribution will be enabled based on the umbraco config setting. - internal WebServiceServerMessenger(string login, string password) - : this(login, password, UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled) - { - } - - /// - /// Initializes a new instance of the class with a login and a password - /// and a value indicating whether distribution is enabled. - /// - /// The login. - /// The password. - /// A value indicating whether distribution is enabled. - internal WebServiceServerMessenger(string login, string password, bool distributedEnabled) - : base(distributedEnabled) - { - if (login == null) throw new ArgumentNullException("login"); - if (password == null) throw new ArgumentNullException("password"); - - Login = login; - Password = password; - } - - /// - /// Initializes a new instance of the with a function providing - /// a login and a password. - /// - /// A function providing a login and a password. - /// Distribution will be enabled based on the umbraco config setting. - public WebServiceServerMessenger(Func> getLoginAndPassword) - : base(false) // value will be overriden by EnsureUserAndPassword - { - _getLoginAndPassword = getLoginAndPassword; - } - - // lazy-get the login, password, and distributed setting - protected void EnsureLoginAndPassword() - { - if (_hasLoginAndPassword || _getLoginAndPassword == null) return; - - lock (_locker) - { - if (_hasLoginAndPassword) return; - _hasLoginAndPassword = true; - - try - { - var result = _getLoginAndPassword(); - if (result == null) - { - Login = null; - Password = null; - DistributedEnabled = false; - } - else - { - Login = result.Item1; - Password = result.Item2; - DistributedEnabled = UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled; - } - } - catch (Exception ex) - { - Current.Logger.Error("Could not resolve username/password delegate, server distribution will be disabled", ex); - Login = null; - Password = null; - DistributedEnabled = false; - } - } - } - - // this exists only for legacy reasons - we should just pass the server identity un-hashed - public static string GetCurrentServerHash() - { - if (SystemUtilities.GetCurrentTrustLevel() != System.Web.AspNetHostingPermissionLevel.Unrestricted) - throw new NotSupportedException("FullTrust ASP.NET permission level is required."); - return GetServerHash(NetworkHelper.MachineName, System.Web.HttpRuntime.AppDomainAppId); - } - - public static string GetServerHash(string machineName, string appDomainAppId) - { - using (var generator = new HashGenerator()) - { - generator.AddString(machineName); - generator.AddString(appDomainAppId); - return generator.GenerateHash(); - } - } - - protected override bool RequiresDistributed(IEnumerable servers, ICacheRefresher refresher, MessageType messageType) - { - EnsureLoginAndPassword(); - return base.RequiresDistributed(servers, refresher, messageType); - } - - protected override void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) - { - var idsA = ids == null ? null : ids.ToArray(); - - Type arrayType; - if (GetArrayType(idsA, out arrayType) == false) - throw new ArgumentException("All items must be of the same type, either int or Guid.", "ids"); - - Message(servers, refresher, messageType, idsA, arrayType, json); - } - - protected virtual void Message( - IEnumerable servers, - ICacheRefresher refresher, - MessageType messageType, - IEnumerable ids = null, - Type idArrayType = null, - string jsonPayload = null) - { - Current.Logger.Debug(() => - $"Performing distributed call for {refresher.GetType()}/{messageType} on servers ({string.Join(";", servers.Select(x => x.ToString()))}), ids: {(ids == null ? "" : string.Join(";", ids.Select(x => x.ToString())))}, json: {(jsonPayload ?? "")}"); - - try - { - // NOTE: we are messaging ALL servers including the local server - // at the moment, the web service, - // for bulk (batched) checks the origin and does NOT process the instructions again - // for anything else, processes the instructions again (but we don't use this anymore, batched is the default) - // TODO: see WebServerHelper, could remove local server from the list of servers - - // the default server messenger uses http requests - using (var client = new ServerSyncWebServiceClient()) - { - var asyncResults = new List(); - - LogStartDispatch(); - - // go through each configured node submitting a request asynchronously - // NOTE: 'asynchronously' in this case does not mean that it will continue while we give the page back to the user! - foreach (var n in servers) - { - // set the server address - client.Url = n.ServerAddress; - - // add the returned WaitHandle to the list for later checking - switch (messageType) - { - case MessageType.RefreshByJson: - asyncResults.Add(client.BeginRefreshByJson(refresher.RefresherUniqueId, jsonPayload, Login, Password, null, null)); - break; - - case MessageType.RefreshAll: - asyncResults.Add(client.BeginRefreshAll(refresher.RefresherUniqueId, Login, Password, null, null)); - break; - - case MessageType.RefreshById: - if (idArrayType == null) - throw new InvalidOperationException("Cannot refresh by id if the idArrayType is null."); - - if (idArrayType == typeof(int)) - { - // bulk of ints is supported - var json = JsonConvert.SerializeObject(ids.Cast().ToArray()); - var result = client.BeginRefreshByIds(refresher.RefresherUniqueId, json, Login, Password, null, null); - asyncResults.Add(result); - } - else // must be guids - { - // bulk of guids is not supported, iterate - asyncResults.AddRange(ids.Select(i => - client.BeginRefreshByGuid(refresher.RefresherUniqueId, (Guid)i, Login, Password, null, null))); - } - - break; - case MessageType.RemoveById: - if (idArrayType == null) - throw new InvalidOperationException("Cannot remove by id if the idArrayType is null."); - - // must be ints - asyncResults.AddRange(ids.Select(i => - client.BeginRemoveById(refresher.RefresherUniqueId, (int)i, Login, Password, null, null))); - break; - } - } - - // wait for all requests to complete - var waitHandles = asyncResults.Select(x => x.AsyncWaitHandle); - WaitHandle.WaitAll(waitHandles.ToArray()); - - // handle results - var errorCount = 0; - foreach (var asyncResult in asyncResults) - { - try - { - switch (messageType) - { - case MessageType.RefreshByJson: - client.EndRefreshByJson(asyncResult); - break; - - case MessageType.RefreshAll: - client.EndRefreshAll(asyncResult); - break; - - case MessageType.RefreshById: - if (idArrayType == typeof(int)) - client.EndRefreshById(asyncResult); - else - client.EndRefreshByGuid(asyncResult); - break; - - case MessageType.RemoveById: - client.EndRemoveById(asyncResult); - break; - } - } - catch (WebException ex) - { - LogDispatchNodeError(ex); - errorCount++; - } - catch (Exception ex) - { - LogDispatchNodeError(ex); - errorCount++; - } - } - - LogDispatchBatchResult(errorCount); - } - } - catch (Exception ee) - { - LogDispatchBatchError(ee); - } - } - - protected virtual void Message(IEnumerable envelopes) - { - var envelopesA = envelopes.ToArray(); - var servers = envelopesA.SelectMany(x => x.Servers).Distinct(); - - try - { - // NOTE: we are messaging ALL servers including the local server - // at the moment, the web service, - // for bulk (batched) checks the origin and does NOT process the instructions again - // for anything else, processes the instructions again (but we don't use this anymore, batched is the default) - // TODO: see WebServerHelper, could remove local server from the list of servers - - using (var client = new ServerSyncWebServiceClient()) - { - var asyncResults = new List(); - - LogStartDispatch(); - - // go through each configured node submitting a request asynchronously - // NOTE: 'asynchronously' in this case does not mean that it will continue while we give the page back to the user! - foreach (var server in servers) - { - // set the server address - client.Url = server.ServerAddress; - - var serverInstructions = envelopesA - .Where(x => x.Servers.Contains(server)) - .SelectMany(x => x.Instructions) - .Distinct() // only execute distinct instructions - no sense in running the same one. - .ToArray(); - - asyncResults.Add( - client.BeginBulkRefresh( - serverInstructions, - GetCurrentServerHash(), - Login, Password, null, null)); - } - - // wait for all requests to complete - var waitHandles = asyncResults.Select(x => x.AsyncWaitHandle).ToArray(); - WaitHandle.WaitAll(waitHandles.ToArray()); - - // handle results - var errorCount = 0; - foreach (var asyncResult in asyncResults) - { - try - { - client.EndBulkRefresh(asyncResult); - } - catch (WebException ex) - { - LogDispatchNodeError(ex); - errorCount++; - } - catch (Exception ex) - { - LogDispatchNodeError(ex); - errorCount++; - } - } - LogDispatchBatchResult(errorCount); - } - } - catch (Exception ee) - { - LogDispatchBatchError(ee); - } - } - - #region Logging - - private static void LogDispatchBatchError(Exception ee) - { - Current.Logger.Error("Error refreshing distributed list", ee); - } - - private static void LogDispatchBatchResult(int errorCount) - { - Current.Logger.Debug(string.Format("Distributed server push completed with {0} nodes reporting an error", errorCount == 0 ? "no" : errorCount.ToString(CultureInfo.InvariantCulture))); - } - - private static void LogDispatchNodeError(Exception ex) - { - Current.Logger.Error("Error refreshing a node in the distributed list", ex); - } - - private static void LogDispatchNodeError(WebException ex) - { - string url = (ex.Response != null) ? ex.Response.ResponseUri.ToString() : "invalid url (responseUri null)"; - Current.Logger.Error("Error refreshing a node in the distributed list, URI attempted: " + url, ex); - } - - private static void LogStartDispatch() - { - Current.Logger.Info("Submitting calls to distributed servers"); - } - - #endregion - } -} diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 18d51d6507..71bf8880b0 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -251,14 +251,12 @@ - - @@ -270,7 +268,6 @@ - @@ -284,8 +281,6 @@ - - @@ -1447,9 +1442,6 @@ - - - @@ -1464,7 +1456,6 @@ - diff --git a/src/Umbraco.Tests/Cache/CacheRefresherTests.cs b/src/Umbraco.Tests/Cache/CacheRefresherTests.cs deleted file mode 100644 index 8002cb9b4f..0000000000 --- a/src/Umbraco.Tests/Cache/CacheRefresherTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -using NUnit.Framework; -using Umbraco.Core.Sync; - -namespace Umbraco.Tests.Cache -{ - [TestFixture] - public class CacheRefresherTests - { - [TestCase("", "123456", "testmachine", true)] //empty hash will continue - [TestCase("2e6deefea4444a69dbd15a01b4c2749d", "123456", "testmachine", false)] //match, don't continue - [TestCase("2e6deefea4444a69dbd15a01b4c2749d", "12345", "testmachine", true)] // no match, continue - [TestCase("2e6deefea4444a69dbd15a01b4c2749d", "123456", "testmachin", true)] // same - [TestCase("2e6deefea4444a69dbd15a01b4c2749", "123456", "testmachine", true)] // same - public void Continue_Refreshing_For_Request(string hash, string appDomainAppId, string machineName, bool expected) - { - if (expected) - Assert.IsTrue(Continue(hash, WebServiceServerMessenger.GetServerHash(appDomainAppId, machineName))); - else - Assert.IsFalse(Continue(hash, WebServiceServerMessenger.GetServerHash(appDomainAppId, machineName))); - } - - // that's what CacheRefresher.asmx.cs does... - private bool Continue(string hash1, string hash2) - { - if (string.IsNullOrEmpty(hash1)) return true; - return hash1 != hash2; - } - } -} diff --git a/src/Umbraco.Tests/Cache/DistributedCache/DistributedCacheTests.cs b/src/Umbraco.Tests/Cache/DistributedCache/DistributedCacheTests.cs index ed28004477..dc67bb532f 100644 --- a/src/Umbraco.Tests/Cache/DistributedCache/DistributedCacheTests.cs +++ b/src/Umbraco.Tests/Cache/DistributedCache/DistributedCacheTests.cs @@ -129,52 +129,52 @@ namespace Umbraco.Tests.Cache.DistributedCache public List PayloadsRefreshed = new List(); public int CountOfFullRefreshes = 0; - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, TPayload[] payload) + public void PerformRefresh(ICacheRefresher refresher, TPayload[] payload) { // doing nothing } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, string jsonPayload) + public void PerformRefresh(ICacheRefresher refresher, string jsonPayload) { PayloadsRefreshed.Add(jsonPayload); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances) + public void PerformRefresh(ICacheRefresher refresher, Func getNumericId, params T[] instances) { IntIdsRefreshed.AddRange(instances.Select(getNumericId)); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, Func getGuidId, params T[] instances) + public void PerformRefresh(ICacheRefresher refresher, Func getGuidId, params T[] instances) { GuidIdsRefreshed.AddRange(instances.Select(getGuidId)); } - public void PerformRemove(IEnumerable servers, ICacheRefresher refresher, string jsonPayload) + public void PerformRemove(ICacheRefresher refresher, string jsonPayload) { PayloadsRemoved.Add(jsonPayload); } - public void PerformRemove(IEnumerable servers, ICacheRefresher refresher, Func getNumericId, params T[] instances) + public void PerformRemove(ICacheRefresher refresher, Func getNumericId, params T[] instances) { IntIdsRemoved.AddRange(instances.Select(getNumericId)); } - public void PerformRemove(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds) + public void PerformRemove(ICacheRefresher refresher, params int[] numericIds) { IntIdsRemoved.AddRange(numericIds); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params int[] numericIds) + public void PerformRefresh(ICacheRefresher refresher, params int[] numericIds) { IntIdsRefreshed.AddRange(numericIds); } - public void PerformRefresh(IEnumerable servers, ICacheRefresher refresher, params Guid[] guidIds) + public void PerformRefresh(ICacheRefresher refresher, params Guid[] guidIds) { GuidIdsRefreshed.AddRange(guidIds); } - public void PerformRefreshAll(IEnumerable servers, ICacheRefresher refresher) + public void PerformRefreshAll(ICacheRefresher refresher) { CountOfFullRefreshes++; } diff --git a/src/Umbraco.Tests/Composing/TypeFinderTests.cs b/src/Umbraco.Tests/Composing/TypeFinderTests.cs index c665fc366e..9a0d473db0 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(23, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] + Assert.AreEqual(22, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] } private static ProfilingLogger GetTestProfilingLogger() diff --git a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs index 4cdd9687f5..46f024429e 100644 --- a/src/Umbraco.Tests/Composing/TypeLoaderTests.cs +++ b/src/Umbraco.Tests/Composing/TypeLoaderTests.cs @@ -272,14 +272,14 @@ AnotherContentFinder public void Resolves_Actions() { var actions = _typeLoader.GetActions(); - Assert.AreEqual(37, actions.Count()); + Assert.AreEqual(35, actions.Count()); } [Test] public void Resolves_Trees() { var trees = _typeLoader.GetTrees(); - Assert.AreEqual(5, trees.Count()); + Assert.AreEqual(4, trees.Count()); } [Test] diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementDefaultTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementDefaultTests.cs deleted file mode 100644 index 2c3a843af6..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementDefaultTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Linq; -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class DistributedCallElementDefaultTests : DistributedCallElementTests - { - protected override bool TestingDefaults - { - get { return true; } - } - - [Test] - public override void Enabled() - { - Assert.IsTrue(SettingsSection.DistributedCall.Enabled == false); - - } - - [Test] - public override void Servers() - { - Assert.IsTrue(SettingsSection.DistributedCall.Servers.Any() == false); - } - } -} diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementTests.cs b/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementTests.cs deleted file mode 100644 index c7796a3b0a..0000000000 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/DistributedCallElementTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Linq; -using NUnit.Framework; - -namespace Umbraco.Tests.Configurations.UmbracoSettings -{ - [TestFixture] - public class DistributedCallElementTests : UmbracoSettingsTests - { - [Test] - public virtual void Enabled() - { - Assert.IsTrue(SettingsSection.DistributedCall.Enabled == true); - - } - [Test] - public void UserId() - { - Assert.IsTrue(SettingsSection.DistributedCall.UserId == 0); - - } - [Test] - public virtual void Servers() - { - Assert.IsTrue(SettingsSection.DistributedCall.Servers.Count() == 2); - Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(0).ServerAddress == "127.0.0.1"); - Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ServerAddress == "127.0.0.2"); - Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ForceProtocol == "https"); - Assert.IsTrue(SettingsSection.DistributedCall.Servers.ElementAt(1).ForcePortnumber == "443"); - } - - } -} diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config index c278a99e95..fc59f62d12 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config @@ -150,14 +150,6 @@ Mvc - - - - cs - vb - - - false true @@ -177,19 +169,6 @@ - - - - - 0 - - - - 127.0.0.1 - 127.0.0.2 - - - diff --git a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config index 83b392f8d4..ba10dbca78 100644 --- a/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config +++ b/src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.minimal.config @@ -42,18 +42,12 @@ Mvc - - - - - - diff --git a/src/Umbraco.Tests/IO/AbstractFileSystemTests.cs b/src/Umbraco.Tests/IO/AbstractFileSystemTests.cs index 9f83529d11..123b9c54c2 100644 --- a/src/Umbraco.Tests/IO/AbstractFileSystemTests.cs +++ b/src/Umbraco.Tests/IO/AbstractFileSystemTests.cs @@ -123,12 +123,12 @@ namespace Umbraco.Tests.IO var created = _fileSystem.GetCreated("test.txt"); var modified = _fileSystem.GetLastModified("test.txt"); - Assert.AreEqual(DateTime.Today.Year, created.Year); - Assert.AreEqual(DateTime.Today.Month, created.Month); + Assert.AreEqual(DateTime.UtcNow.Year, created.Year); + Assert.AreEqual(DateTime.UtcNow.Month, created.Month); Assert.AreEqual(DateTime.UtcNow.Date, created.Date); - Assert.AreEqual(DateTime.Today.Year, modified.Year); - Assert.AreEqual(DateTime.Today.Month, modified.Month); + Assert.AreEqual(DateTime.UtcNow.Year, modified.Year); + Assert.AreEqual(DateTime.UtcNow.Month, modified.Month); Assert.AreEqual(DateTime.UtcNow.Date, modified.Date); _fileSystem.DeleteFile("test.txt"); diff --git a/src/Umbraco.Tests/Integration/ContentEventsTests.cs b/src/Umbraco.Tests/Integration/ContentEventsTests.cs index c87774ba27..246626f0a8 100644 --- a/src/Umbraco.Tests/Integration/ContentEventsTests.cs +++ b/src/Umbraco.Tests/Integration/ContentEventsTests.cs @@ -14,8 +14,10 @@ using Umbraco.Core.Sync; using Umbraco.Tests.Cache.DistributedCache; using Umbraco.Tests.Services; using Umbraco.Tests.TestHelpers.Entities; +using Umbraco.Tests.TestHelpers.Stubs; using Umbraco.Tests.Testing; using Umbraco.Web.Cache; +using static Umbraco.Tests.Cache.DistributedCache.DistributedCacheTests; namespace Umbraco.Tests.Integration { @@ -50,8 +52,8 @@ namespace Umbraco.Tests.Integration { base.Compose(); - Container.Register(_ => new DistributedCacheTests.TestServerRegistrar()); // localhost-only - Container.Register(new PerContainerLifetime()); + Container.Register(_ => new TestServerRegistrar()); // localhost-only + Container.Register(new PerContainerLifetime()); Container.RegisterCollectionBuilder() .Add() @@ -2234,5 +2236,15 @@ namespace Umbraco.Tests.Integration // all content type events #endregion + + public class LocalServerMessenger : ServerMessengerBase + { + public LocalServerMessenger() : base(false) + { } + + protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) + { + } + } } } diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 98d36ca616..a440da483a 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -68,7 +68,6 @@ namespace Umbraco.Tests.Macros Assert.AreEqual(converted.Result, prop.GetValue(ctrl)); } - [TestCase("Xslt", true)] [TestCase("PartialView", true)] [TestCase("UserControl", true)] [TestCase("Unknown", false)] diff --git a/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs b/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs index bb134d7e35..9c0560351b 100644 --- a/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs +++ b/src/Umbraco.Tests/Misc/ApplicationUrlHelperTests.cs @@ -11,25 +11,18 @@ using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Sync; using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.Cache.DistributedCache; +using Umbraco.Tests.TestHelpers.Stubs; + namespace Umbraco.Tests.Misc { [TestFixture] public class ApplicationUrlHelperTests { - private IServerRegistrar _registrar; - // note: in tests, read appContext._umbracoApplicationUrl and not the property, // because reading the property does run some code, as long as the field is null. - private void Initialize(IUmbracoSettingsSection settings, IGlobalSettings globalSettings) - { - _registrar = new ConfigServerRegistrar(settings.DistributedCall, Mock.Of(), globalSettings); - var container = new ServiceContainer(); - container.ConfigureUmbracoCore(); - container.Register(_ => _registrar); - } - [TearDown] public void Reset() { @@ -39,18 +32,42 @@ namespace Umbraco.Tests.Misc [Test] public void NoApplicationUrlByDefault() { - var state = new RuntimeState(Mock.Of(), new Lazy(Mock.Of), new Lazy(Mock.Of)); + var state = new RuntimeState(Mock.Of(), new Lazy(Mock.Of), new Lazy(Mock.Of), Mock.Of(), Mock.Of()); Assert.IsNull(state.ApplicationUrl); } + [Test] + public void SetApplicationUrlViaServerRegistrar() + { + // no applicable settings, but a provider + + var settings = Mock.Of(section => + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) + && section.ScheduledTasks == Mock.Of()); + + var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); + globalConfig.Setup(x => x.UseHttps).Returns(true); + + var registrar = new Mock(); + registrar.Setup(x => x.GetCurrentServerUmbracoApplicationUrl()).Returns("http://server1.com/umbraco"); + + var state = new RuntimeState( + Mock.Of(), + new Lazy(() => registrar.Object), + new Lazy(Mock.Of), settings, globalConfig.Object); + + state.EnsureApplicationUrl(); + + Assert.AreEqual("http://server1.com/umbraco", state.ApplicationUrl.ToString()); + } + [Test] public void SetApplicationUrlViaProvider() { // no applicable settings, but a provider var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of()); var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); @@ -58,11 +75,11 @@ namespace Umbraco.Tests.Misc ApplicationUrlHelper.ApplicationUrlProvider = request => "http://server1.com/umbraco"; - Initialize(settings, globalConfig.Object); + - var state = new RuntimeState(Mock.Of(), new Lazy(Mock.Of), new Lazy(Mock.Of)); + var state = new RuntimeState(Mock.Of(), new Lazy(Mock.Of), new Lazy(Mock.Of), settings, globalConfig.Object); - state.EnsureApplicationUrl(settings, globalConfig.Object); + state.EnsureApplicationUrl(); Assert.AreEqual("http://server1.com/umbraco", state.ApplicationUrl.ToString()); } @@ -73,176 +90,31 @@ namespace Umbraco.Tests.Misc // no applicable settings, cannot set url var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of()); var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); globalConfig.Setup(x => x.UseHttps).Returns(true); - Initialize(settings, globalConfig.Object); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object, Mock.Of()); // still NOT set Assert.IsNull(url); } - - [Test] - public void SetApplicationUrlFromDcSettingsSsl1() - { - // set from distributed call settings - // first server is master server - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled && callSection.Servers == new[] - { - Mock.Of(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), - Mock.Of(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), - }) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - globalConfig.Setup(x => x.UseHttps).Returns(true); - - Initialize(settings, globalConfig.Object); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); - - Assert.AreEqual("http://server1.com:80/umbraco", url); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Master, role); - } - - [Test] - public void SetApplicationUrlFromDcSettingsSsl2() - { - // set from distributed call settings - // other servers are slave servers - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled && callSection.Servers == new[] - { - Mock.Of(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), - Mock.Of(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), - }) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - globalConfig.Setup(x => x.UseHttps).Returns(true); - - Initialize(settings, globalConfig.Object); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); - - Assert.AreEqual("http://server1.com:80/umbraco", url); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Slave, role); - } - - [Test] - public void SetApplicationUrlFromDcSettingsSsl3() - { - // set from distributed call settings - // cannot set if not enabled - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled == false && callSection.Servers == new[] - { - Mock.Of(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), - Mock.Of(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), - }) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - globalConfig.Setup(x => x.UseHttps).Returns(true); - - Initialize(settings, globalConfig.Object); - - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); - - Assert.IsNull(url); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Single, role); - } - - [Test] - public void ServerRoleSingle() - { - // distributed call settings disabled, single server - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled == false && callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - - Initialize(settings, globalConfig.Object); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Single, role); - } - - [Test] - public void ServerRoleUnknown1() - { - // distributed call enabled but missing servers, unknown server - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled && callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - - Initialize(settings, globalConfig.Object); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Unknown, role); - } - - [Test] - public void ServerRoleUnknown2() - { - // distributed call enabled, cannot find server, assume it's an undeclared slave - - var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Enabled && callSection.Servers == new[] - { - Mock.Of(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), - }) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string)null) - && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == (string)null)); - - var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); - - Initialize(settings, globalConfig.Object); - - var role = _registrar.GetCurrentServerRole(); - Assert.AreEqual(ServerRole.Slave, role); - } - + [Test] public void SetApplicationUrlFromStSettingsNoSsl() { var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); globalConfig.Setup(x => x.UseHttps).Returns(false); - Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); + + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object, Mock.Of()); Assert.AreEqual("http://mycoolhost.com/umbraco", url); } @@ -251,16 +123,15 @@ namespace Umbraco.Tests.Misc public void SetApplicationUrlFromStSettingsSsl() { var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco/")); var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); globalConfig.Setup(x => x.UseHttps).Returns(true); - Initialize(settings, globalConfig.Object); - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); + + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object, Mock.Of()); Assert.AreEqual("https://mycoolhost.com/umbraco", url); } @@ -269,18 +140,19 @@ namespace Umbraco.Tests.Misc public void SetApplicationUrlFromWrSettingsSsl() { var settings = Mock.Of(section => - section.DistributedCall == Mock.Of(callSection => callSection.Servers == Enumerable.Empty()) - && section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/") + section.WebRouting == Mock.Of(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/") && section.ScheduledTasks == Mock.Of(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); var globalConfig = Mock.Get(SettingsForTests.GenerateMockGlobalSettings()); globalConfig.Setup(x => x.UseHttps).Returns(true); - Initialize(settings, globalConfig.Object); + - var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object); + var url = ApplicationUrlHelper.TryGetApplicationUrl(settings, Mock.Of(), globalConfig.Object, Mock.Of()); Assert.AreEqual("httpx://whatever.com/umbraco", url); } + + } } diff --git a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs index 23a0773f71..703179b184 100644 --- a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs +++ b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs @@ -10,7 +10,8 @@ using Umbraco.Web; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Sync; - +using Umbraco.Core.Configuration.UmbracoSettings; + namespace Umbraco.Tests.Routing { [TestFixture] @@ -24,14 +25,16 @@ namespace Umbraco.Tests.Routing base.SetUp(); //create the module - _module = new UmbracoModule(); - - // test - _module.Logger = Mock.Of(); - var runtime = new RuntimeState(_module.Logger, new Lazy(), new Lazy()); + _module = new UmbracoModule + { + GlobalSettings = TestObjects.GetGlobalSettings(), + Logger = Mock.Of() + }; + var runtime = new RuntimeState(_module.Logger, new Lazy(), new Lazy(), Mock.Of(), _module.GlobalSettings); + _module.Runtime = runtime; runtime.Level = RuntimeLevel.Run; - _module.GlobalSettings = TestObjects.GetGlobalSettings(); + //SettingsForTests.ReservedPaths = "~/umbraco,~/install/"; //SettingsForTests.ReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd"; diff --git a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs index c2ec892770..48bbdb1e22 100644 --- a/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedRepositoryTests.cs @@ -334,7 +334,7 @@ namespace Umbraco.Tests.Scoping : base(false) { } - protected override void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) + protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs index 899d2f999e..9de2012dce 100644 --- a/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedXmlTests.cs @@ -299,7 +299,7 @@ namespace Umbraco.Tests.Scoping : base(false) { } - protected override void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) + protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { throw new NotImplementedException(); } diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index 34c6a35833..35d3d72183 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -58,7 +58,6 @@ namespace Umbraco.Tests.TestHelpers var templates = new Mock(); var logging = new Mock(); var tasks = new Mock(); - var distCall = new Mock(); var providers = new Mock(); var routing = new Mock(); @@ -68,7 +67,6 @@ namespace Umbraco.Tests.TestHelpers 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.DistributedCall).Returns(distCall.Object); settings.Setup(x => x.Providers).Returns(providers.Object); settings.Setup(x => x.WebRouting).Returns(routing.Object); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index d39608c49c..827bfef4b7 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -206,7 +206,6 @@ - @@ -282,8 +281,6 @@ - - diff --git a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj index 7dbced3167..10e288092f 100644 --- a/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj +++ b/src/Umbraco.Web.UI/Umbraco.Web.UI.csproj @@ -539,9 +539,6 @@ - - Form - diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config index 3f06c398f5..534a9e2640 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.Release.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.Release.config @@ -90,50 +90,6 @@ - - - - - 0 - - - - - - - - - - - - - - - 0 - - - - - - - - - - - diff --git a/src/Umbraco.Web.UI/umbraco/webservices/CacheRefresher.asmx b/src/Umbraco.Web.UI/umbraco/webservices/CacheRefresher.asmx deleted file mode 100644 index 4347d8ede8..0000000000 --- a/src/Umbraco.Web.UI/umbraco/webservices/CacheRefresher.asmx +++ /dev/null @@ -1 +0,0 @@ -<%@ WebService Language="c#" Codebehind="CacheRefresher.asmx.cs" Class="umbraco.presentation.webservices.CacheRefresher" %> diff --git a/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs b/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs index d03077bf24..a28a180d50 100644 --- a/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs +++ b/src/Umbraco.Web/BatchedDatabaseServerMessenger.cs @@ -57,7 +57,7 @@ namespace Umbraco.Web FlushBatch(); } - protected override void DeliverRemote(IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) + protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, string json = null) { var idsA = ids?.ToArray(); @@ -65,7 +65,7 @@ namespace Umbraco.Web if (GetArrayType(idsA, out arrayType) == false) throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids)); - BatchMessage(servers, refresher, messageType, idsA, arrayType, json); + BatchMessage(refresher, messageType, idsA, arrayType, json); } public void FlushBatch() @@ -124,7 +124,6 @@ namespace Umbraco.Web } protected void BatchMessage( - IEnumerable servers, ICacheRefresher refresher, MessageType messageType, IEnumerable ids = null, @@ -149,7 +148,7 @@ namespace Umbraco.Web } else { - batch.Add(new RefreshInstructionEnvelope(servers, refresher, instructions)); + batch.Add(new RefreshInstructionEnvelope(refresher, instructions)); } } diff --git a/src/Umbraco.Web/BatchedWebServiceServerMessenger.cs b/src/Umbraco.Web/BatchedWebServiceServerMessenger.cs deleted file mode 100644 index 66a850e5c5..0000000000 --- a/src/Umbraco.Web/BatchedWebServiceServerMessenger.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Web; -using Umbraco.Core.Sync; -using Umbraco.Web.Routing; - -namespace Umbraco.Web -{ - /// - /// An that works by messaging servers via web services. - /// - /// - /// This binds to appropriate umbraco events in order to trigger the FlushBatch() calls - /// - internal class BatchedWebServiceServerMessenger : Core.Sync.BatchedWebServiceServerMessenger - { - internal BatchedWebServiceServerMessenger() - : base() - { - UmbracoModule.EndRequest += UmbracoModule_EndRequest; - } - - internal BatchedWebServiceServerMessenger(string login, string password) - : base(login, password) - { - UmbracoModule.EndRequest += UmbracoModule_EndRequest; - } - - internal BatchedWebServiceServerMessenger(string login, string password, bool useDistributedCalls) - : base(login, password, useDistributedCalls) - { - UmbracoModule.EndRequest += UmbracoModule_EndRequest; - } - - public BatchedWebServiceServerMessenger(Func> getLoginAndPassword) - : base(getLoginAndPassword) - { - UmbracoModule.EndRequest += UmbracoModule_EndRequest; - } - - protected override ICollection GetBatch(bool ensureHttpContext) - { - //try get the http context from the UmbracoContext, we do this because in the case we are launching an async - // thread and we know that the cache refreshers will execute, we will ensure the UmbracoContext and therefore we - // can get the http context from it - var httpContext = (UmbracoContext.Current == null ? null : UmbracoContext.Current.HttpContext) - //if this is null, it could be that an async thread is calling this method that we weren't aware of and the UmbracoContext - // wasn't ensured at the beginning of the thread. We can try to see if the HttpContext.Current is available which might be - // the case if the asp.net synchronization context has kicked in - ?? (HttpContext.Current == null ? null : new HttpContextWrapper(HttpContext.Current)); - - if (httpContext == null) - { - if (ensureHttpContext) - throw new NotSupportedException("Cannot execute without a valid/current HttpContext assigned."); - return null; - } - - var key = typeof(BatchedWebServiceServerMessenger).Name; - - // no thread-safety here because it'll run in only 1 thread (request) at a time - var batch = (ICollection)httpContext.Items[key]; - if (batch == null && ensureHttpContext) - httpContext.Items[key] = batch = new List(); - return batch; - } - - private void UmbracoModule_EndRequest(object sender, UmbracoRequestEventArgs e) - { - FlushBatch(); - } - - protected override void ProcessBatch(RefreshInstructionEnvelope[] batch) - { - Message(batch); - } - } -} diff --git a/src/Umbraco.Web/Cache/DistributedCache.cs b/src/Umbraco.Web/Cache/DistributedCache.cs index 23d1067282..6f5196d642 100644 --- a/src/Umbraco.Web/Cache/DistributedCache.cs +++ b/src/Umbraco.Web/Cache/DistributedCache.cs @@ -38,7 +38,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || instances.Length == 0 || getNumericId == null) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), getNumericId, instances); @@ -54,7 +53,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || id == default(int)) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), id); } @@ -69,7 +67,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || id == Guid.Empty) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), id); } @@ -81,7 +78,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || payload == null) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), payload); } @@ -93,7 +89,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || payloads == null) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), payloads.ToArray()); } @@ -107,7 +102,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || jsonPayload.IsNullOrWhiteSpace()) return; Current.ServerMessenger.PerformRefresh( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), jsonPayload); } @@ -136,7 +130,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty) return; Current.ServerMessenger.PerformRefreshAll( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid)); } @@ -150,7 +143,6 @@ namespace Umbraco.Web.Cache if (refresherGuid == Guid.Empty || id == default(int)) return; Current.ServerMessenger.PerformRemove( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), id); } @@ -168,7 +160,6 @@ namespace Umbraco.Web.Cache public void Remove(Guid refresherGuid, Func getNumericId, params T[] instances) { Current.ServerMessenger.PerformRemove( - Current.ServerRegistrar.Registrations, GetRefresherById(refresherGuid), getNumericId, instances); diff --git a/src/Umbraco.Web/Components/DatabaseServerRegistrarAndMessengerComponent.cs b/src/Umbraco.Web/Components/DatabaseServerRegistrarAndMessengerComponent.cs index f679b00943..e07a36bbfc 100644 --- a/src/Umbraco.Web/Components/DatabaseServerRegistrarAndMessengerComponent.cs +++ b/src/Umbraco.Web/Components/DatabaseServerRegistrarAndMessengerComponent.cs @@ -50,9 +50,6 @@ namespace Umbraco.Web.Components public override void Compose(Composition composition) { - //fixme inject IUmbracoSettingsSection - if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled) return; - composition.SetServerMessenger(factory => { var runtime = factory.GetInstance(); @@ -96,8 +93,6 @@ namespace Umbraco.Web.Components public void Initialize(IRuntimeState runtime, IServerRegistrar serverRegistrar, IServerMessenger serverMessenger, IServerRegistrationService registrationService, ILogger logger, IExamineManager examineManager) { - if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled) return; - _registrar = serverRegistrar as DatabaseServerRegistrar; if (_registrar == null) throw new Exception("panic: registar."); diff --git a/src/Umbraco.Web/Components/LegacyServerRegistrarAndMessengerComponent.cs b/src/Umbraco.Web/Components/LegacyServerRegistrarAndMessengerComponent.cs deleted file mode 100644 index d494d239a3..0000000000 --- a/src/Umbraco.Web/Components/LegacyServerRegistrarAndMessengerComponent.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using LightInject; -using Umbraco.Core; -using Umbraco.Core.Components; -using Umbraco.Core.Configuration; -using Umbraco.Core.Logging; -using Umbraco.Core.Services; -using Umbraco.Web.Runtime; - -namespace Umbraco.Web.Components -{ - // the legacy LB is not enabled by default, because LB is implemented by - // DatabaseServerRegistrarAndMessengerComponent instead - - [RuntimeLevel(MinLevel = RuntimeLevel.Run)] - [DisableComponent] // is not enabled by default - public sealed class LegacyServerRegistrarAndMessengerComponent : UmbracoComponentBase, IUmbracoCoreComponent - { - public override void Compose(Composition composition) - { - if (UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled == false) return; - - composition.SetServerMessenger(factory => - { - var runtime = factory.GetInstance(); - var logger = factory.GetInstance(); - var userService = factory.GetInstance(); - - return new BatchedWebServiceServerMessenger(() => - { - // we should not proceed to change this if the app/database is not configured since there will - // be no user, plus we don't need to have server messages sent if this is the case. - if (runtime.Level == RuntimeLevel.Run) - { - try - { - var user = userService.GetUserById(UmbracoConfig.For.UmbracoSettings().DistributedCall.UserId); - return Tuple.Create(user.Username, user.RawPasswordValue); - } - catch (Exception e) - { - logger.Error("An error occurred trying to set the IServerMessenger during application startup", e); - return null; - } - } - logger.Warn("Could not initialize the DefaultServerMessenger, the application is not configured or the database is not configured"); - return null; - }); - }); - } - } -} diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 0dd6ef73f1..5a39523707 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -417,7 +417,6 @@ - @@ -575,7 +574,6 @@ - @@ -1410,10 +1408,6 @@ - - CacheRefresher.asmx - Component - CheckForUpgrade.asmx Component @@ -1487,9 +1481,6 @@ ASPXCodeBehind - - Form - diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index 1578f5dc53..24189fd601 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -89,7 +89,7 @@ namespace Umbraco.Web private void BeginRequest(HttpContextBase httpContext) { // ensure application url is initialized - ((RuntimeState) Current.RuntimeState).EnsureApplicationUrl(UmbracoSettings, GlobalSettings, httpContext.Request); + ((RuntimeState) Current.RuntimeState).EnsureApplicationUrl(httpContext.Request); // do not process if client-side request if (httpContext.Request.Url.IsClientSideRequest()) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx deleted file mode 100644 index 4347d8ede8..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx +++ /dev/null @@ -1 +0,0 @@ -<%@ WebService Language="c#" Codebehind="CacheRefresher.asmx.cs" Class="umbraco.presentation.webservices.CacheRefresher" %> diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs deleted file mode 100644 index c10c35a6c0..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/CacheRefresher.asmx.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System; -using System.Linq; -using System.Web; -using System.Web.Services; -using System.Xml; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.Owin; -using Newtonsoft.Json; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Logging; -using Umbraco.Core.Sync; -using Umbraco.Core.Models.Identity; -using Umbraco.Core.Security; -using Umbraco.Core.Xml; -using Umbraco.Web.Security; -using Umbraco.Web; -using Umbraco.Web.Composing; - -namespace umbraco.presentation.webservices -{ - /// - /// CacheRefresher web service. - /// - [WebService(Namespace="http://umbraco.org/webservices/")] - public class CacheRefresher : WebService - { - #region Helpers - - // is the server originating from this server - ie are we self-messaging? - // in which case we should ignore the message because it's been processed locally already - internal static bool SelfMessage(string hash) - { - if (string.IsNullOrEmpty(hash)) return false; // no hash = don't know = not self - if (hash != WebServiceServerMessenger.GetCurrentServerHash()) return false; - - Current.Logger.Debug(() => - $"Ignoring self-message. (server: {NetworkHelper.MachineName}, appId: {HttpRuntime.AppDomainAppId}, hash: {hash})"); - - return true; - } - - private static ICacheRefresher GetRefresher(Guid id) - { - var refresher = Current.CacheRefreshers[id]; - if (refresher == null) - throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist."); - return refresher; - } - - private static IJsonCacheRefresher GetJsonRefresher(Guid id) - { - return GetJsonRefresher(GetRefresher(id)); - } - - private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher) - { - var jsonRefresher = refresher as IJsonCacheRefresher; - if (jsonRefresher == null) - throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + "."); - return jsonRefresher; - } - - private bool Authorized(string login, string rawPassword) - { - //TODO: This technique of passing the raw password in is a legacy idea and isn't really - // a very happy way to secure this webservice. To prevent brute force attacks, we need - // to ensure that the lockout policies are applied, though because we are not authenticating - // the user with their real password, we need to do this a bit manually. - - var userMgr = Context.GetOwinContext().GetBackOfficeUserManager(); - - var user = Current.Services.UserService.GetByUsername(login); - if (user == null) return false; - - var u = userMgr.FindById(user.Id); - if (u == null) return false; - - if (u.IsLockedOut) return false; - - if (user.RawPasswordValue != rawPassword) - { - //this performs the lockout and/or increments the access failed count - userMgr.AccessFailed(u.Id); - return false; - } - - return true; - } - - #endregion - - [WebMethod] - public void BulkRefresh(RefreshInstruction[] instructions, string appId, string login, string password) - { - if (Authorized(login, password) == false) return; - if (SelfMessage(appId)) return; // do not process self-messages - - // only execute distinct instructions - no sense in running the same one more than once - foreach (var instruction in instructions.Distinct()) - { - var refresher = GetRefresher(instruction.RefresherId); - switch (instruction.RefreshType) - { - case RefreshMethodType.RefreshAll: - refresher.RefreshAll(); - break; - case RefreshMethodType.RefreshByGuid: - refresher.Refresh(instruction.GuidId); - break; - case RefreshMethodType.RefreshById: - refresher.Refresh(instruction.IntId); - break; - case RefreshMethodType.RefreshByIds: // not directly supported by ICacheRefresher - foreach (var id in JsonConvert.DeserializeObject(instruction.JsonIds)) - refresher.Refresh(id); - break; - case RefreshMethodType.RefreshByJson: - GetJsonRefresher(refresher).Refresh(instruction.JsonPayload); - break; - case RefreshMethodType.RemoveById: - refresher.Remove(instruction.IntId); - break; - //case RefreshMethodType.RemoveByIds: // not directly supported by ICacheRefresher - // foreach (var id in JsonConvert.DeserializeObject(instruction.JsonIds)) - // refresher.Remove(id); - // break; - } - } - } - - [WebMethod] - public void RefreshAll(Guid uniqueIdentifier, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - GetRefresher(uniqueIdentifier).RefreshAll(); - } - - [WebMethod] - public void RefreshByGuid(Guid uniqueIdentifier, Guid Id, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - GetRefresher(uniqueIdentifier).Refresh(Id); - } - - [WebMethod] - public void RefreshById(Guid uniqueIdentifier, int Id, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - GetRefresher(uniqueIdentifier).Refresh(Id); - } - - [WebMethod] - public void RefreshByIds(Guid uniqueIdentifier, string jsonIds, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - var refresher = GetRefresher(uniqueIdentifier); - foreach (var id in JsonConvert.DeserializeObject(jsonIds)) - refresher.Refresh(id); - } - - [WebMethod] - public void RefreshByJson(Guid uniqueIdentifier, string jsonPayload, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - GetJsonRefresher(uniqueIdentifier).Refresh(jsonPayload); - } - - [WebMethod] - public void RemoveById(Guid uniqueIdentifier, int Id, string Login, string Password) - { - if (Authorized(Login, Password) == false) return; - GetRefresher(uniqueIdentifier).Remove(Id); - } - - [WebMethod] - public XmlDocument GetRefreshers(string Login, string Password) - { - if (Authorized(Login, Password) == false) return null; - - var xd = new XmlDocument(); - xd.LoadXml(""); - foreach (var cr in Current.CacheRefreshers) - { - var n = XmlHelper.AddTextNode(xd, "cacheRefresher", cr.Name); - n.Attributes.Append(XmlHelper.AddAttribute(xd, "uniqueIdentifier", cr.RefresherUniqueId.ToString())); - xd.DocumentElement.AppendChild(n); - } - return xd; - } - } -} From 459479a7b8d4834208675a049c122a9dc88cf646 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 12:12:26 +1000 Subject: [PATCH 57/58] Refactors how macros are stored in the DB --- .../Events/MacroErrorEventArgs.cs | 2 +- .../Migrations/Upgrade/UmbracoPlan.cs | 7 +- .../Upgrade/V_8_0_0/AddVariationTables1A.cs | 2 +- .../Upgrade/V_8_0_0/RefactorMacroColumns.cs | 43 ++ src/Umbraco.Core/Models/IMacro.cs | 15 +- src/Umbraco.Core/Models/Macro.cs | 49 +- src/Umbraco.Core/Persistence/Dtos/MacroDto.cs | 15 +- .../Persistence/Factories/MacroFactory.cs | 8 +- .../Persistence/Mappers/MacroMapper.cs | 4 +- .../Services/EntityXmlSerializer.cs | 4 +- .../Services/Implement/MacroService.cs | 15 - .../Services/Implement/PackagingService.cs | 6 +- src/Umbraco.Core/Umbraco.Core.csproj | 1 + src/Umbraco.Tests/Macros/MacroTests.cs | 5 +- src/Umbraco.Tests/Models/MacroTests.cs | 2 +- .../Repositories/MacroRepositoryTest.cs | 25 +- .../Services/MacroServiceTests.cs | 24 +- .../Services/PackagingServiceTests.cs | 2 +- .../developer/Macros/EditMacro.aspx.cs | 302 +++++++++-- .../Macros/EditMacro.aspx.designer.cs | 182 ++++++- src/Umbraco.Web/Editors/MacroController.cs | 2 +- src/Umbraco.Web/Macros/MacroModel.cs | 15 +- src/Umbraco.Web/Macros/MacroRenderer.cs | 24 +- .../Macros/PartialViewMacroController.cs | 2 +- .../Macros/PartialViewMacroEngine.cs | 2 +- .../Macros/UserControlMacroEngine.cs | 2 +- src/Umbraco.Web/Umbraco.Web.csproj | 3 - .../PackageInstance/PackagerUtility.cs | 9 +- .../umbraco/create/macroTasks.cs | 2 +- .../developer/Macros/editMacro.aspx.cs | 469 ------------------ .../umbraco/templateControls/Macro.cs | 2 +- 31 files changed, 592 insertions(+), 653 deletions(-) create mode 100644 src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorMacroColumns.cs delete mode 100644 src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs diff --git a/src/Umbraco.Core/Events/MacroErrorEventArgs.cs b/src/Umbraco.Core/Events/MacroErrorEventArgs.cs index bdda23ba3a..75312508a7 100644 --- a/src/Umbraco.Core/Events/MacroErrorEventArgs.cs +++ b/src/Umbraco.Core/Events/MacroErrorEventArgs.cs @@ -19,7 +19,7 @@ namespace Umbraco.Core.Events /// /// Filename, file path, fully qualified class name, or other key used by the macro engine to do it's processing of the faulting macro. /// - public string ItemKey { get; set; } + public string MacroSource { get; set; } /// /// Exception raised. diff --git a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs index 4954742908..565d5be138 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs @@ -118,9 +118,10 @@ namespace Umbraco.Core.Migrations.Upgrade Chain("{7F59355A-0EC9-4438-8157-EB517E6D2727}"); Chain("{66B6821A-0DE3-4DF8-A6A4-65ABD211EDDE}"); Chain("{49506BAE-CEBB-4431-A1A6-24AD6EBBBC57}"); + Chain("{083A9894-903D-41B7-B6B3-9EAF2D4CCED0}"); // must chain to v8 final state (see at end of file) - Chain("{76DF5CD7-A884-41A5-8DC6-7860D95B1DF5}"); + Chain("{A7540C58-171D-462A-91C5-7A9AA5CB8BFD}"); // UPGRADE FROM 7, MORE RECENT @@ -209,10 +210,12 @@ namespace Umbraco.Core.Migrations.Upgrade // however, need to take care of ppl in post-AddVariationTables1 state Add("{941B2ABA-2D06-4E04-81F5-74224F1DB037}", "{76DF5CD7-A884-41A5-8DC6-7860D95B1DF5}"); + Chain("{A7540C58-171D-462A-91C5-7A9AA5CB8BFD}"); + // FINAL STATE - MUST MATCH LAST ONE ABOVE ! // whenever this changes, update all references in this file! - Add(string.Empty, "{76DF5CD7-A884-41A5-8DC6-7860D95B1DF5}"); + Add(string.Empty, "{A7540C58-171D-462A-91C5-7A9AA5CB8BFD}"); } } } diff --git a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddVariationTables1A.cs b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddVariationTables1A.cs index 0fce88da46..96e82d281d 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddVariationTables1A.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/AddVariationTables1A.cs @@ -33,7 +33,7 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0 //now we need to update the new column with some values because this column doesn't allow NULL values Update.Table(ContentVersionCultureVariationDto.TableName).Set(new {date = DateTime.Now}).AllRows().Do(); //now apply constraints (NOT NULL) to new table - foreach (var sql in sqls) Database.Execute(sql); + foreach (var sql in sqls) Execute.Sql(sql).Do(); // name, languageId are now non-nullable AlterColumn(Constants.DatabaseSchema.Tables.ContentVersionCultureVariation, "name"); diff --git a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorMacroColumns.cs b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorMacroColumns.cs new file mode 100644 index 0000000000..623a842525 --- /dev/null +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorMacroColumns.cs @@ -0,0 +1,43 @@ +using Umbraco.Core.Models; +using Umbraco.Core.Persistence.Dtos; + +namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0 +{ + public class RefactorMacroColumns : MigrationBase + { + public RefactorMacroColumns(IMigrationContext context) + : base(context) + { } + + public override void Migrate() + { + if (ColumnExists(Constants.DatabaseSchema.Tables.Macro, "macroXSLT")) + { + //special trick to add the column without constraints and return the sql to add them later + AddColumn("macroType", out var sqls1); + //now we need to update the new column with some values because this column doesn't allow NULL values + Update.Table(Constants.DatabaseSchema.Tables.Macro).Set(new { macroType = (int)MacroTypes.Unknown}).AllRows().Do(); + //now apply constraints (NOT NULL) to new table + foreach (var sql in sqls1) Execute.Sql(sql).Do(); + + //special trick to add the column without constraints and return the sql to add them later + AddColumn("macroSource", out var sqls2); + + //populate the new macroSource column with legacy data + Execute.Sql($"UPDATE {Constants.DatabaseSchema.Tables.Macro} SET macroSource = macroXSLT, macroType = {(int)MacroTypes.Unknown} WHERE macroXSLT IS NOT NULL").Do(); + Execute.Sql($"UPDATE {Constants.DatabaseSchema.Tables.Macro} SET macroSource = macroScriptAssembly, macroType = {(int)MacroTypes.Unknown} WHERE macroScriptAssembly IS NOT NULL").Do(); + Execute.Sql($"UPDATE {Constants.DatabaseSchema.Tables.Macro} SET macroSource = macroScriptType, macroType = {(int)MacroTypes.UserControl} WHERE macroScriptType IS NOT NULL").Do(); + Execute.Sql($"UPDATE {Constants.DatabaseSchema.Tables.Macro} SET macroSource = macroPython, macroType = {(int)MacroTypes.PartialView} WHERE macroPython IS NOT NULL").Do(); + + //now apply constraints (NOT NULL) to new table + foreach (var sql in sqls2) Execute.Sql(sql).Do(); + + //now remove these old columns + Delete.Column("macroXSLT").FromTable(Constants.DatabaseSchema.Tables.Macro).Do(); + Delete.Column("macroScriptAssembly").FromTable(Constants.DatabaseSchema.Tables.Macro).Do(); + Delete.Column("macroScriptType").FromTable(Constants.DatabaseSchema.Tables.Macro).Do(); + Delete.Column("macroPython").FromTable(Constants.DatabaseSchema.Tables.Macro).Do(); + } + } + } +} diff --git a/src/Umbraco.Core/Models/IMacro.cs b/src/Umbraco.Core/Models/IMacro.cs index c56d3d9628..472c135e32 100644 --- a/src/Umbraco.Core/Models/IMacro.cs +++ b/src/Umbraco.Core/Models/IMacro.cs @@ -51,20 +51,19 @@ namespace Umbraco.Core.Models /// [DataMember] bool DontRender { get; set; } - + /// - /// Gets or sets the path to user control or the Control Type to render + /// Gets or set the path to the macro source to render /// [DataMember] - string ControlType { get; set; } - + string MacroSource { get; set; } + /// - /// Gets or set the path to the Python file in use + /// Gets or set the macro type /// - /// Optional: Can only be one of three Script, Python or Xslt [DataMember] - string ScriptPath { get; set; } - + MacroTypes MacroType { get; set; } + /// /// Gets or sets a list of Macro Properties /// diff --git a/src/Umbraco.Core/Models/Macro.cs b/src/Umbraco.Core/Models/Macro.cs index a24d659ce3..dc411a0291 100644 --- a/src/Umbraco.Core/Models/Macro.cs +++ b/src/Umbraco.Core/Models/Macro.cs @@ -34,12 +34,11 @@ namespace Umbraco.Core.Models /// /// /// - /// /// /// /// - /// - public Macro(int id, Guid key, bool useInEditor, int cacheDuration, string @alias, string name, string controlType, bool cacheByPage, bool cacheByMember, bool dontRender, string scriptPath) + /// + public Macro(int id, Guid key, bool useInEditor, int cacheDuration, string @alias, string name, bool cacheByPage, bool cacheByMember, bool dontRender, string macroSource, MacroTypes macroType) : this() { Id = id; @@ -48,11 +47,11 @@ namespace Umbraco.Core.Models CacheDuration = cacheDuration; Alias = alias.ToCleanString(CleanStringType.Alias); Name = name; - ControlType = controlType; CacheByPage = cacheByPage; CacheByMember = cacheByMember; DontRender = dontRender; - ScriptPath = scriptPath; + MacroSource = macroSource; + MacroType = macroType; } /// @@ -62,14 +61,13 @@ namespace Umbraco.Core.Models /// /// /// - /// /// /// /// - /// + /// public Macro(string @alias, string name, - string controlType = "", - string scriptPath = "", + string macroSource, + MacroTypes macroType, bool cacheByPage = false, bool cacheByMember = false, bool dontRender = true, @@ -81,11 +79,11 @@ namespace Umbraco.Core.Models CacheDuration = cacheDuration; Alias = alias.ToCleanString(CleanStringType.Alias); Name = name; - ControlType = controlType; CacheByPage = cacheByPage; CacheByMember = cacheByMember; DontRender = dontRender; - ScriptPath = scriptPath; + MacroSource = macroSource; + MacroType = macroType; } private string _alias; @@ -95,8 +93,8 @@ namespace Umbraco.Core.Models private bool _cacheByPage; private bool _cacheByMember; private bool _dontRender; - private string _scriptFile; - private string _scriptPath; + private string _macroSource; + private MacroTypes _macroType = MacroTypes.Unknown; private MacroPropertyCollection _properties; private List _addedProperties; private List _removedProperties; @@ -112,8 +110,8 @@ namespace Umbraco.Core.Models public readonly PropertyInfo CacheByPageSelector = ExpressionHelper.GetPropertyInfo(x => x.CacheByPage); public readonly PropertyInfo CacheByMemberSelector = ExpressionHelper.GetPropertyInfo(x => x.CacheByMember); public readonly PropertyInfo DontRenderSelector = ExpressionHelper.GetPropertyInfo(x => x.DontRender); - public readonly PropertyInfo ControlPathSelector = ExpressionHelper.GetPropertyInfo(x => x.ControlType); - public readonly PropertyInfo ScriptPathSelector = ExpressionHelper.GetPropertyInfo(x => x.ScriptPath); + public readonly PropertyInfo ScriptPathSelector = ExpressionHelper.GetPropertyInfo(x => x.MacroSource); + public readonly PropertyInfo MacroTypeSelector = ExpressionHelper.GetPropertyInfo(x => x.MacroType); public readonly PropertyInfo PropertiesSelector = ExpressionHelper.GetPropertyInfo(x => x.Properties); } @@ -258,24 +256,23 @@ namespace Umbraco.Core.Models } /// - /// Gets or sets the path to user control or the Control Type to render + /// Gets or set the path to the Partial View to render /// [DataMember] - public string ControlType + public string MacroSource { - get { return _scriptFile; } - set { SetPropertyValueAndDetectChanges(value, ref _scriptFile, Ps.Value.ControlPathSelector); } - } - + get { return _macroSource; } + set { SetPropertyValueAndDetectChanges(value, ref _macroSource, Ps.Value.ScriptPathSelector); } + } + /// - /// Gets or set the path to the Python file in use + /// Gets or set the path to the Partial View to render /// - /// Optional: Can only be one of three Script, Python or Xslt [DataMember] - public string ScriptPath + public MacroTypes MacroType { - get { return _scriptPath; } - set { SetPropertyValueAndDetectChanges(value, ref _scriptPath, Ps.Value.ScriptPathSelector); } + get { return _macroType; } + set { SetPropertyValueAndDetectChanges(value, ref _macroType, Ps.Value.MacroTypeSelector); } } /// diff --git a/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs b/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs index 2bfbcaba29..8558ce4a35 100644 --- a/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/MacroDto.cs @@ -34,10 +34,6 @@ namespace Umbraco.Core.Persistence.Dtos [NullSetting(NullSetting = NullSettings.Null)] public string Name { get; set; } - [Column("macroScriptType")] - [NullSetting(NullSetting = NullSettings.Null)] - public string ScriptType { get; set; } - [Column("macroCacheByPage")] [Constraint(Default = "1")] public bool CacheByPage { get; set; } @@ -50,10 +46,13 @@ namespace Umbraco.Core.Persistence.Dtos [Constraint(Default = "0")] public bool DontRender { get; set; } - //TODO: Rename this column! - actually please revamp all of the macros! :) - [Column("macroPython")] - [NullSetting(NullSetting = NullSettings.Null)] - public string MacroFilePath { get; set; } + [Column("macroSource")] + [NullSetting(NullSetting = NullSettings.NotNull)] + public string MacroSource { get; set; } + + [Column("macroType")] + [NullSetting(NullSetting = NullSettings.NotNull)] + public int MacroType { get; set; } [ResultColumn] [Reference(ReferenceType.Many, ReferenceMemberName = "Macro")] diff --git a/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs b/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs index a85de1fa57..3963c591f0 100644 --- a/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs +++ b/src/Umbraco.Core/Persistence/Factories/MacroFactory.cs @@ -9,7 +9,7 @@ namespace Umbraco.Core.Persistence.Factories { public IMacro BuildEntity(MacroDto dto) { - var model = new Macro(dto.Id, dto.UniqueId, dto.UseInEditor, dto.RefreshRate, dto.Alias, dto.Name, dto.ScriptType, dto.CacheByPage, dto.CachePersonalized, dto.DontRender, dto.MacroFilePath); + var model = new Macro(dto.Id, dto.UniqueId, dto.UseInEditor, dto.RefreshRate, dto.Alias, dto.Name, dto.CacheByPage, dto.CachePersonalized, dto.DontRender, dto.MacroSource, (MacroTypes)dto.MacroType); try { @@ -40,11 +40,11 @@ namespace Umbraco.Core.Persistence.Factories CachePersonalized = entity.CacheByMember, DontRender = entity.DontRender, Name = entity.Name, - MacroFilePath = entity.ScriptPath, + MacroSource = entity.MacroSource, RefreshRate = entity.CacheDuration, - ScriptType = entity.ControlType, UseInEditor = entity.UseInEditor, - MacroPropertyDtos = BuildPropertyDtos(entity) + MacroPropertyDtos = BuildPropertyDtos(entity), + MacroType = (int)entity.MacroType }; if (entity.HasIdentity) diff --git a/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs b/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs index 07490a4cd8..489bd40ddf 100644 --- a/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs +++ b/src/Umbraco.Core/Persistence/Mappers/MacroMapper.cs @@ -18,11 +18,11 @@ namespace Umbraco.Core.Persistence.Mappers CacheMap(src => src.Alias, dto => dto.Alias); CacheMap(src => src.CacheByPage, dto => dto.CacheByPage); CacheMap(src => src.CacheByMember, dto => dto.CachePersonalized); - CacheMap(src => src.ControlType, dto => dto.ScriptType); + CacheMap(src => src.MacroType, dto => dto.MacroType); CacheMap(src => src.DontRender, dto => dto.DontRender); CacheMap(src => src.Name, dto => dto.Name); CacheMap(src => src.CacheDuration, dto => dto.RefreshRate); - CacheMap(src => src.ScriptPath, dto => dto.MacroFilePath); + CacheMap(src => src.MacroSource, dto => dto.MacroSource); CacheMap(src => src.UseInEditor, dto => dto.UseInEditor); } } diff --git a/src/Umbraco.Core/Services/EntityXmlSerializer.cs b/src/Umbraco.Core/Services/EntityXmlSerializer.cs index 772d1f183d..e418c8d3e6 100644 --- a/src/Umbraco.Core/Services/EntityXmlSerializer.cs +++ b/src/Umbraco.Core/Services/EntityXmlSerializer.cs @@ -295,8 +295,8 @@ namespace Umbraco.Core.Services var xml = new XElement("macro"); xml.Add(new XElement("name", macro.Name)); xml.Add(new XElement("alias", macro.Alias)); - xml.Add(new XElement("scriptType", macro.ControlType)); - xml.Add(new XElement("scriptingFile", macro.ScriptPath)); + xml.Add(new XElement("macroType", macro.MacroType)); + xml.Add(new XElement("macroSource", macro.MacroSource)); xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); xml.Add(new XElement("dontRender", macro.DontRender.ToString())); xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); diff --git a/src/Umbraco.Core/Services/Implement/MacroService.cs b/src/Umbraco.Core/Services/Implement/MacroService.cs index 1e0be6c4b3..fdcc8e2ee0 100644 --- a/src/Umbraco.Core/Services/Implement/MacroService.cs +++ b/src/Umbraco.Core/Services/Implement/MacroService.cs @@ -25,21 +25,6 @@ namespace Umbraco.Core.Services.Implement _auditRepository = auditRepository; } - /// - /// Returns an enum based on the properties on the Macro - /// - /// - internal static MacroTypes GetMacroType(IMacro macro) - { - if (string.IsNullOrEmpty(macro.ScriptPath) == false) - return MacroTypes.PartialView; - - if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx")) - return MacroTypes.UserControl; - - return MacroTypes.Unknown; - } - /// /// Gets an object by its alias /// diff --git a/src/Umbraco.Core/Services/Implement/PackagingService.cs b/src/Umbraco.Core/Services/Implement/PackagingService.cs index 04e52833d6..1e585053da 100644 --- a/src/Umbraco.Core/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Core/Services/Implement/PackagingService.cs @@ -1270,8 +1270,8 @@ namespace Umbraco.Core.Services.Implement { var macroName = macroElement.Element("name").Value; var macroAlias = macroElement.Element("alias").Value; - var controlType = macroElement.Element("scriptType").Value; - var scriptPath = macroElement.Element("scriptingFile").Value; + var macroType = Enum.Parse(macroElement.Element("macroType").Value); + var macroSource = macroElement.Element("macroSource").Value; //Following xml elements are treated as nullable properties var useInEditorElement = macroElement.Element("useInEditor"); @@ -1306,7 +1306,7 @@ namespace Umbraco.Core.Services.Implement } var existingMacro = _macroService.GetByAlias(macroAlias) as Macro; - var macro = existingMacro ?? new Macro(macroAlias, macroName, controlType, scriptPath, + var macro = existingMacro ?? new Macro(macroAlias, macroName, macroSource, macroType, cacheByPage, cacheByMember, dontRender, useInEditor, cacheDuration); var properties = macroElement.Element("properties"); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 71bf8880b0..456d7d667a 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -329,6 +329,7 @@ + diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index a440da483a..29d81e773e 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -53,7 +53,7 @@ namespace Umbraco.Tests.Macros { Name = "test", Alias = "test", - ScriptName = "~/usercontrols/menu.ascx" + MacroSource = "~/usercontrols/menu.ascx" }; macroModel.Properties.Add(new MacroPropertyModel(macroPropName, val)); @@ -77,8 +77,7 @@ namespace Umbraco.Tests.Macros var model = new MacroModel { MacroType = macroType, - ScriptName = "anything", - TypeName = "anything" + MacroSource = "anything" }; var filename = MacroRenderer.GetMacroFileName(model); if (expectedNonNull) diff --git a/src/Umbraco.Tests/Models/MacroTests.cs b/src/Umbraco.Tests/Models/MacroTests.cs index c1fda841c2..b4060134bd 100644 --- a/src/Umbraco.Tests/Models/MacroTests.cs +++ b/src/Umbraco.Tests/Models/MacroTests.cs @@ -20,7 +20,7 @@ namespace Umbraco.Tests.Models [Test] public void Can_Deep_Clone() { - var macro = new Macro(1, Guid.NewGuid(), true, 3, "test", "Test", "blah", false, true, true, "script"); + var macro = new Macro(1, Guid.NewGuid(), true, 3, "test", "Test", false, true, true, "~/script.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty(6, Guid.NewGuid(), "rewq", "REWQ", 1, "asdfasdf")); var clone = (Macro)macro.DeepClone(); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs index d4dbd51991..a526864d6b 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MacroRepositoryTest.cs @@ -37,7 +37,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test1", "Test", "~/views/macropartials/test.cshtml", MacroTypes.PartialView); ; Assert.Throws(() => repository.Save(macro)); @@ -94,11 +94,10 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(macro.Alias, Is.EqualTo("test1")); Assert.That(macro.CacheByPage, Is.EqualTo(false)); Assert.That(macro.CacheByMember, Is.EqualTo(false)); - Assert.That(macro.ControlType, Is.EqualTo("~/usercontrol/test1.ascx")); Assert.That(macro.DontRender, Is.EqualTo(true)); Assert.That(macro.Name, Is.EqualTo("Test1")); Assert.That(macro.CacheDuration, Is.EqualTo(0)); - Assert.That(macro.ScriptPath, Is.EqualTo("~/views/macropartials/test1.cshtml")); + Assert.That(macro.MacroSource, Is.EqualTo("~/views/macropartials/test1.cshtml")); Assert.That(macro.UseInEditor, Is.EqualTo(false)); } @@ -169,7 +168,7 @@ namespace Umbraco.Tests.Persistence.Repositories var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); // Act - var macro = new Macro("test", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test", "Test", "~/views/macropartials/test.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty("test", "Test", 0, "test")); repository.Save(macro); @@ -195,9 +194,8 @@ namespace Umbraco.Tests.Persistence.Repositories macro.CacheDuration = 1234; macro.CacheByPage = true; macro.CacheByMember = true; - macro.ControlType = ""; macro.DontRender = false; - macro.ScriptPath = "~/newpath.cshtml"; + macro.MacroSource = "~/newpath.cshtml"; macro.UseInEditor = true; repository.Save(macro); @@ -210,9 +208,8 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(macroUpdated.CacheDuration, Is.EqualTo(1234)); Assert.That(macroUpdated.CacheByPage, Is.EqualTo(true)); Assert.That(macroUpdated.CacheByMember, Is.EqualTo(true)); - Assert.That(macroUpdated.ControlType, Is.EqualTo("")); Assert.That(macroUpdated.DontRender, Is.EqualTo(false)); - Assert.That(macroUpdated.ScriptPath, Is.EqualTo("~/newpath.cshtml")); + Assert.That(macroUpdated.MacroSource, Is.EqualTo("~/newpath.cshtml")); Assert.That(macroUpdated.UseInEditor, Is.EqualTo(true)); } } @@ -293,7 +290,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); @@ -318,7 +315,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); macro.Properties.Add(new MacroProperty("blah1", "New1", 4, "test.editor")); repository.Save(macro); @@ -342,7 +339,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - var macro = new Macro("newmacro", "A new macro", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml"); + var macro = new Macro("newmacro", "A new macro", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); @@ -428,9 +425,9 @@ namespace Umbraco.Tests.Persistence.Repositories { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "~/views/macropartials/test3.cshtml")); + repository.Save(new Macro("test1", "Test1", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView)); + repository.Save(new Macro("test2", "Test2", "~/views/macropartials/test2.cshtml", MacroTypes.PartialView)); + repository.Save(new Macro("test3", "Tet3", "~/views/macropartials/test3.cshtml", MacroTypes.PartialView)); scope.Complete(); } diff --git a/src/Umbraco.Tests/Services/MacroServiceTests.cs b/src/Umbraco.Tests/Services/MacroServiceTests.cs index 44c5596bfc..ab8d18b249 100644 --- a/src/Umbraco.Tests/Services/MacroServiceTests.cs +++ b/src/Umbraco.Tests/Services/MacroServiceTests.cs @@ -28,9 +28,9 @@ namespace Umbraco.Tests.Services { var repository = new MacroRepository((IScopeAccessor) provider, CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); - repository.Save(new Macro("test1", "Test1", "~/usercontrol/test1.ascx", "~/views/macropartials/test1.cshtml")); - repository.Save(new Macro("test2", "Test2", "~/usercontrol/test2.ascx", "~/views/macropartials/test2.cshtml")); - repository.Save(new Macro("test3", "Tet3", "~/usercontrol/test3.ascx", "~/views/macropartials/test3.cshtml")); + repository.Save(new Macro("test1", "Test1", "~/views/macropartials/test1.cshtml", MacroTypes.PartialView)); + repository.Save(new Macro("test2", "Test2", "~/views/macropartials/test2.cshtml", MacroTypes.PartialView)); + repository.Save(new Macro("test3", "Tet3", "~/views/macropartials/test3.cshtml", MacroTypes.PartialView)); scope.Complete(); } } @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Services var macroService = ServiceContext.MacroService; // Act - var macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + var macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); macroService.Save(macro); //assert @@ -85,13 +85,13 @@ namespace Umbraco.Tests.Services var result = macroService.GetById(macro.Id); Assert.AreEqual("test", result.Alias); Assert.AreEqual("Test", result.Name); - Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.ScriptPath); + Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); Assert.AreEqual(1234, result.CacheDuration); result = macroService.GetById(macro.Key); Assert.AreEqual("test", result.Alias); Assert.AreEqual("Test", result.Name); - Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.ScriptPath); + Assert.AreEqual("~/Views/MacroPartials/Test.cshtml", result.MacroSource); Assert.AreEqual(1234, result.CacheDuration); } @@ -100,7 +100,7 @@ namespace Umbraco.Tests.Services { // Arrange var macroService = ServiceContext.MacroService; - var macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + var macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); macroService.Save(macro); // Act @@ -119,7 +119,7 @@ namespace Umbraco.Tests.Services { // Arrange var macroService = ServiceContext.MacroService; - IMacro macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + IMacro macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); macroService.Save(macro); // Act @@ -143,7 +143,7 @@ namespace Umbraco.Tests.Services { // Arrange var macroService = ServiceContext.MacroService; - IMacro macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + IMacro macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); macro.Properties.Add(new MacroProperty("blah", "Blah", 0, "blah")); macroService.Save(macro); @@ -174,7 +174,7 @@ namespace Umbraco.Tests.Services { // Arrange var macroService = ServiceContext.MacroService; - IMacro macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + IMacro macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); macro.Properties.Add(new MacroProperty("blah2", "Blah2", 1, "blah2")); macro.Properties.Add(new MacroProperty("blah3", "Blah3", 2, "blah3")); @@ -218,7 +218,7 @@ namespace Umbraco.Tests.Services public void Can_Add_And_Remove_Properties() { var macroService = ServiceContext.MacroService; - var macro = new Macro("test", "Test", scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + var macro = new Macro("test", "Test", "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); //adds some properties macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); @@ -253,7 +253,7 @@ namespace Umbraco.Tests.Services { // Arrange var macroService = ServiceContext.MacroService; - var macro = new Macro("test", string.Empty, scriptPath: "~/Views/MacroPartials/Test.cshtml", cacheDuration: 1234); + var macro = new Macro("test", string.Empty, "~/Views/MacroPartials/Test.cshtml", MacroTypes.PartialView, cacheDuration: 1234); // Act & Assert Assert.Throws(() => macroService.Save(macro)); diff --git a/src/Umbraco.Tests/Services/PackagingServiceTests.cs b/src/Umbraco.Tests/Services/PackagingServiceTests.cs index 36093e4feb..5a7d7320e1 100644 --- a/src/Umbraco.Tests/Services/PackagingServiceTests.cs +++ b/src/Umbraco.Tests/Services/PackagingServiceTests.cs @@ -23,7 +23,7 @@ namespace Umbraco.Tests.Services public void PackagingService_Can_Export_Macro() { // Arrange - var macro = new Macro("test1", "Test", "~/usercontrol/blah.ascx", "~/views/macropartials/test.cshtml"); + var macro = new Macro("test1", "Test", "~/views/macropartials/test.cshtml", MacroTypes.PartialView); ServiceContext.MacroService.Save(macro); // Act diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs index 353828f7dc..ff50281eec 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.cs @@ -1,63 +1,287 @@ using System; using System.Collections; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Web; +using System.Web.UI; using System.Web.UI.WebControls; -using Umbraco.Core.IO; +using System.Web.UI.HtmlControls; +using System.IO; using Umbraco.Core; +using Umbraco.Core.IO; using Umbraco.Core.Models; - +using Umbraco.Core.PropertyEditors; +using umbraco.cms.presentation.Trees; +using System.Linq; +using Umbraco.Web.UI; +using Umbraco.Web.UI.Pages; +using Umbraco.Core.Services; +using Umbraco.Web; +using Umbraco.Web.Composing; +using Umbraco.Web._Legacy.Controls; + namespace Umbraco.Web.UI.Umbraco.Developer.Macros { - public partial class EditMacro : global::umbraco.cms.presentation.developer.editMacro - { + public partial class EditMacro : UmbracoEnsuredPage + { + public EditMacro() + { + CurrentApp = Constants.Applications.Developer.ToString(); + } + + protected PlaceHolder Buttons; + protected Table MacroElements; + + public TabPage InfoTabPage; + public TabPage Parameters; + + private IMacro _macro; protected override void OnLoad(EventArgs e) { - base.OnLoad(e); + base.OnLoad(e); + + _macro = Services.MacroService.GetById(Convert.ToInt32(Request.QueryString["macroID"])); - PopulatePartialViewFiles(); - } - - /// - /// This ensures that the SelectedPartialView txt box value is set correctly when the m_macro object's - /// ScriptingFile property contains a full virtual path beginning with the MacroPartials path - /// - /// - /// - /// - protected override void PopulateFieldsOnLoad(IMacro macro, string macroTypeValue) - { - base.PopulateFieldsOnLoad(macro, macroTypeValue); - //check if the ScriptingFile property contains the MacroPartials path - if (macro.ScriptPath.IsNullOrWhiteSpace() == false && - (macro.ScriptPath.StartsWith(SystemDirectories.MvcViews + "/MacroPartials/") - || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled)))) + if (IsPostBack == false) { - SelectedPartialView.Text = macro.ScriptPath; + ClientTools + .SyncTree("-1," + _macro.Id, false); + + PopulateFieldsOnLoad(_macro); + + // Load elements from macro + MacroPropertyBind(); + + PopulatePartialViewFiles(); + + // Load usercontrols + PopulateUserControls(IOHelper.MapPath(SystemDirectories.UserControls)); + userControlList.Items.Insert(0, new ListItem("Browse usercontrols on server...", string.Empty)); + } } /// - /// This changes the macro type to a PartialViewMacro if the SelectedPartialView txt box has a value. - /// This then also updates the file path saved for the partial view to be the full virtual path, not just the file name. + /// Populates the control (textbox) values on page load /// - /// - /// - /// - /// - protected override void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroTypeValue) + /// + protected void PopulateFieldsOnLoad(IMacro macro) { - base.SetMacroValuesFromPostBack(macro, macroCachePeriod, macroTypeValue); - if (!SelectedPartialView.Text.IsNullOrWhiteSpace()) - { - macro.ScriptPath = SelectedPartialView.Text; - } + macroName.Text = macro.Name; + macroAlias.Text = macro.Alias; + macroKey.Text = macro.Key.ToString(); + cachePeriod.Text = macro.CacheDuration.ToInvariantString(); + macroRenderContent.Checked = macro.DontRender == false; + macroEditor.Checked = macro.UseInEditor; + cacheByPage.Checked = macro.CacheByPage; + cachePersonalized.Checked = macro.CacheByMember; + macroUserControl.Text = macro.MacroType == MacroTypes.UserControl ? macro.MacroSource : null; + SelectedPartialView.Text = macro.MacroType == MacroTypes.PartialView ? macro.MacroSource : null; } + /// + /// Sets the values on the Macro object from the values posted back before saving the macro + /// + protected void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string userControlValue, string partialViewValue) + { + macro.UseInEditor = macroEditor.Checked; + macro.DontRender = macroRenderContent.Checked == false; + macro.CacheByPage = cacheByPage.Checked; + macro.CacheByMember = cachePersonalized.Checked; + macro.CacheDuration = macroCachePeriod; + macro.Alias = macroAlias.Text; + macro.Name = macroName.Text; + macro.MacroSource = !userControlValue.IsNullOrWhiteSpace() ? userControlValue : partialViewValue; + macro.MacroType = !userControlValue.IsNullOrWhiteSpace() ? MacroTypes.UserControl : !partialViewValue.IsNullOrWhiteSpace() ? MacroTypes.PartialView : MacroTypes.Unknown; + } + + public void DeleteMacroProperty(object sender, EventArgs e) + { + var macroPropertyId = (HtmlInputHidden)((Control)sender).Parent.FindControl("macroPropertyID"); + + var property = _macro.Properties.Single(x => x.Id == int.Parse(macroPropertyId.Value)); + _macro.Properties.Remove(property); + + Services.MacroService.Save(_macro); + + MacroPropertyBind(); + } + + public void MacroPropertyBind() + { + macroProperties.DataSource = _macro.Properties.OrderBy(x => x.SortOrder); + macroProperties.DataBind(); + } + + public object CheckNull(object test) + { + return Convert.IsDBNull(test) ? 0 : test; + } + + protected IEnumerable GetMacroParameterEditors() + { + // we need to show the depracated ones for backwards compatibility + // FIXME not managing deprecated here?! + return Current.ParameterEditors; + } + + public void macroPropertyCreate(object sender, EventArgs e) + { + //enable add validators + var val1 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator1"); + var val2 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator4"); + var val3 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator5"); + val1.Enabled = true; + val2.Enabled = true; + val3.Enabled = true; + + Page.Validate(); + + if (Page.IsValid == false) + { + return; + } + + var macroPropertyAliasNew = (TextBox)((Control)sender).Parent.FindControl("macroPropertyAliasNew"); + var macroPropertyNameNew = (TextBox)((Control)sender).Parent.FindControl("macroPropertyNameNew"); + var macroPropertyTypeNew = (DropDownList)((Control)sender).Parent.FindControl("macroPropertyTypeNew"); + + if (macroPropertyAliasNew.Text != Services.TextService.Localize("general/new") + " " + Services.TextService.Localize("general/alias")) + { + if (_macro.Properties.ContainsKey(macroPropertyAliasNew.Text.Trim())) + { + //don't continue + return; + } + + _macro.Properties.Add(new MacroProperty( + macroPropertyAliasNew.Text.Trim(), + macroPropertyNameNew.Text.Trim(), + _macro.Properties.Any() ? _macro.Properties.Max(x => x.SortOrder) + 1 : 0, + macroPropertyTypeNew.SelectedValue)); + + Services.MacroService.Save(_macro); + + MacroPropertyBind(); + } + } + + public bool macroIsVisible(object isChecked) + { + return Convert.ToBoolean(isChecked); + } + + public void AddChooseList(object sender, EventArgs e) + { + if (IsPostBack == false) + { + var dropDown = (DropDownList)sender; + dropDown.Items.Insert(0, new ListItem("Choose...", string.Empty)); + } + } + + private void PopulateUserControls(string path) + { + var directoryInfo = new DirectoryInfo(path); + if (directoryInfo.Exists == false) return; + + var rootDir = IOHelper.MapPath(SystemDirectories.UserControls); + + foreach (var uc in directoryInfo.GetFiles("*.ascx")) + { + userControlList.Items.Add( + new ListItem(SystemDirectories.UserControls + + uc.FullName.Substring(rootDir.Length).Replace(IOHelper.DirSepChar, '/'))); + + } + foreach (var dir in directoryInfo.GetDirectories()) + PopulateUserControls(dir.FullName); + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + EnsureChildControls(); + } + + protected override void CreateChildControls() + { + base.CreateChildControls(); + + // Tab setup + InfoTabPage = TabView1.NewTabPage("Macro Properties"); + InfoTabPage.Controls.Add(Pane1); + InfoTabPage.Controls.Add(Pane1_2); + InfoTabPage.Controls.Add(Pane1_3); + InfoTabPage.Controls.Add(Pane1_4); + + Parameters = TabView1.NewTabPage("Parameters"); + Parameters.Controls.Add(Panel2); + + var save = TabView1.Menu.NewButton(); + save.ButtonType = MenuButtonType.Primary; + save.Text = Services.TextService.Localize("save"); + save.ID = "save"; + save.Click += Save_Click; + } + + void Save_Click(object sender, EventArgs e) + { + + Page.Validate(); + + ClientTools + .SyncTree("-1," + _macro.Id.ToInvariantString(), true); //true forces the reload + + + var tempCachePeriod = cachePeriod.Text; + if (tempCachePeriod == string.Empty) + tempCachePeriod = "0"; + + SetMacroValuesFromPostBack(_macro, Convert.ToInt32(tempCachePeriod), macroUserControl.Text, SelectedPartialView.Text); + + // save elements + // this is oh so completely broken + var aliases = new Dictionary(); + foreach (RepeaterItem item in macroProperties.Items) + { + var macroPropertyId = (HtmlInputHidden)item.FindControl("macroPropertyID"); + var macroElementName = (TextBox)item.FindControl("macroPropertyName"); + var macroElementAlias = (TextBox)item.FindControl("macroPropertyAlias"); + var macroElementSortOrder = (TextBox)item.FindControl("macroPropertySortOrder"); + var macroElementType = (DropDownList)item.FindControl("macroPropertyType"); + + var prop = _macro.Properties.Single(x => x.Id == int.Parse(macroPropertyId.Value)); + var sortOrder = 0; + int.TryParse(macroElementSortOrder.Text, out sortOrder); + + var alias = macroElementAlias.Text.Trim(); + if (prop.Alias != alias) // changing the alias + { + // use a temp alias to avoid collision if eg swapping aliases + var tempAlias = Guid.NewGuid().ToString("N").Substring(0, 8); + aliases[tempAlias] = alias; + alias = tempAlias; + } + + _macro.Properties.UpdateProperty( + prop.Alias, + macroElementName.Text.Trim(), + sortOrder, + macroElementType.SelectedValue, + alias); + } + + // now apply the real aliases, should not collide + foreach (var kvp in aliases) + _macro.Properties.UpdateProperty(kvp.Key, newAlias: kvp.Value); + + Services.MacroService.Save(_macro); + + ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Save, "Macro saved", ""); + + MacroPropertyBind(); + } + /// /// Populate the drop down list for partial view files /// diff --git a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs index a1febaa2ba..617862cd6a 100644 --- a/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs +++ b/src/Umbraco.Web.UI/umbraco/developer/Macros/EditMacro.aspx.designer.cs @@ -37,6 +37,186 @@ namespace Umbraco.Web.UI.Umbraco.Developer.Macros { /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// - protected global::System.Web.UI.WebControls.DropDownList PartialViewList; + protected global::System.Web.UI.WebControls.DropDownList PartialViewList; + + /// + /// TabView1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.TabView TabView1; + + /// + /// Pane1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.Pane Pane1; + + /// + /// macroPane control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlTable macroPane; + + /// + /// macroName control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox macroName; + + /// + /// macroAlias control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox macroAlias; + + /// + /// macroAlias control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Label macroKey; + + /// + /// Pane1_2 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_2; + + /// + /// macroUserControl control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox macroUserControl; + + /// + /// userControlList control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.DropDownList userControlList; + + /// + /// Pane1_3 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_3; + + /// + /// Table1 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlTable Table1; + + /// + /// macroEditor control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox macroEditor; + + /// + /// macroRenderContent control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox macroRenderContent; + + /// + /// Pane1_4 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_4; + + /// + /// Table3 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.HtmlControls.HtmlTable Table3; + + /// + /// cachePeriod control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.TextBox cachePeriod; + + /// + /// cacheByPage control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox cacheByPage; + + /// + /// cachePersonalized control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.CheckBox cachePersonalized; + + /// + /// Panel2 control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::Umbraco.Web._Legacy.Controls.Pane Panel2; + + /// + /// macroProperties control. + /// + /// + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// + protected global::System.Web.UI.WebControls.Repeater macroProperties; } } diff --git a/src/Umbraco.Web/Editors/MacroController.cs b/src/Umbraco.Web/Editors/MacroController.cs index dc4d42a48c..af30f0fc28 100644 --- a/src/Umbraco.Web/Editors/MacroController.cs +++ b/src/Umbraco.Web/Editors/MacroController.cs @@ -143,7 +143,7 @@ namespace Umbraco.Web.Editors { Alias = macroName.ToSafeAlias(), Name = macroName, - ScriptPath = model.VirtualPath.EnsureStartsWith("~") + MacroSource = model.VirtualPath.EnsureStartsWith("~") }; Services.MacroService.Save(macro); // may throw diff --git a/src/Umbraco.Web/Macros/MacroModel.cs b/src/Umbraco.Web/Macros/MacroModel.cs index 28aad1b777..bea07cebc5 100644 --- a/src/Umbraco.Web/Macros/MacroModel.cs +++ b/src/Umbraco.Web/Macros/MacroModel.cs @@ -19,13 +19,7 @@ namespace Umbraco.Web.Macros public MacroTypes MacroType { get; set; } - public string TypeName { get; set; } - - public string ScriptName { get; set; } - - public string ScriptCode { get; set; } - - public string ScriptLanguage { get; set; } + public string MacroSource { get; set; } public int CacheDuration { get; set; } @@ -49,8 +43,8 @@ namespace Umbraco.Web.Macros Id = macro.Id; Name = macro.Name; Alias = macro.Alias; - TypeName = macro.ControlType; - ScriptName = macro.ScriptPath; + MacroType = macro.MacroType; + MacroSource = macro.MacroSource; CacheDuration = macro.CacheDuration; CacheByPage = macro.CacheByPage; CacheByMember = macro.CacheByMember; @@ -59,8 +53,7 @@ namespace Umbraco.Web.Macros foreach (var prop in macro.Properties) Properties.Add(new MacroPropertyModel(prop.Alias, string.Empty, prop.EditorAlias)); - // can convert enums - MacroType = MacroService.GetMacroType(macro); + MacroType = macro.MacroType; } } } diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index b96453d3d2..8320e881b1 100644 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -46,9 +46,7 @@ namespace Umbraco.Web.Macros { var id = new StringBuilder(); - var alias = string.IsNullOrEmpty(model.ScriptCode) - ? model.Alias - : GenerateCacheKeyFromCode(model.ScriptCode); + var alias = model.Alias; id.AppendFormat("{0}-", alias); if (model.CacheByPage) @@ -173,10 +171,8 @@ namespace Umbraco.Web.Macros switch (model.MacroType) { case MacroTypes.PartialView: - filename = model.ScriptName; //partial views are saved with their full virtual path - break; case MacroTypes.UserControl: - filename = model.TypeName; //user controls are saved with their full virtual path + filename = model.MacroSource; //user controls & partial views are saved with their full virtual path break; default: // not file-based, or not supported @@ -314,7 +310,7 @@ namespace Umbraco.Web.Macros { Name = macro.Name, Alias = macro.Alias, - ItemKey = macro.ScriptName, + MacroSource = macro.MacroSource, Exception = e, Behaviour = UmbracoConfig.For.UmbracoSettings().Content.MacroErrorBehaviour }; @@ -362,17 +358,17 @@ namespace Umbraco.Web.Macros { case MacroTypes.PartialView: return ExecuteMacroWithErrorWrapper(model, - $"Executing PartialView: TypeName=\"{model.TypeName}\", ScriptName=\"{model.ScriptName}\".", + $"Executing PartialView: MacroSource=\"{model.MacroSource}\".", "Executed PartialView.", () => ExecutePartialView(model), - () => textService.Localize("errors/macroErrorLoadingPartialView", new[] { model.ScriptName })); + () => textService.Localize("errors/macroErrorLoadingPartialView", new[] { model.MacroSource })); case MacroTypes.UserControl: return ExecuteMacroWithErrorWrapper(model, - $"Loading UserControl: TypeName=\"{model.TypeName}\".", + $"Loading UserControl: MacroSource=\"{model.MacroSource}\".", "Loaded UserControl.", () => ExecuteUserControl(model), - () => textService.Localize("errors/macroErrorLoadingUsercontrol", new[] { model.TypeName })); + () => textService.Localize("errors/macroErrorLoadingUsercontrol", new[] { model.MacroSource })); //case MacroTypes.Script: default: @@ -418,9 +414,9 @@ namespace Umbraco.Web.Macros public static MacroContent ExecuteUserControl(MacroModel macro) { // add tilde for v4 defined macros - if (string.IsNullOrEmpty(macro.TypeName) == false - && macro.TypeName.StartsWith("~") == false) - macro.TypeName = "~/" + macro.TypeName; + if (string.IsNullOrEmpty(macro.MacroSource) == false + && macro.MacroSource.StartsWith("~") == false) + macro.MacroSource = "~/" + macro.MacroSource; var engine = new UserControlMacroEngine(); return engine.Execute(macro); diff --git a/src/Umbraco.Web/Macros/PartialViewMacroController.cs b/src/Umbraco.Web/Macros/PartialViewMacroController.cs index cf31de3bac..a46c1995f4 100644 --- a/src/Umbraco.Web/Macros/PartialViewMacroController.cs +++ b/src/Umbraco.Web/Macros/PartialViewMacroController.cs @@ -34,7 +34,7 @@ namespace Umbraco.Web.Macros _macro.Alias, _macro.Name, _macro.Properties.ToDictionary(x => x.Key, x => (object)x.Value)); - return PartialView(_macro.ScriptName, model); + return PartialView(_macro.MacroSource, model); } } } diff --git a/src/Umbraco.Web/Macros/PartialViewMacroEngine.cs b/src/Umbraco.Web/Macros/PartialViewMacroEngine.cs index 4488dee2ec..fa71436c34 100644 --- a/src/Umbraco.Web/Macros/PartialViewMacroEngine.cs +++ b/src/Umbraco.Web/Macros/PartialViewMacroEngine.cs @@ -65,7 +65,7 @@ namespace Umbraco.Web.Macros { if (macro == null) throw new ArgumentNullException(nameof(macro)); if (content == null) throw new ArgumentNullException(nameof(content)); - if (macro.ScriptName.IsNullOrWhiteSpace()) throw new ArgumentException("The ScriptName property of the macro object cannot be null or empty"); + if (macro.MacroSource.IsNullOrWhiteSpace()) throw new ArgumentException("The MacroSource property of the macro object cannot be null or empty"); var http = _getHttpContext(); var umbCtx = _getUmbracoContext(); diff --git a/src/Umbraco.Web/Macros/UserControlMacroEngine.cs b/src/Umbraco.Web/Macros/UserControlMacroEngine.cs index 790425f649..67122f9f56 100644 --- a/src/Umbraco.Web/Macros/UserControlMacroEngine.cs +++ b/src/Umbraco.Web/Macros/UserControlMacroEngine.cs @@ -14,7 +14,7 @@ namespace Umbraco.Web.Macros { public MacroContent Execute(MacroModel model) { - var filename = model.TypeName; + var filename = model.MacroSource; // ensure the file exists var path = IOHelper.FindFile(filename); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 5a39523707..d589c06bdd 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -1150,9 +1150,6 @@ ASPXCodeBehind - - ASPXCodeBehind - ASPXCodeBehind diff --git a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs index ced330c638..53ed58810c 100644 --- a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs +++ b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/PackagerUtility.cs @@ -132,13 +132,8 @@ namespace umbraco.cms.businesslogic.packager if (appendFile) { - //TODO: Clearly the packager hasn't worked very well for packaging Partial Views to date since there is no logic in here for that - - //if (!string.IsNullOrEmpty(mcr.ScriptingFile)) - // AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.MacroScripts) + "/" + mcr.ScriptingFile, packageDirectory, doc); - - if (!string.IsNullOrEmpty(mcr.ControlType)) - AppendFileToManifest(mcr.ControlType, packageDirectory, doc); + if (!string.IsNullOrEmpty(mcr.MacroSource)) + AppendFileToManifest(mcr.MacroSource, packageDirectory, doc); } var serializer = new EntityXmlSerializer(); diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs index 2b34bb0d04..12166cae96 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/macroTasks.cs @@ -12,7 +12,7 @@ namespace Umbraco.Web var macro = Current.Services.MacroService.GetByAlias(Alias); if (macro == null) { - macro = new Macro(Alias, Alias); + macro = new Macro(Alias, Alias, string.Empty, MacroTypes.Unknown); Current.Services.MacroService.Save(macro); } _returnUrl = string.Format("developer/Macros/editMacro.aspx?macroID={0}", macro.Id); diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs deleted file mode 100644 index 2183f5fc83..0000000000 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/developer/Macros/editMacro.aspx.cs +++ /dev/null @@ -1,469 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Web.UI; -using System.Web.UI.WebControls; -using System.Web.UI.HtmlControls; -using System.IO; -using Umbraco.Core; -using Umbraco.Core.IO; -using Umbraco.Core.Models; -using Umbraco.Core.PropertyEditors; -using umbraco.cms.presentation.Trees; -using System.Linq; -using Umbraco.Web.UI; -using Umbraco.Web.UI.Pages; -using Umbraco.Core.Services; -using Umbraco.Web; -using Umbraco.Web.Composing; -using Umbraco.Web._Legacy.Controls; - -namespace umbraco.cms.presentation.developer -{ - /// - /// Summary description for editMacro. - /// - public partial class editMacro : UmbracoEnsuredPage - { - public editMacro() - { - CurrentApp = Constants.Applications.Developer.ToString(); - } - - protected PlaceHolder Buttons; - protected Table MacroElements; - - public TabPage InfoTabPage; - public TabPage Parameters; - - private IMacro _macro; - - protected void Page_Load(object sender, EventArgs e) - { - _macro = Services.MacroService.GetById(Convert.ToInt32(Request.QueryString["macroID"])); - - if (IsPostBack == false) - { - ClientTools - .SyncTree("-1," + _macro.Id, false); - - string tempMacroType = _macro.ControlType ?? ""; - - PopulateFieldsOnLoad(_macro, tempMacroType); - - // Load elements from macro - MacroPropertyBind(); - - // Load usercontrols - PopulateUserControls(IOHelper.MapPath(SystemDirectories.UserControls)); - userControlList.Items.Insert(0, new ListItem("Browse usercontrols on server...", string.Empty)); - - } - } - - /// - /// Populates the control (textbox) values on page load - /// - /// - /// - /// - protected virtual void PopulateFieldsOnLoad(IMacro macro, string macroTypeValue) - { - macroName.Text = macro.Name; - macroAlias.Text = macro.Alias; - macroKey.Text = macro.Key.ToString(); - cachePeriod.Text = macro.CacheDuration.ToInvariantString(); - macroRenderContent.Checked = macro.DontRender == false; - macroEditor.Checked = macro.UseInEditor; - cacheByPage.Checked = macro.CacheByPage; - cachePersonalized.Checked = macro.CacheByMember; - - macroUserControl.Text = macroTypeValue; - } - - /// - /// Sets the values on the Macro object from the values posted back before saving the macro - /// - protected virtual void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroTypeValue) - { - macro.UseInEditor = macroEditor.Checked; - macro.DontRender = macroRenderContent.Checked == false; - macro.CacheByPage = cacheByPage.Checked; - macro.CacheByMember = cachePersonalized.Checked; - macro.CacheDuration = macroCachePeriod; - macro.Alias = macroAlias.Text; - macro.Name = macroName.Text; - macro.ControlType = macroTypeValue; - } - - public void DeleteMacroProperty(object sender, EventArgs e) - { - var macroPropertyId = (HtmlInputHidden)((Control)sender).Parent.FindControl("macroPropertyID"); - - var property = _macro.Properties.Single(x => x.Id == int.Parse(macroPropertyId.Value)); - _macro.Properties.Remove(property); - - Services.MacroService.Save(_macro); - - MacroPropertyBind(); - } - - public void MacroPropertyBind() - { - macroProperties.DataSource = _macro.Properties.OrderBy(x => x.SortOrder); - macroProperties.DataBind(); - } - - public object CheckNull(object test) - { - return Convert.IsDBNull(test) ? 0 : test; - } - - protected IEnumerable GetMacroParameterEditors() - { - // we need to show the depracated ones for backwards compatibility - // FIXME not managing deprecated here?! - return Current.ParameterEditors; - } - - public void macroPropertyCreate(object sender, EventArgs e) - { - //enable add validators - var val1 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator1"); - var val2 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator4"); - var val3 = (RequiredFieldValidator)((Control)sender).Parent.FindControl("RequiredFieldValidator5"); - val1.Enabled = true; - val2.Enabled = true; - val3.Enabled = true; - - Page.Validate(); - - if (Page.IsValid == false) - { - return; - } - - var macroPropertyAliasNew = (TextBox)((Control)sender).Parent.FindControl("macroPropertyAliasNew"); - var macroPropertyNameNew = (TextBox)((Control)sender).Parent.FindControl("macroPropertyNameNew"); - var macroPropertyTypeNew = (DropDownList)((Control)sender).Parent.FindControl("macroPropertyTypeNew"); - - if (macroPropertyAliasNew.Text != Services.TextService.Localize("general/new") + " " + Services.TextService.Localize("general/alias")) - { - if (_macro.Properties.ContainsKey(macroPropertyAliasNew.Text.Trim())) - { - //don't continue - return; - } - - _macro.Properties.Add(new MacroProperty( - macroPropertyAliasNew.Text.Trim(), - macroPropertyNameNew.Text.Trim(), - _macro.Properties.Any() ? _macro.Properties.Max(x => x.SortOrder) + 1 : 0, - macroPropertyTypeNew.SelectedValue)); - - Services.MacroService.Save(_macro); - - MacroPropertyBind(); - } - } - - public bool macroIsVisible(object isChecked) - { - return Convert.ToBoolean(isChecked); - } - - public void AddChooseList(object sender, EventArgs e) - { - if (IsPostBack == false) - { - var dropDown = (DropDownList)sender; - dropDown.Items.Insert(0, new ListItem("Choose...", string.Empty)); - } - } - - private void PopulateUserControls(string path) - { - var directoryInfo = new DirectoryInfo(path); - if (directoryInfo.Exists == false) return; - - var rootDir = IOHelper.MapPath(SystemDirectories.UserControls); - - foreach (var uc in directoryInfo.GetFiles("*.ascx")) - { - userControlList.Items.Add( - new ListItem(SystemDirectories.UserControls + - uc.FullName.Substring(rootDir.Length).Replace(IOHelper.DirSepChar, '/'))); - - } - foreach (var dir in directoryInfo.GetDirectories()) - PopulateUserControls(dir.FullName); - } - - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - EnsureChildControls(); - } - - protected override void CreateChildControls() - { - base.CreateChildControls(); - - // Tab setup - InfoTabPage = TabView1.NewTabPage("Macro Properties"); - InfoTabPage.Controls.Add(Pane1); - InfoTabPage.Controls.Add(Pane1_2); - InfoTabPage.Controls.Add(Pane1_3); - InfoTabPage.Controls.Add(Pane1_4); - - Parameters = TabView1.NewTabPage("Parameters"); - Parameters.Controls.Add(Panel2); - - var save = TabView1.Menu.NewButton(); - save.ButtonType = MenuButtonType.Primary; - save.Text = Services.TextService.Localize("save"); - save.ID = "save"; - save.Click += Save_Click; - } - - void Save_Click(object sender, EventArgs e) - { - - Page.Validate(); - - ClientTools - .SyncTree("-1," + _macro.Id.ToInvariantString(), true); //true forces the reload - - - var tempCachePeriod = cachePeriod.Text; - if (tempCachePeriod == string.Empty) - tempCachePeriod = "0"; - var tempMacroType = macroUserControl.Text; - - SetMacroValuesFromPostBack(_macro, Convert.ToInt32(tempCachePeriod), tempMacroType); - - // save elements - // this is oh so completely broken - var aliases = new Dictionary(); - foreach (RepeaterItem item in macroProperties.Items) - { - var macroPropertyId = (HtmlInputHidden)item.FindControl("macroPropertyID"); - var macroElementName = (TextBox)item.FindControl("macroPropertyName"); - var macroElementAlias = (TextBox)item.FindControl("macroPropertyAlias"); - var macroElementSortOrder = (TextBox)item.FindControl("macroPropertySortOrder"); - var macroElementType = (DropDownList)item.FindControl("macroPropertyType"); - - var prop = _macro.Properties.Single(x => x.Id == int.Parse(macroPropertyId.Value)); - var sortOrder = 0; - int.TryParse(macroElementSortOrder.Text, out sortOrder); - - var alias = macroElementAlias.Text.Trim(); - if (prop.Alias != alias) // changing the alias - { - // use a temp alias to avoid collision if eg swapping aliases - var tempAlias = Guid.NewGuid().ToString("N").Substring(0, 8); - aliases[tempAlias] = alias; - alias = tempAlias; - } - - _macro.Properties.UpdateProperty( - prop.Alias, - macroElementName.Text.Trim(), - sortOrder, - macroElementType.SelectedValue, - alias); - } - - // now apply the real aliases, should not collide - foreach (var kvp in aliases) - _macro.Properties.UpdateProperty(kvp.Key, newAlias: kvp.Value); - - Services.MacroService.Save(_macro); - - ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Save, "Macro saved", ""); - - MacroPropertyBind(); - } - - /// - /// TabView1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.TabView TabView1; - - /// - /// Pane1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Pane1; - - /// - /// macroPane control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlTable macroPane; - - /// - /// macroName control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroName; - - /// - /// macroAlias control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroAlias; - - /// - /// macroAlias control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Label macroKey; - - /// - /// Pane1_2 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_2; - - /// - /// macroUserControl control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox macroUserControl; - - /// - /// userControlList control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.DropDownList userControlList; - - /// - /// Pane1_3 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_3; - - /// - /// Table1 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlTable Table1; - - /// - /// macroEditor control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox macroEditor; - - /// - /// macroRenderContent control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox macroRenderContent; - - /// - /// Pane1_4 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Pane1_4; - - /// - /// Table3 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.HtmlControls.HtmlTable Table3; - - /// - /// cachePeriod control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.TextBox cachePeriod; - - /// - /// cacheByPage control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox cacheByPage; - - /// - /// cachePersonalized control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.CheckBox cachePersonalized; - - /// - /// Panel2 control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::Umbraco.Web._Legacy.Controls.Pane Panel2; - - /// - /// macroProperties control. - /// - /// - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// - protected global::System.Web.UI.WebControls.Repeater macroProperties; - } - -} diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Macro.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Macro.cs index 1847871ac5..d9da799f82 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Macro.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/templateControls/Macro.cs @@ -150,7 +150,7 @@ namespace umbraco.presentation.templateControls if (extension.InvariantEndsWith(".cshtml") == false && extension.InvariantEndsWith(".vbhtml") == false) throw new NotSupportedException(""); - tempMacro.ScriptName = FileLocation; + tempMacro.MacroSource = FileLocation; tempMacro.MacroType = MacroTypes.PartialView; if (string.IsNullOrEmpty(Attributes["Cache"]) == false) From 171a82e233e3b400b6d9553ddf1ceeac5ed13d2d Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 1 May 2018 12:23:09 +1000 Subject: [PATCH 58/58] Adds more description to CustomRouteUrlProvider --- src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs index 926db253c8..138155c8f6 100644 --- a/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs +++ b/src/Umbraco.Web/Routing/CustomRouteUrlProvider.cs @@ -1,18 +1,20 @@ using System; using System.Collections.Generic; using System.Globalization; +using Umbraco.Web.Mvc; +using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Web.Routing { /// - /// This url provider is used purely to deal with umbraco custom routes that utilize UmbracoVirtualNodeRouteHandler and will return + /// This url provider is used purely to deal with umbraco custom routes that utilize and will return /// the URL returned from the current PublishedContentRequest.PublishedContent (virtual node) if the request is in fact a virtual route and /// the id that is being requested matches the id of the current PublishedContentRequest.PublishedContent. /// internal class CustomRouteUrlProvider : IUrlProvider { /// - /// This will simply return the URL that is returned by the assigned IPublishedContent if this is a custom route + /// This will return the URL that is returned by the assigned custom if this is a custom route /// /// /// @@ -30,7 +32,11 @@ namespace Umbraco.Web.Routing if (umbracoContext.HttpContext.Request.RequestContext.RouteData == null) return null; if (umbracoContext.HttpContext.Request.RequestContext.RouteData.DataTokens == null) return null; if (umbracoContext.HttpContext.Request.RequestContext.RouteData.DataTokens.ContainsKey(Umbraco.Core.Constants.Web.CustomRouteDataToken) == false) return null; - //ok so it's a custom route with published content assigned, check if the id being requested for is the same id as the assigned published content + + //If we get this far, it means it's a custom route with published content assigned, check if the id being requested for is the same id as the assigned published content + //NOTE: This looks like it might cause an infinite loop because PublishedContentBase.Url calls into UmbracoContext.Current.UrlProvider.GetUrl which calls back into the IUrlProvider pipeline + // but the specific purpose of this is that a developer is using their own IPublishedContent that returns a specific Url and doesn't go back into the UrlProvider pipeline. + //TODO: We could put a try/catch here just in case, else we could do some reflection checking to see if the implementation is PublishedContentBase and the Url property is not overridden. return id == umbracoContext.PublishedRequest.PublishedContent.Id ? umbracoContext.PublishedRequest.PublishedContent.Url : null;