From e60a5a4a8338009d7a12794d58f91babb518fe38 Mon Sep 17 00:00:00 2001 From: Stephan Date: Fri, 26 Jan 2018 17:55:20 +0100 Subject: [PATCH] DataType refactoring - in progress --- .../Cache/DictionaryCacheProvider.cs | 3 +- .../Cache/DictionaryCacheProviderBase.cs | 7 +- .../Cache/HttpRequestCacheProvider.cs | 3 +- .../Cache/HttpRuntimeCacheProvider.cs | 3 +- .../Cache/ObjectCacheRuntimeCacheProvider.cs | 3 +- .../Composing/LightInjectExtensions.cs | 4 + src/Umbraco.Core/Constants-Conventions.cs | 4 +- src/Umbraco.Core/Deploy/IPreValueConnector.cs | 2 +- src/Umbraco.Core/Enum.cs | 99 +++++------ src/Umbraco.Core/Manifest/ManifestParser.cs | 17 +- .../Install/DatabaseSchemaCreator.cs | 2 +- .../Migrations/MigrationBase_Extra.cs | 9 +- .../Migrations/Upgrade/UmbracoPlan.cs | 2 +- .../Upgrade/V_8_0_0/RefactorDataType.cs | 23 ++- .../Models/ContentTypeBaseExtensions.cs | 6 +- src/Umbraco.Core/Models/PreValue.cs | 48 ------ src/Umbraco.Core/Models/PreValueCollection.cs | 90 ---------- src/Umbraco.Core/Models/Property.cs | 2 +- src/Umbraco.Core/Models/PropertyType.cs | 2 +- src/Umbraco.Core/Models/ValueStorageType.cs | 6 +- src/Umbraco.Core/ObjectExtensions.cs | 23 ++- .../Persistence/Dtos/DataTypeDto.cs | 4 +- .../Persistence/Dtos/DataTypePreValueDto.cs | 50 ------ .../Dtos/PropertyTypeReadOnlyDto.cs | 2 +- .../Persistence/Factories/PropertyFactory.cs | 2 +- .../Implement/ContentRepositoryBase.cs | 47 +++--- .../Implement/ContentTypeRepositoryBase.cs | 4 +- .../Implement/DataTypeRepository.cs | 33 ++-- .../Implement/MemberTypeRepository.cs | 2 +- .../PropertyEditors/ConfigurationEditor.cs | 9 +- .../ConfigurationEditorOfTConfiguration.cs | 28 ++-- .../PropertyEditors/IDataTypeConfiguration.cs | 13 -- .../PropertyEditors/PropertyEditor.cs | 38 ++--- .../PropertyEditors/ValueEditor.cs | 67 +++++--- .../PropertyEditors/ValueTypes.cs | 2 +- src/Umbraco.Core/ReflectionUtilities.cs | 17 +- .../Runtime/CoreRuntimeComponent.cs | 12 +- .../Services/Implement/PackagingService.cs | 27 +-- src/Umbraco.Core/Umbraco.Core.csproj | 4 - .../Manifest/ManifestParserTests.cs | 4 +- .../Collections/PropertyCollectionTests.cs | 6 +- src/Umbraco.Tests/Models/ContentTypeTests.cs | 2 +- src/Umbraco.Tests/Models/DataTypeTests.cs | 4 +- .../Models/Mapping/AutoMapperTests.cs | 7 +- .../Mapping/ContentTypeModelMappingTests.cs | 35 +--- src/Umbraco.Tests/Models/MediaXmlTest.cs | 2 +- .../Models/PreValueCollectionTests.cs | 51 ------ .../Models/PropertyGroupTests.cs | 16 +- src/Umbraco.Tests/Models/PropertyTypeTests.cs | 8 +- src/Umbraco.Tests/Models/VariationTests.cs | 8 +- .../Querying/ContentTypeSqlMappingTests.cs | 2 +- .../Repositories/ContentRepositoryTest.cs | 4 +- .../Repositories/ContentTypeRepositoryTest.cs | 2 +- .../DataTypeDefinitionRepositoryTest.cs | 117 ------------- .../Persistence/SqlCeTableByTableTest.cs | 15 -- .../PropertyEditors/ImageCropperTest.cs | 10 +- ...cyPropertyEditorIdToAliasConverterTests.cs | 70 -------- .../MultiValuePropertyEditorTests.cs | 83 ++++++---- .../PropertyEditorValueEditorTests.cs | 4 +- .../Published/NestedContentTests.cs | 57 ++++--- .../PublishedContent/PublishedContentTests.cs | 2 +- .../PublishedContent/PublishedMediaTests.cs | 2 +- .../Services/ContentServiceTests.cs | 14 +- .../Services/DataTypeServiceTests.cs | 155 ------------------ .../Services/Importing/PackageImportTests.cs | 21 +-- .../Services/PreValueConverterTests.cs | 93 ----------- .../Entities/MockedContentTypes.cs | 20 +-- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 4 +- src/Umbraco.Tests/Umbraco.Tests.csproj | 3 - .../EnsureListViewDataTypeIsCreated.cs | 23 +-- .../ContentPropertyDisplayConverter.cs | 4 +- ...taTypeConfigurationFieldDisplayResolver.cs | 2 +- .../Models/Mapping/DataTypeMapperProfile.cs | 2 +- .../Mapping/PropertyTypeGroupResolver.cs | 2 +- .../Mapping/TabsAndPropertiesResolver.cs | 2 +- .../ContentPicker2PropertyEditor.cs | 2 +- .../PropertyEditors/DatePropertyEditor.cs | 2 +- .../PropertyEditors/DateTimePropertyEditor.cs | 2 +- .../DropDownMultipleConfigurationEditor.cs | 4 +- .../FileUploadPropertyEditor.cs | 99 +---------- .../ImageCropperPropertyEditor.cs | 13 +- .../PropertyEditors/ListViewConfiguration.cs | 87 +++++++--- .../PropertyEditors/ListViewPropertyEditor.cs | 2 +- .../MediaPicker2PropertyEditor.cs | 2 +- .../MemberPicker2PropertyEditor.cs | 2 +- .../MultiNodePickerConfigurationEditor.cs | 4 +- .../MultiNodeTreePicker2PropertyEditor.cs | 2 +- .../MultipleTextStringConfigurationEditor.cs | 2 +- .../MultipleTextStringPropertyEditor.cs | 19 +-- .../NestedContentConfiguration.cs | 23 ++- .../NestedContentPropertyEditor.cs | 67 ++------ .../PublishValueValueEditor.cs | 47 ++---- .../PublishValuesMultipleValueEditor.cs | 19 +-- .../RelatedLinks2PropertyEditor.cs | 2 +- .../PropertyEditors/RichTextConfiguration.cs | 16 ++ .../RichTextConfigurationEditor.cs | 67 +------- .../PropertyEditors/RichTextPropertyEditor.cs | 27 ++- .../PropertyEditors/TagConfigurationEditor.cs | 4 +- .../PropertyEditors/TagsPropertyEditor.cs | 2 +- .../PropertyEditors/TextOnlyValueEditor.cs | 2 +- .../PropertyEditors/TextboxConfiguration.cs | 2 +- .../UploadFileTypeValidator.cs | 23 +-- .../UserPickerPropertyEditor.cs | 2 +- .../NestedContentManyValueConverter.cs | 4 +- .../NestedContentSingleValueConverter.cs | 2 +- .../NestedContentValueConverterBase.cs | 2 +- .../ValueListConfigurationEditor.cs | 2 +- .../NuCache/PublishedContent.cs | 2 +- src/Umbraco.Web/Umbraco.Web.csproj | 1 + .../umbraco.presentation/library.cs | 54 ------ 110 files changed, 662 insertions(+), 1525 deletions(-) delete mode 100644 src/Umbraco.Core/Models/PreValue.cs delete mode 100644 src/Umbraco.Core/Models/PreValueCollection.cs delete mode 100644 src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs delete mode 100644 src/Umbraco.Core/PropertyEditors/IDataTypeConfiguration.cs delete mode 100644 src/Umbraco.Tests/Models/PreValueCollectionTests.cs delete mode 100644 src/Umbraco.Tests/PropertyEditors/LegacyPropertyEditorIdToAliasConverterTests.cs delete mode 100644 src/Umbraco.Tests/Services/PreValueConverterTests.cs create mode 100644 src/Umbraco.Web/PropertyEditors/RichTextConfiguration.cs diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs index 22f9209acc..98dceb80b0 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs +++ b/src/Umbraco.Core/Cache/DictionaryCacheProvider.cs @@ -140,7 +140,8 @@ namespace Umbraco.Core.Cache // in order NOT to cache exceptions _items.TryRemove(cacheKey, out result); - throw eh.Exception; // throw once! + eh.Exception.Throw(); // throw once! + return null; // never reached } } } diff --git a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs b/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs index cc62fbac8d..6baa2cf0ed 100644 --- a/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs +++ b/src/Umbraco.Core/Cache/DictionaryCacheProviderBase.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Runtime.ExceptionServices; using System.Text.RegularExpressions; using Umbraco.Core.Composing; @@ -45,7 +46,7 @@ namespace Umbraco.Core.Cache } catch (Exception e) { - return new ExceptionHolder(e); + return new ExceptionHolder(ExceptionDispatchInfo.Capture(e)); } }); } @@ -75,12 +76,12 @@ namespace Umbraco.Core.Cache internal class ExceptionHolder { - public ExceptionHolder(Exception e) + public ExceptionHolder(ExceptionDispatchInfo e) { Exception = e; } - public Exception Exception { get; private set; } + public ExceptionDispatchInfo Exception { get; } } #region Clear diff --git a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs b/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs index 5f5a599135..4a43dd154f 100644 --- a/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs +++ b/src/Umbraco.Core/Cache/HttpRequestCacheProvider.cs @@ -136,8 +136,7 @@ namespace Umbraco.Core.Cache //return result.Value; var value = result.Value; // will not throw (safe lazy) - var eh = value as ExceptionHolder; - if (eh != null) throw eh.Exception; // throw once! + if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! return value; } diff --git a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs index 6368eef78c..ad46201c0c 100644 --- a/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/HttpRuntimeCacheProvider.cs @@ -153,8 +153,7 @@ namespace Umbraco.Core.Cache //return result.Value; value = result.Value; // will not throw (safe lazy) - var eh = value as ExceptionHolder; - if (eh != null) throw new Exception("Exception while creating a value.", eh.Exception); // throw once! + if (value is ExceptionHolder eh) eh.Exception.Throw(); // throw once! return value; } diff --git a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs b/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs index 76a3d1c558..70e37addb8 100644 --- a/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs +++ b/src/Umbraco.Core/Cache/ObjectCacheRuntimeCacheProvider.cs @@ -225,8 +225,7 @@ namespace Umbraco.Core.Cache //return result.Value; var value = result.Value; // will not throw (safe lazy) - var eh = value as DictionaryCacheProviderBase.ExceptionHolder; - if (eh != null) throw eh.Exception; // throw once! + if (value is DictionaryCacheProviderBase.ExceptionHolder eh) eh.Exception.Throw(); // throw once! return value; } diff --git a/src/Umbraco.Core/Composing/LightInjectExtensions.cs b/src/Umbraco.Core/Composing/LightInjectExtensions.cs index 952dcd5f48..74a2c331e9 100644 --- a/src/Umbraco.Core/Composing/LightInjectExtensions.cs +++ b/src/Umbraco.Core/Composing/LightInjectExtensions.cs @@ -307,6 +307,10 @@ namespace Umbraco.Core.Composing if (factory == null) throw new ArgumentNullException(nameof(factory)); + // fixme temp - STOP doing this, it confuses LightInject and then we get ugly exception traces + // we HAVE to let LightInject throw - and catch at THE OUTERMOST if InvalidOperationException in LightInject.Anything! + + return factory.GetInstance(tService, serviceName, args); try { return factory.GetInstance(tService, serviceName, args); diff --git a/src/Umbraco.Core/Constants-Conventions.cs b/src/Umbraco.Core/Constants-Conventions.cs index 1cc9b40454..8ca4daddb3 100644 --- a/src/Umbraco.Core/Constants-Conventions.cs +++ b/src/Umbraco.Core/Constants-Conventions.cs @@ -274,14 +274,14 @@ namespace Umbraco.Core }, { PasswordAnswer, - new PropertyType(PropertyEditors.Aliases.NoEdit, ValueStorageType.NVarChar, true, PasswordAnswer) + new PropertyType(PropertyEditors.Aliases.NoEdit, ValueStorageType.Nvarchar, true, PasswordAnswer) { Name = PasswordAnswerLabel } }, { PasswordQuestion, - new PropertyType(PropertyEditors.Aliases.NoEdit, ValueStorageType.NVarChar, true, PasswordQuestion) + new PropertyType(PropertyEditors.Aliases.NoEdit, ValueStorageType.Nvarchar, true, PasswordQuestion) { Name = PasswordQuestionLabel } diff --git a/src/Umbraco.Core/Deploy/IPreValueConnector.cs b/src/Umbraco.Core/Deploy/IPreValueConnector.cs index 3f97b324fc..15f9a9e619 100644 --- a/src/Umbraco.Core/Deploy/IPreValueConnector.cs +++ b/src/Umbraco.Core/Deploy/IPreValueConnector.cs @@ -7,7 +7,7 @@ namespace Umbraco.Core.Deploy /// /// PreValues may contain values such as content identifiers, that would be local /// to one environment, and need to be converted in order to be deployed. - public interface IPreValueConnector + public interface IPreValueConnector // fixme this needs to change really { /// /// Gets the property editor aliases that the value converter supports by default. diff --git a/src/Umbraco.Core/Enum.cs b/src/Umbraco.Core/Enum.cs index d7a9e60818..5bc70c637d 100644 --- a/src/Umbraco.Core/Enum.cs +++ b/src/Umbraco.Core/Enum.cs @@ -1,105 +1,106 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Umbraco.Core { /// - /// A very useful class for parsing, enumerating and querying Enum objects + /// Provides utility methods for handling enumerations. /// - /// /// /// Taken from http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5 /// - public static class Enum where T : struct + public static class Enum + where T : struct { - private static readonly IEnumerable All = Enum.GetValues(typeof(T)).Cast(); - private static readonly Dictionary InsensitiveNames = All.ToDictionary(k => Enum.GetName(typeof(T), k).ToLowerInvariant()); - private static readonly Dictionary SensitiveNames = All.ToDictionary(k => Enum.GetName(typeof(T), k)); - private static readonly Dictionary Values = All.ToDictionary(k => Convert.ToInt32(k)); - private static readonly Dictionary Names = All.ToDictionary(k => k, v => v.ToString()); + private static readonly List Values; + private static readonly Dictionary InsensitiveNameToValue; + private static readonly Dictionary SensitiveNameToValue; + private static readonly Dictionary IntToValue; + private static readonly Dictionary ValueToName; + + static Enum() + { + Values = Enum.GetValues(typeof(T)).Cast().ToList(); + + IntToValue = new Dictionary(); + ValueToName = new Dictionary(); + SensitiveNameToValue = new Dictionary(); + InsensitiveNameToValue = new Dictionary(); + + foreach (var value in Values) + { + var name = value.ToString(); + + IntToValue[Convert.ToInt32(value)] = value; + ValueToName[value] = name; + SensitiveNameToValue[name] = value; + InsensitiveNameToValue[name.ToLowerInvariant()] = value; + } + } public static bool IsDefined(T value) { - return Names.Keys.Contains(value); + return ValueToName.Keys.Contains(value); } public static bool IsDefined(string value) { - return SensitiveNames.Keys.Contains(value); + return SensitiveNameToValue.Keys.Contains(value); } public static bool IsDefined(int value) { - return Values.Keys.Contains(value); + return IntToValue.Keys.Contains(value); } public static IEnumerable GetValues() { - return All; + return Values; } public static string[] GetNames() { - return Names.Values.ToArray(); + return ValueToName.Values.ToArray(); } public static string GetName(T value) { - string name; - Names.TryGetValue(value, out name); - return name; + return ValueToName.TryGetValue(value, out var name) ? name : null; } - public static T Parse(string value) + public static T Parse(string value, bool ignoreCase = false) { - T parsed = default(T); - if (!SensitiveNames.TryGetValue(value, out parsed)) - throw new ArgumentException("Value is not one of the named constants defined for the enumeration", "value"); - return parsed; + var names = ignoreCase ? InsensitiveNameToValue : SensitiveNameToValue; + if (ignoreCase) value = value.ToLowerInvariant(); + + if (names.TryGetValue(value, out var parsed)) + return parsed; + + throw new ArgumentException($"Value \"{value}\"is not a valid {typeof(T).Name} enumeration value.", nameof(value)); } - public static T Parse(string value, bool ignoreCase) + public static bool TryParse(string value, out T returnValue, bool ignoreCase = false) { - if (!ignoreCase) - return Parse(value); - - T parsed = default(T); - if (!InsensitiveNames.TryGetValue(value.ToLowerInvariant(), out parsed)) - throw new ArgumentException("Value is not one of the named constants defined for the enumeration", "value"); - return parsed; - } - - public static bool TryParse(string value, out T returnValue) - { - return SensitiveNames.TryGetValue(value, out returnValue); - } - - public static bool TryParse(string value, bool ignoreCase, out T returnValue) - { - if (!ignoreCase) - return TryParse(value, out returnValue); - - return InsensitiveNames.TryGetValue(value.ToLowerInvariant(), out returnValue); + var names = ignoreCase ? InsensitiveNameToValue : SensitiveNameToValue; + if (ignoreCase) value = value.ToLowerInvariant(); + return names.TryGetValue(value, out returnValue); } public static T? ParseOrNull(string value) { - if (String.IsNullOrEmpty(value)) + if (string.IsNullOrWhiteSpace(value)) return null; - T foundValue; - if (InsensitiveNames.TryGetValue(value.ToLowerInvariant(), out foundValue)) - return foundValue; + if (InsensitiveNameToValue.TryGetValue(value.ToLowerInvariant(), out var parsed)) + return parsed; return null; } public static T? CastOrNull(int value) { - T foundValue; - if (Values.TryGetValue(value, out foundValue)) + if (IntToValue.TryGetValue(value, out var foundValue)) return foundValue; return null; diff --git a/src/Umbraco.Core/Manifest/ManifestParser.cs b/src/Umbraco.Core/Manifest/ManifestParser.cs index 5b7cd67914..2fd3a5f6ad 100644 --- a/src/Umbraco.Core/Manifest/ManifestParser.cs +++ b/src/Umbraco.Core/Manifest/ManifestParser.cs @@ -17,32 +17,39 @@ namespace Umbraco.Core.Manifest /// public class ManifestParser { + private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); + private readonly IRuntimeCacheProvider _cache; - private readonly string _path; private readonly ILogger _logger; private readonly ManifestValidatorCollection _validators; - private static readonly string Utf8Preamble = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); + private string _path; /// /// Initializes a new instance of the class. /// - public ManifestParser(IRuntimeCacheProvider cache, ManifestValidatorCollection validators, ILogger logger) // fixme is LightInject going to pick that one? + public ManifestParser(IRuntimeCacheProvider cache, ManifestValidatorCollection validators, ILogger logger) : this(cache, validators, "~/App_Plugins", logger) { } /// /// Initializes a new instance of the class. /// - public ManifestParser(IRuntimeCacheProvider cache, ManifestValidatorCollection validators, string path, ILogger logger) + private ManifestParser(IRuntimeCacheProvider cache, ManifestValidatorCollection validators, string path, ILogger logger) { _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _validators = validators ?? throw new ArgumentNullException(nameof(validators)); if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullOrEmptyException(nameof(path)); - _path = path.StartsWith("~/") ? IOHelper.MapPath(path) : path; + Path = path; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } + public string Path + { + get => _path; + set => _path = value.StartsWith("~/") ? IOHelper.MapPath(value) : value; + } + /// /// Gets all manifests, merged into a single manifest object. /// diff --git a/src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs b/src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs index 52c1c9d06e..659f3818ce 100644 --- a/src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs +++ b/src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs @@ -38,7 +38,7 @@ namespace Umbraco.Core.Migrations.Install {5, typeof (DocumentDto)}, {6, typeof (ContentTypeTemplateDto)}, {7, typeof (DataTypeDto)}, - {8, typeof (DataTypePreValueDto)}, + //removed: {8, typeof (DataTypePreValueDto)}, {9, typeof (DictionaryDto)}, {10, typeof (LanguageDto)}, diff --git a/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs b/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs index 9e0ca99b5c..821e6da5a4 100644 --- a/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs +++ b/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs @@ -13,8 +13,13 @@ namespace Umbraco.Core.Migrations protected void AddColumn(string tableName, string columnName) { - AddColumn(tableName, columnName, out var sqls); - foreach (var sql in sqls) Database.Execute(sql); + //if (ColumnExists(tableName, columnName)) + // throw new InvalidOperationException($"Column {tableName}.{columnName} already exists."); + + var table = DefinitionFactory.GetTableDefinition(typeof(T), SqlSyntax); + var column = table.Columns.First(x => x.Name == columnName); + var createSql = SqlSyntax.Format(column); + Database.Execute(string.Format(SqlSyntax.AddColumn, SqlSyntax.GetQuotedTableName(tableName), createSql)); } protected void AddColumn(string tableName, string columnName, out IEnumerable sqls) diff --git a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs index 8fdd00a203..d20ced57cd 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs @@ -83,7 +83,7 @@ namespace Umbraco.Core.Migrations.Upgrade .Chain("{CBFF58A2-7B50-4F75-8E98-249920DB0F37}") .Chain("{3D18920C-E84D-405C-A06A-B7CEE52FE5DD}") .Chain("{FB0A5429-587E-4BD0-8A67-20F0E7E62FF7}") - .Chain("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}") + .Chain("{F0C42457-6A3B-4912-A7EA-F27ED85A2092}") .Chain("{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}"); // 7.8.1 = same as 7.8.0 diff --git a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs index aaa4929ec6..b93b68b27d 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using NPoco; +using Umbraco.Core.Migrations.Install; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; @@ -19,22 +20,27 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0 public override void Migrate() { - // drop all keys and indexes - Delete.KeysAndIndexes("cmsDataType").Do(); + // delete *all* keys and indexes - because of FKs + Delete.KeysAndIndexes().Do(); // drop and create columns Delete.Column("pk").FromTable("cmsDataType").Do(); - AddColumn("cmsDataType", "config"); // rename the table - Rename.Table("cmsDataType").To(Constants.DatabaseSchema.Tables.Document).Do(); + Rename.Table("cmsDataType").To(Constants.DatabaseSchema.Tables.DataType).Do(); - // recreate all keys and indexes - Create.KeysAndIndexes().Do(); + // create column + // fixme it is annoying that these are NOT written out to the log?! + AddColumn(Constants.DatabaseSchema.Tables.DataType, "config"); + Database.Execute(Sql().Update(u => u.Set(x => x.Configuration, string.Empty))); + + // re-create *all* keys and indexes + foreach (var x in DatabaseSchemaCreator.OrderedTables) + Create.KeysAndIndexes(x.Value).Do(); var sql = Sql() .Select() - .AndSelect() + .AndSelect(x => x.Alias, x => x.SortOrder, x => x.Value) .From() .InnerJoin().On((left, right) => left.NodeId == right.NodeId) .OrderBy(x => x.NodeId) @@ -71,7 +77,8 @@ namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0 } // drop preValues table - Delete.Table("cmsDataTypePreValues"); + // FIXME keep it around for now + //Delete.Table("cmsDataTypePreValues"); } [TableName("cmsDataTypePreValues")] diff --git a/src/Umbraco.Core/Models/ContentTypeBaseExtensions.cs b/src/Umbraco.Core/Models/ContentTypeBaseExtensions.cs index 6a71ff0979..ef55f0d469 100644 --- a/src/Umbraco.Core/Models/ContentTypeBaseExtensions.cs +++ b/src/Umbraco.Core/Models/ContentTypeBaseExtensions.cs @@ -11,9 +11,9 @@ namespace Umbraco.Core.Models { var type = contentType.GetType(); var itemType = PublishedItemType.Unknown; - if (type == typeof(IContentType)) itemType = PublishedItemType.Content; - else if (type == typeof(IMediaType)) itemType = PublishedItemType.Media; - else if (type == typeof(IMemberType)) itemType = PublishedItemType.Member; + if (typeof(IContentType).IsAssignableFrom(type)) itemType = PublishedItemType.Content; + else if (typeof(IMediaType).IsAssignableFrom(type)) itemType = PublishedItemType.Media; + else if (typeof(IMemberType).IsAssignableFrom(type)) itemType = PublishedItemType.Member; return itemType; } } diff --git a/src/Umbraco.Core/Models/PreValue.cs b/src/Umbraco.Core/Models/PreValue.cs deleted file mode 100644 index 05572ee4d7..0000000000 --- a/src/Umbraco.Core/Models/PreValue.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace Umbraco.Core.Models -{ - /// - /// Represents a stored pre-value field value - /// - public class PreValue : IDeepCloneable - { - public PreValue(int id, string value, int sortOrder) - { - Id = id; - Value = value; - SortOrder = sortOrder; - } - - public PreValue(int id, string value) - { - Id = id; - Value = value; - } - - public PreValue(string value) - { - Value = value; - } - - /// - /// The value stored for the pre-value field - /// - public string Value { get; set; } - - /// - /// The database id for the pre-value field value - /// - public int Id { get; private set; } - - /// - /// The sort order stored for the pre-value field value - /// - public int SortOrder { get; private set; } - - public virtual object DeepClone() - { - //Memberwise clone on PreValue will work since it doesn't have any deep elements - var clone = (PreValue)MemberwiseClone(); - return clone; - } - } -} diff --git a/src/Umbraco.Core/Models/PreValueCollection.cs b/src/Umbraco.Core/Models/PreValueCollection.cs deleted file mode 100644 index f505892dca..0000000000 --- a/src/Umbraco.Core/Models/PreValueCollection.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Umbraco.Core.Models -{ - /// - /// Represents the preValues for a data type. - /// - /// - /// Due to the legacy nature of the data that can be stored for pre-values, we have this class which encapsulates the 2 different - /// ways that pre-values are stored: A string array or a Dictionary. - /// - /// Most legacy property editors won't support the dictionary format but new property editors should always use the dictionary format. - /// In order to get overrideable pre-values working we need a dictionary since we'll have to reference a pre-value by a key. - /// - public class PreValueCollection : IDeepCloneable - { - private IDictionary _preValuesAsDictionary; - private PreValue[] _preValuesAsArray; - - /// - /// Gets the collection as an array. - /// - public IEnumerable PreValuesAsArray - { - get => _preValuesAsArray - ?? throw new InvalidOperationException("The current preValue collection is dictionary based, use the PreValuesAsDictionary property instead."); - set => _preValuesAsArray = value.ToArray(); - } - - /// - /// Gets the collection as a dictionary. - /// - public IDictionary PreValuesAsDictionary - { - get => _preValuesAsDictionary - ?? throw new InvalidOperationException("The current preValue collection is array based, use the PreValuesAsArray property instead."); - set => _preValuesAsDictionary = value; - } - - /// - /// Gets a value indicating whether the collection is dictionary-based. - /// - public bool IsDictionaryBased => _preValuesAsDictionary != null; - - /// - /// Initializes a new array-based instance of the class. - /// - public PreValueCollection(IEnumerable preVals) - { - _preValuesAsArray = preVals.ToArray(); - } - - /// - /// Initializes a new dictionary-based instance of the class. - /// - public PreValueCollection(IDictionary preVals) - { - _preValuesAsDictionary = preVals; - } - - /// - /// Gets the collection as a dictionary, even if it is array-based. - /// - public IDictionary FormatAsDictionary() - { - if (IsDictionaryBased) - return PreValuesAsDictionary; - - var dictionary = new Dictionary(); - for (var i = 0; i < _preValuesAsArray.Length; i++) - dictionary[i.ToInvariantString()] = _preValuesAsArray[i]; - return dictionary; - } - - public object DeepClone() - { - var clone = (PreValueCollection) MemberwiseClone(); - - if (_preValuesAsArray != null) - clone._preValuesAsArray = _preValuesAsArray.Select(x => (PreValue) x.DeepClone()).ToArray(); - - if (_preValuesAsDictionary != null) - clone._preValuesAsDictionary = _preValuesAsDictionary.ToDictionary(x => x.Key, x => (PreValue) x.Value.DeepClone()); - - return clone; - } - } -} diff --git a/src/Umbraco.Core/Models/Property.cs b/src/Umbraco.Core/Models/Property.cs index 2f07167af2..54ac950bfc 100644 --- a/src/Umbraco.Core/Models/Property.cs +++ b/src/Umbraco.Core/Models/Property.cs @@ -353,7 +353,7 @@ namespace Umbraco.Core.Models switch (PropertyType.ValueStorageType) { - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: case ValueStorageType.Ntext: return s; diff --git a/src/Umbraco.Core/Models/PropertyType.cs b/src/Umbraco.Core/Models/PropertyType.cs index b6537e25ba..900bad834e 100644 --- a/src/Umbraco.Core/Models/PropertyType.cs +++ b/src/Umbraco.Core/Models/PropertyType.cs @@ -322,7 +322,7 @@ namespace Umbraco.Core.Models return valueType == typeof(decimal); case ValueStorageType.Date: return valueType == typeof(DateTime); - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: return valueType == typeof(string); case ValueStorageType.Ntext: return valueType == typeof(string); diff --git a/src/Umbraco.Core/Models/ValueStorageType.cs b/src/Umbraco.Core/Models/ValueStorageType.cs index 77b1f7108e..abbae60dc7 100644 --- a/src/Umbraco.Core/Models/ValueStorageType.cs +++ b/src/Umbraco.Core/Models/ValueStorageType.cs @@ -10,6 +10,10 @@ namespace Umbraco.Core.Models [DataContract] public enum ValueStorageType { + // note: these values are written out in the database in some places, + // and then parsed back in a case-sensitive way - think about it before + // changing the casing of values. + /// /// Store property value as NText. /// @@ -20,7 +24,7 @@ namespace Umbraco.Core.Models /// Store property value as NVarChar. /// [EnumMember] - NVarChar, + Nvarchar, /// /// Store property value as Integer. diff --git a/src/Umbraco.Core/ObjectExtensions.cs b/src/Umbraco.Core/ObjectExtensions.cs index e6ae1092f1..c814461f36 100644 --- a/src/Umbraco.Core/ObjectExtensions.cs +++ b/src/Umbraco.Core/ObjectExtensions.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Xml; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; using Umbraco.Core.Composing; namespace Umbraco.Core @@ -501,26 +503,37 @@ namespace Umbraco.Core return new Dictionary(); } - private static readonly ConcurrentDictionary>> ToObjectTypes - = new ConcurrentDictionary>>(); + private static readonly ConcurrentDictionary> ToObjectTypes + = new ConcurrentDictionary>(); /// /// Converts an object's properties into a dictionary. /// /// The object to convert. /// A dictionary containing each properties. - public static Dictionary ToObjectDictionary(object obj) + public static Dictionary ToObjectDictionary(T obj) { + // fixme refactor this! + var d = new Dictionary(); + if (obj == null) return d; + foreach (var p in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) + { + var jsonProperty = p.GetCustomAttribute(); + var name = jsonProperty != null ? jsonProperty.PropertyName : p.Name; + d[name] = p.GetValue(obj); + } + return d; + var t = obj.GetType(); if (!ToObjectTypes.TryGetValue(t, out var properties)) { ToObjectTypes[t] = properties = t .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy) - .ToDictionary(x => x.Name, ReflectionUtilities.EmitPropertyGetter); + .ToDictionary(x => x.Name, x => (object) ReflectionUtilities.EmitPropertyGetter(x)); } - return properties.ToDictionary(x => x.Key, x => x.Value(obj)); + return properties.ToDictionary(x => x.Key, x => ((Func) x.Value)(obj)); } internal static string ToDebugString(this object obj, int levels = 0) diff --git a/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs b/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs index be86f2fbf8..ceeaea38b7 100644 --- a/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs @@ -21,7 +21,9 @@ namespace Umbraco.Core.Persistence.Dtos public string DbType { get; set; }//NOTE Is set to [varchar] (50) in Sql Server script [Column("config")] - public string Configuration { get; set; } // fixme - length? + [SpecialDbType(SpecialDbTypes.NTEXT)] + [Constraint(Default = "")] + public string Configuration { get; set; } [ResultColumn] [Reference(ReferenceType.OneToOne, ColumnName = "DataTypeId")] diff --git a/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs b/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs deleted file mode 100644 index d01073ccc8..0000000000 --- a/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs +++ /dev/null @@ -1,50 +0,0 @@ -using NPoco; -using Umbraco.Core.Persistence.DatabaseAnnotations; - -namespace Umbraco.Core.Persistence.Dtos -{ - [TableName("cmsDataTypePreValues")] - [PrimaryKey("id")] - [ExplicitColumns] - internal class DataTypePreValueDto - { - [Column("id")] - [PrimaryKeyColumn(IdentitySeed = 10)] - public int Id { get; set; } - - [Column("datatypeNodeId")] - [ForeignKey(typeof(DataTypeDto), Column = "nodeId")] - public int DataTypeNodeId { get; set; } - - [Column("value")] - [NullSetting(NullSetting = NullSettings.Null)] - [SpecialDbType(SpecialDbTypes.NTEXT)] - public string Value { get; set; } - - [Column("sortorder")] - public int SortOrder { get; set; } - - [Column("alias")] - [NullSetting(NullSetting = NullSettings.Null)] - [Length(50)] - public string Alias { get; set; } - - protected bool Equals(DataTypePreValueDto other) - { - return Id == other.Id; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((DataTypePreValueDto) obj); - } - - public override int GetHashCode() - { - return Id; - } - } -} diff --git a/src/Umbraco.Core/Persistence/Dtos/PropertyTypeReadOnlyDto.cs b/src/Umbraco.Core/Persistence/Dtos/PropertyTypeReadOnlyDto.cs index 3cb3040083..88c02862e2 100644 --- a/src/Umbraco.Core/Persistence/Dtos/PropertyTypeReadOnlyDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/PropertyTypeReadOnlyDto.cs @@ -45,7 +45,7 @@ namespace Umbraco.Core.Persistence.Dtos [Column("viewOnProfile")] public bool ViewOnProfile { get; set; } - /* cmsDataType */ + /* DataType */ [Column("propertyEditorAlias")] public string PropertyEditorAlias { get; set; } diff --git a/src/Umbraco.Core/Persistence/Factories/PropertyFactory.cs b/src/Umbraco.Core/Persistence/Factories/PropertyFactory.cs index 2902d94113..4e2789bab7 100644 --- a/src/Umbraco.Core/Persistence/Factories/PropertyFactory.cs +++ b/src/Umbraco.Core/Persistence/Factories/PropertyFactory.cs @@ -80,7 +80,7 @@ namespace Umbraco.Core.Persistence.Factories { dto.TextValue = value.ToString(); } - else if (property.ValueStorageType == ValueStorageType.NVarChar && value != null) + else if (property.ValueStorageType == ValueStorageType.Nvarchar && value != null) { dto.VarcharValue = value.ToString(); } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs index e46327ec4c..691bd77f56 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs @@ -409,15 +409,15 @@ namespace Umbraco.Core.Persistence.Repositories.Implement foreach (var a in allPropertyDataDtos) a.PropertyTypeDto = indexedPropertyTypeDtos[a.PropertyTypeId]; - // lazy access to prevalue for data types if any property requires tag support - var pre = new Lazy>(() => - { - return Database.FetchByGroups(allPropertyTypeIds, 2000, batch => - SqlContext.Sql() - .Select() - .From() - .WhereIn(x => x.DataTypeNodeId, batch)); - }); + //// lazy access to prevalue for data types if any property requires tag support + //var pre = new Lazy>(() => + //{ + // return Database.FetchByGroups(allPropertyTypeIds, 2000, batch => + // SqlContext.Sql() + // .Select() + // .From() + // .WhereIn(x => x.DataTypeNodeId, batch)); + //}); // now we have // - the definitinos @@ -425,10 +425,10 @@ namespace Umbraco.Core.Persistence.Repositories.Implement // - a lazy access to prevalues // and we need to build the proper property collections - return GetPropertyCollections(temps, allPropertyDataDtos, pre); + return GetPropertyCollections(temps, allPropertyDataDtos /*, pre*/); } - private IDictionary GetPropertyCollections(List> temps, IEnumerable allPropertyDataDtos, Lazy> allPreValues) + private IDictionary GetPropertyCollections(List> temps, IEnumerable allPropertyDataDtos /*, Lazy> allPreValues*/) where T : class, IContentBase { var result = new Dictionary(); @@ -474,18 +474,21 @@ namespace Umbraco.Core.Persistence.Repositories.Implement propertiesWithTagSupport[property.PropertyType.PropertyEditorAlias] = tagSupport = TagExtractor.GetAttribute(editor); if (tagSupport == null) continue; - //this property has tags, so we need to extract them and for that we need the prevals which we've already looked up - // fixme - optimize with index - var preValData = allPreValues.Value.Where(x => x.DataTypeNodeId == property.PropertyType.DataTypeId) - .Distinct() - .ToArray(); + // fixme - this is totally borked of course for just anything and we need to re-do it entirely without prevalue + //#error This cannot work! - // build and set tags - var asDictionary = preValData.ToDictionary(x => x.Alias, x => new PreValue(x.Id, x.Value, x.SortOrder)); - var preVals = new PreValueCollection(asDictionary); - // fixme this is totally borked of course for variants - var contentPropData = new ContentPropertyData(property.GetValue(), preVals); - TagExtractor.SetPropertyTags(property, contentPropData, property.GetValue(), tagSupport); + //// this property has tags, so we need to extract them and for that we need the prevals which we've already looked up + //// fixme - optimize with index + //var preValData = allPreValues.Value.Where(x => x.DataTypeNodeId == property.PropertyType.DataTypeId) + // .Distinct() + // .ToArray(); + + //// build and set tags + //var asDictionary = preValData.ToDictionary(x => x.Alias, x => new PreValue(x.Id, x.Value, x.SortOrder)); + //var preVals = new PreValueCollection(asDictionary); + //// fixme this is totally borked of course for variants + //var contentPropData = new ContentPropertyData(property.GetValue(), preVals); + //TagExtractor.SetPropertyTags(property, contentPropData, property.GetValue(), tagSupport); } if (result.ContainsKey(temp.VersionId)) diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index 8a795a80db..3ce03f759a 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -587,7 +587,7 @@ AND umbracoNode.id <> @id", { public class AssociatedTemplate { - public AssociatedTemplate(int templateId, string @alias, string templateName) + public AssociatedTemplate(int templateId, string alias, string templateName) { TemplateId = templateId; Alias = alias; @@ -1095,7 +1095,7 @@ ORDER BY contentTypeId, id"; pt.Name AS name, pt.sortOrder AS sortOrder, pt.validationRegExp AS regexp, pt.variations as variations, dt.nodeId as dataTypeId, dt.dbType as dbType, dt.propertyEditorAlias as editorAlias FROM cmsPropertyType pt -INNER JOIN cmsDataType as dt ON pt.dataTypeId = dt.nodeId +INNER JOIN uDataType as dt ON pt.dataTypeId = dt.nodeId WHERE pt.contentTypeId IN (@ids) ORDER BY contentTypeId, groupId, id"; diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs index 9b00729572..e6488cc566 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -24,9 +24,10 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class DataTypeRepository : NPocoRepositoryBase, IDataTypeRepository { - private readonly PropertyEditorCollection _editors; + private readonly Lazy _editors; - public DataTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, PropertyEditorCollection editors, ILogger logger) + // fixme temp fixing circular dependencies with LAZY but is this the right place? + public DataTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, Lazy editors, ILogger logger) : base(scopeAccessor, cache, logger) { _editors = editors; @@ -53,7 +54,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement } var dtos = Database.Fetch(dataTypeSql); - return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors[x.EditorAlias])).ToArray(); + return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors.Value[x.EditorAlias])).ToArray(); } protected override IEnumerable PerformGetByQuery(IQuery query) @@ -64,7 +65,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement var dtos = Database.Fetch(sql); - return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors[x.EditorAlias])).ToArray(); + return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors.Value[x.EditorAlias])).ToArray(); } #endregion @@ -112,10 +113,13 @@ namespace Umbraco.Core.Persistence.Repositories.Implement //TODO: should the below be removed? //Cannot add a duplicate data type - var exists = Database.ExecuteScalar(@"SELECT COUNT(*) FROM cmsDataType -INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id -WHERE umbracoNode." + SqlSyntax.GetQuotedColumnName("text") + "= @name", new { name = entity.Name }); - if (exists > 0) + var existsSql = Sql() + .SelectCount() + .From() + .InnerJoin().On((left, right) => left.NodeId == right.NodeId) + .Where(x => x.Text == entity.Name); + var exists = Database.ExecuteScalar(existsSql) > 0; + if (exists) { throw new DuplicateNameException("A data type with the name " + entity.Name + " already exists"); } @@ -158,12 +162,13 @@ WHERE umbracoNode." + SqlSyntax.GetQuotedColumnName("text") + "= @name", new { n entity.Name = EnsureUniqueNodeName(entity.Name, entity.Id); //Cannot change to a duplicate alias - var exists = Database.ExecuteScalar(@"SELECT COUNT(*) FROM cmsDataType -INNER JOIN umbracoNode ON cmsDataType.nodeId = umbracoNode.id -WHERE umbracoNode." + SqlSyntax.GetQuotedColumnName("text") + @"= @name -AND umbracoNode.id <> @id", - new { id = entity.Id, name = entity.Name }); - if (exists > 0) + var existsSql = Sql() + .SelectCount() + .From() + .InnerJoin().On((left, right) => left.NodeId == right.NodeId) + .Where(x => x.Text == entity.Name && x.NodeId != entity.Id); + var exists = Database.ExecuteScalar(existsSql) > 0; + if (exists) { throw new DuplicateNameException("A data type with the name " + entity.Name + " already exists"); } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs index 3c431567ee..6fef47679b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs @@ -148,7 +148,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement "cmsPropertyType.Name", "cmsPropertyType.Description", "cmsPropertyType.mandatory", "cmsPropertyType.UniqueID", "cmsPropertyType.validationRegExp", "cmsPropertyType.dataTypeId", "cmsPropertyType.sortOrder AS PropertyTypeSortOrder", "cmsPropertyType.propertyTypeGroupId AS PropertyTypesGroupId", "cmsMemberType.memberCanEdit", "cmsMemberType.viewOnProfile", - "cmsDataType.propertyEditorAlias", "cmsDataType.dbType", "cmsPropertyTypeGroup.id AS PropertyTypeGroupId", + "uDataType.propertyEditorAlias", "uDataType.dbType", "cmsPropertyTypeGroup.id AS PropertyTypeGroupId", "cmsPropertyTypeGroup.text AS PropertyGroupName", "cmsPropertyTypeGroup.uniqueID AS PropertyGroupUniqueID", "cmsPropertyTypeGroup.sortorder AS PropertyGroupSortOrder", "cmsPropertyTypeGroup.contenttypeNodeId") .From() diff --git a/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs b/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs index e3fd496775..339cbdaf06 100644 --- a/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/ConfigurationEditor.cs @@ -45,7 +45,7 @@ namespace Umbraco.Core.PropertyEditors /// Parses the configuration. /// /// Used to create the actual configuration dictionary from the database value. - public object ParseConfiguration(string configurationJson) + public virtual object ParseConfiguration(string configurationJson) => JsonConvert.DeserializeObject>(configurationJson); public static TConfiguration ConfigurationAs(object obj) @@ -83,8 +83,15 @@ namespace Umbraco.Core.PropertyEditors // configuration with their current configuration // make sure we have dictionaries + if (defaultConfiguration == null) + defaultConfiguration = new Dictionary(); + if (!(defaultConfiguration is IDictionary d)) throw new ArgumentException($"Expecting a {typeof(Dictionary).Name} instance but got {defaultConfiguration.GetType().Name}.", nameof(defaultConfiguration)); + + if (configuration == null) + configuration = new Dictionary(); + if (!(configuration is IDictionary c)) throw new ArgumentException($"Expecting a {typeof(Dictionary).Name} instance but got {configuration.GetType().Name}.", nameof(configuration)); diff --git a/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs b/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs index 8ff4944893..6a5bfd4040 100644 --- a/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs +++ b/src/Umbraco.Core/PropertyEditors/ConfigurationEditorOfTConfiguration.cs @@ -91,13 +91,17 @@ namespace Umbraco.Core.PropertyEditors return fields; } - /// - /// Parses the configuration. - /// - /// Used to create the actual configuration object from the database value. - public new virtual TConfiguration ParseConfiguration(string configuration) + /// + public override object ParseConfiguration(string configuration) { - return JsonConvert.DeserializeObject(configuration); + try + { + return JsonConvert.DeserializeObject(configuration); + } + catch (Exception e) + { + throw new Exception($"Failed to parse configuration \"{configuration}\" as \"{typeof(TConfiguration).Name}\" (see inner exception).", e); + } } /// @@ -119,7 +123,7 @@ namespace Umbraco.Core.PropertyEditors /// public sealed override Dictionary ToEditor(object defaultConfiguration, object configuration) { - return ToEditor((TConfiguration) defaultConfiguration, (TConfiguration) configuration); + return ToEditor((TConfiguration) configuration); } /// @@ -127,7 +131,7 @@ namespace Umbraco.Core.PropertyEditors /// /// The default configuration. /// The configuration. - public virtual Dictionary ToEditor(TConfiguration defaultConfiguration, TConfiguration configuration) + public virtual Dictionary ToEditor(TConfiguration configuration) { // fixme - how shall we merge? does defaultConfiguration makes any sense here? var dictionary = ObjectExtensions.ToObjectDictionary(configuration); @@ -149,8 +153,11 @@ namespace Umbraco.Core.PropertyEditors where T : new() { // fixme cache! see also ToObject in ObjectExtensions + // this is probably very bad, must REAFACTOR! the property setter of course cannot work like this! + //var properties = TypeHelper.CachedDiscoverableProperties(typeof(T)) + // .ToDictionary(x => x.Name, x => (Type: x.PropertyType, Set: ReflectionUtilities.EmitPropertySetter(x))); var properties = TypeHelper.CachedDiscoverableProperties(typeof(T)) - .ToDictionary(x => x.Name, x => (Type: x.PropertyType, Set: ReflectionUtilities.EmitPropertySetter(x))); + .ToDictionary(x => x.Name, x => (Type: x.PropertyType, Infos: x)); var obj = new T(); @@ -161,7 +168,8 @@ namespace Umbraco.Core.PropertyEditors // fixme if value is null? is this what we want? if (!value.GetType().IsInstanceOfType(property.Type)) throw new Exception(); - property.Set(obj, value); + //property.Set(obj, value); + property.Infos.SetValue(obj, value); } return obj; diff --git a/src/Umbraco.Core/PropertyEditors/IDataTypeConfiguration.cs b/src/Umbraco.Core/PropertyEditors/IDataTypeConfiguration.cs deleted file mode 100644 index 635d724d2b..0000000000 --- a/src/Umbraco.Core/PropertyEditors/IDataTypeConfiguration.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Umbraco.Core.PropertyEditors -{ - public interface IDataTypeConfiguration - { - IDictionary ToDictionary(); - } -} diff --git a/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs b/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs index 056ba13965..5a7b323cce 100644 --- a/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs @@ -17,9 +17,7 @@ namespace Umbraco.Core.PropertyEditors [DebuggerDisplay("{" + nameof(DebuggerDisplay) + "(),nq}")] public class PropertyEditor : IParameterEditor { - private ValueEditor _valueEditor; private ValueEditor _valueEditorAssigned; - private ConfigurationEditor _configurationEditor; private ConfigurationEditor _configurationEditorAssigned; /// @@ -95,12 +93,11 @@ namespace Umbraco.Core.PropertyEditors [JsonProperty("editor", Required = Required.Always)] public ValueEditor ValueEditor { - get => _valueEditor ?? (_valueEditor = CreateValueEditor()); - set - { - _valueEditorAssigned = value; - _valueEditor = null; - } + // create a new value editor each time - the property editor can be a + // singleton, but the value editor will get a configuration which depends + // on the datatype, so it cannot be a singleton really + get => CreateValueEditor(); + set => _valueEditorAssigned = value; } [JsonIgnore] @@ -109,19 +106,20 @@ namespace Umbraco.Core.PropertyEditors [JsonProperty("prevalues")] // change, breaks manifests public ConfigurationEditor ConfigurationEditor { - get => _configurationEditor ?? (_configurationEditor = CreateConfigurationEditor()); - set - { - _configurationEditorAssigned = value; - _configurationEditor = null; - } + // create a new configuration editor each time - the property editor can be a + // singleton, and technically the configuration editor could be a singleton + // too, but we'd rather not keep all configuration editor around in memory + get => CreateConfigurationEditor(); + set => _configurationEditorAssigned = value; } + // fixme explain what this is + // makes sense only for dictionary-based configurationeditor, true conf editors have classes? [JsonProperty("defaultConfig")] - public virtual IDictionary DefaultPreValues { get; set; } + public virtual IDictionary DefaultConfiguration { get; set; } [JsonIgnore] - IDictionary IParameterEditor.Configuration => DefaultPreValues; // fixme - because we must, but - bah + IDictionary IParameterEditor.Configuration => DefaultConfiguration; // fixme - because we must, but - bah /// /// Creates a value editor instance. @@ -174,13 +172,5 @@ namespace Umbraco.Core.PropertyEditors { return $"Name: {Name}, Alias: {Alias}, IsParameterEditor: {IsParameterEditor}"; } - - /// - /// Maps configuration to a strongly typed object. - /// - public virtual object DeserializeConfiguration(string json) // fixme - { - return JsonConvert.DeserializeObject>(json); - } } } diff --git a/src/Umbraco.Core/PropertyEditors/ValueEditor.cs b/src/Umbraco.Core/PropertyEditors/ValueEditor.cs index 3ae14fa0ee..0d8aa4c2d6 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueEditor.cs @@ -56,32 +56,45 @@ namespace Umbraco.Core.PropertyEditors HideLabel = attribute.HideLabel; } - private PreValueCollection _preVals; - protected PreValueCollection PreValues - { - get - { - if (_preVals == null) - { - throw new InvalidOperationException("Pre values cannot be accessed until the Configure method has been called"); - } - return _preVals; - } - } + // fixme kabam! + // I don't understand the remarks in the code commented out below + // and then, + // IPropertyEditor come from a PropertyEditorCollection so they are singletons + // IValueEditor is the actual value editor used for editing the value, + // and it has its own configuration, depending on the datatype, so it + // should NOT be a singleton => do NOT cache it in PropertyEditor! /// - /// This is called to configure the editor for display with it's prevalues, useful when properties need to change dynamically - /// depending on what is in the pre-values. + /// Gets or sets the value editor configuration. /// - /// - /// - /// This cannot be used to change the value being sent to the editor, ConfigureEditor will be called *after* ConvertDbToEditor, pre-values - /// should not be used to modify values. - /// - public virtual void ConfigureForDisplay(PreValueCollection preValues) - { - _preVals = preValues ?? throw new ArgumentNullException(nameof(preValues)); - } + public virtual object Configuration { get; set; } + + //private PreValueCollection _preVals; + //protected PreValueCollection PreValues + //{ + // get + // { + // if (_preVals == null) + // { + // throw new InvalidOperationException("Pre values cannot be accessed until the Configure method has been called"); + // } + // return _preVals; + // } + //} + + ///// + ///// This is called to configure the editor for display with it's prevalues, useful when properties need to change dynamically + ///// depending on what is in the pre-values. + ///// + ///// + ///// + ///// This cannot be used to change the value being sent to the editor, ConfigureEditor will be called *after* ConvertDbToEditor, pre-values + ///// should not be used to modify values. + ///// + //public virtual void ConfigureForDisplay(PreValueCollection preValues) + //{ + // _preVals = preValues ?? throw new ArgumentNullException(nameof(preValues)); + //} /// /// Gets or sets the editor view. @@ -166,7 +179,7 @@ namespace Umbraco.Core.PropertyEditors switch (GetDatabaseType()) { case ValueStorageType.Ntext: - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: valueType = typeof(string); break; case ValueStorageType.Integer: @@ -257,7 +270,7 @@ namespace Umbraco.Core.PropertyEditors switch (GetDatabaseType()) { case ValueStorageType.Ntext: - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: //if it is a string type, we will attempt to see if it is json stored data, if it is we'll try to convert //to a real json object so we can pass the true json object directly to angular! var asString = property.GetValue().ToString(); @@ -352,7 +365,7 @@ namespace Umbraco.Core.PropertyEditors case ValueStorageType.Integer: case ValueStorageType.Decimal: return new XText(ConvertDbToString(propertyType, value, dataTypeService)); - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: case ValueStorageType.Ntext: //put text in cdata return new XCData(ConvertDbToString(propertyType, value, dataTypeService)); @@ -371,7 +384,7 @@ namespace Umbraco.Core.PropertyEditors switch (GetDatabaseType()) { - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: case ValueStorageType.Ntext: return value.ToXmlString(); case ValueStorageType.Integer: diff --git a/src/Umbraco.Core/PropertyEditors/ValueTypes.cs b/src/Umbraco.Core/PropertyEditors/ValueTypes.cs index 9f2545c1dc..fea89943aa 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueTypes.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueTypes.cs @@ -87,7 +87,7 @@ namespace Umbraco.Core.PropertyEditors return ValueStorageType.Decimal; case String: - return ValueStorageType.NVarChar; + return ValueStorageType.Nvarchar; case Text: case Json: diff --git a/src/Umbraco.Core/ReflectionUtilities.cs b/src/Umbraco.Core/ReflectionUtilities.cs index 002ed257cf..d628896eac 100644 --- a/src/Umbraco.Core/ReflectionUtilities.cs +++ b/src/Umbraco.Core/ReflectionUtilities.cs @@ -367,14 +367,25 @@ namespace Umbraco.Core ThrowInvalidLambda(method.Name, returned, args); // all other generic args must match parameters - // except the last one, if it's a function, 'cos then its the returned type + // except the last one, if it's a function, 'cos then it's the returned type while (gx < genericArgs.Length - (isFunction ? 1 : 0)) if (genericArgs[gx++] != args[ax++]) ThrowInvalidLambda(method.Name, returned, args); // if it's a function then the last one must match the returned type - if (isFunction && genericArgs[gx] != returned) - ThrowInvalidLambda(method.Name, returned, args); + if (isFunction) + { + if (genericArgs[gx] != returned) + { + if (genericArgs[gx].IsAssignableFrom(returned)) + { + returned = genericArgs[gx]; // FIXME cast etc?! + } + else ThrowInvalidLambda(method.Name, returned, args); + } + } + //if (isFunction && !genericArgs[gx].IsAssignableFrom(returned)) + // ThrowInvalidLambda(method.Name, returned, args); // emit return EmitMethod(returned, args, method); diff --git a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs index 27ec23b468..9491614bf4 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntimeComponent.cs @@ -58,12 +58,6 @@ namespace Umbraco.Core.Runtime // register manifest parser, will be injected in collection builders where needed composition.Container.RegisterSingleton(); - composition.Container.RegisterCollectionBuilder() - .Add(factory => factory.GetInstance().GetPropertyEditors()); - - composition.Container.RegisterCollectionBuilder() - .Add(factory => factory.GetInstance().GetParameterEditors()); - // register our predefined validators composition.Container.RegisterCollectionBuilder() .Add() @@ -73,6 +67,12 @@ namespace Umbraco.Core.Runtime .Add() .Add(); + composition.Container.RegisterCollectionBuilder() + .Add(factory => factory.GetInstance().GetPropertyEditors()); + + composition.Container.RegisterCollectionBuilder() + .Add(factory => factory.GetInstance().GetParameterEditors()); + // 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 composition.Container.RegisterSingleton(f => diff --git a/src/Umbraco.Core/Services/Implement/PackagingService.cs b/src/Umbraco.Core/Services/Implement/PackagingService.cs index e570858934..634afeb5cf 100644 --- a/src/Umbraco.Core/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Core/Services/Implement/PackagingService.cs @@ -274,22 +274,23 @@ namespace Umbraco.Core.Services.Implement if (propertyType != null) { - if (propertyType.PropertyEditorAlias == Constants.PropertyEditors.Aliases.CheckBoxList) - { + // fixme - wtf is this very specific thing here?! + //if (propertyType.PropertyEditorAlias == Constants.PropertyEditors.Aliases.CheckBoxList) + //{ - //TODO: We need to refactor this so the packager isn't making direct db calls for an 'edge' case - var database = scope.Database; - var dtos = database.Fetch("WHERE datatypeNodeId = @Id", new { Id = propertyType.DataTypeId }); + // //TODO: We need to refactor this so the packager isn't making direct db calls for an 'edge' case + // var database = scope.Database; + // var dtos = database.Fetch("WHERE datatypeNodeId = @Id", new { Id = propertyType.DataTypeId }); - var propertyValueList = new List(); - foreach (var preValue in propertyValue.Split(',')) - { - propertyValueList.Add(dtos.Single(x => x.Value == preValue).Id.ToString(CultureInfo.InvariantCulture)); - } + // var propertyValueList = new List(); + // foreach (var preValue in propertyValue.Split(',')) + // { + // propertyValueList.Add(dtos.Single(x => x.Value == preValue).Id.ToString(CultureInfo.InvariantCulture)); + // } - propertyValue = string.Join(",", propertyValueList.ToArray()); + // propertyValue = string.Join(",", propertyValueList.ToArray()); - } + //} } //set property value content.SetValue(propertyTypeAlias, propertyValue); @@ -1016,7 +1017,7 @@ namespace Umbraco.Core.Services.Implement try { - dataType.Configuration = editor.DeserializeConfiguration(configurationAttribute.Value); + dataType.Configuration = editor.ConfigurationEditor.ParseConfiguration(configurationAttribute.Value); } catch (Exception ex) { diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 7fd733fab7..72a75c5503 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -334,7 +334,6 @@ - @@ -671,8 +670,6 @@ - - @@ -723,7 +720,6 @@ - diff --git a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs index b04e268e95..bd289dcdf7 100644 --- a/src/Umbraco.Tests/Manifest/ManifestParserTests.cs +++ b/src/Umbraco.Tests/Manifest/ManifestParserTests.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Manifest [SetUp] public void Setup() { - _parser = new ManifestParser(NullCacheProvider.Instance, Mock.Of()); + _parser = new ManifestParser(NullCacheProvider.Instance, new ManifestValidatorCollection(Enumerable.Empty()), Mock.Of()); } [Test] @@ -193,7 +193,7 @@ javascript: ['~/test.js',/*** some note about stuff asd09823-4**09234*/ '~/test2 Assert.AreEqual("\\d*", v.Config); // this is not part of the manifest - var preValues = editor.DefaultPreValues; + var preValues = editor.DefaultConfiguration; Assert.IsNull(preValues); var preValueEditor = editor.ConfigurationEditor; diff --git a/src/Umbraco.Tests/Models/Collections/PropertyCollectionTests.cs b/src/Umbraco.Tests/Models/Collections/PropertyCollectionTests.cs index a6ba9bb809..d12ddb9284 100644 --- a/src/Umbraco.Tests/Models/Collections/PropertyCollectionTests.cs +++ b/src/Umbraco.Tests/Models/Collections/PropertyCollectionTests.cs @@ -16,8 +16,8 @@ namespace Umbraco.Tests.Models.Collections { var collection = new PropertyCollection(); - collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.NVarChar, "test"))); - collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.NVarChar, "Test"))); + collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.Nvarchar, "test"))); + collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.Nvarchar, "Test"))); Assert.AreEqual(1, collection.Count); } @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Models.Collections { var collection = new PropertyCollection(); - collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.NVarChar, "test"))); + collection.Add(new Property(new PropertyType("propEditor", ValueStorageType.Nvarchar, "test"))); Assert.IsTrue(collection.Contains("Test")); } diff --git a/src/Umbraco.Tests/Models/ContentTypeTests.cs b/src/Umbraco.Tests/Models/ContentTypeTests.cs index 6d1a783eb9..c63853940f 100644 --- a/src/Umbraco.Tests/Models/ContentTypeTests.cs +++ b/src/Umbraco.Tests/Models/ContentTypeTests.cs @@ -243,7 +243,7 @@ namespace Umbraco.Tests.Models var asDirty = (ICanBeDirty)clone; Assert.IsFalse(asDirty.IsPropertyDirty("PropertyTypes")); - clone.AddPropertyType(new PropertyType("test", ValueStorageType.NVarChar, "blah")); + clone.AddPropertyType(new PropertyType("test", ValueStorageType.Nvarchar, "blah")); Assert.IsTrue(asDirty.IsPropertyDirty("PropertyTypes")); Assert.IsFalse(asDirty.IsPropertyDirty("PropertyGroups")); clone.AddPropertyGroup("hello"); diff --git a/src/Umbraco.Tests/Models/DataTypeTests.cs b/src/Umbraco.Tests/Models/DataTypeTests.cs index d01d095564..35b4476fd7 100644 --- a/src/Umbraco.Tests/Models/DataTypeTests.cs +++ b/src/Umbraco.Tests/Models/DataTypeTests.cs @@ -17,7 +17,7 @@ namespace Umbraco.Tests.Models { CreateDate = DateTime.Now, CreatorId = 5, - DatabaseType = ValueStorageType.NVarChar, + DatabaseType = ValueStorageType.Nvarchar, Id = 4, Key = Guid.NewGuid(), Level = 7, @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Models { CreateDate = DateTime.Now, CreatorId = 5, - DatabaseType = ValueStorageType.NVarChar, + DatabaseType = ValueStorageType.Nvarchar, Id = 4, Key = Guid.NewGuid(), Level = 7, diff --git a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs index 50940db1fd..d75cfd4324 100644 --- a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs @@ -23,8 +23,11 @@ namespace Umbraco.Tests.Models.Mapping var manifestBuilder = new ManifestParser( CacheHelper.CreateDisabledCacheHelper().RuntimeCache, - TestHelper.CurrentAssemblyDirectory, - Logger); + new ManifestValidatorCollection(Enumerable.Empty()), + Logger) + { + Path = TestHelper.CurrentAssemblyDirectory + }; Container.Register(_ => manifestBuilder); Func> typeListProducerList = Enumerable.Empty; diff --git a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs index 0612225207..149fe9f6ab 100644 --- a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs @@ -95,7 +95,7 @@ namespace Umbraco.Tests.Models.Mapping definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" - && definition.DatabaseType == ValueStorageType.NVarChar)); + && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMemberTypeSave(); @@ -154,7 +154,7 @@ namespace Umbraco.Tests.Models.Mapping definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" - && definition.DatabaseType == ValueStorageType.NVarChar)); + && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMediaTypeSave(); @@ -211,7 +211,7 @@ namespace Umbraco.Tests.Models.Mapping definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" - && definition.DatabaseType == ValueStorageType.NVarChar)); + && definition.DatabaseType == ValueStorageType.Nvarchar)); _fileService.Setup(x => x.GetTemplate(It.IsAny())) @@ -285,7 +285,7 @@ namespace Umbraco.Tests.Models.Mapping definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" - && definition.DatabaseType == ValueStorageType.NVarChar)); + && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionMediaTypeSave(); @@ -312,7 +312,7 @@ namespace Umbraco.Tests.Models.Mapping definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" - && definition.DatabaseType == ValueStorageType.NVarChar)); + && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionContentTypeSave(); @@ -334,11 +334,6 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now - // TODO: but we'll need to change this to return some pre-values to test the mappings - _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary())); - var memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.MemberTypePropertyTypes[memberType.PropertyTypes.Last().Alias] = new MemberTypePropertyProfileAccess(true, true); @@ -397,11 +392,6 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now - // TODO: but we'll need to change this to return some pre-values to test the mappings - _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary())); - var mediaType = MockedContentTypes.CreateImageMediaType(); MockedContentTypes.EnsureAllIds(mediaType, 8888); @@ -455,11 +445,6 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now - // TODO: but we'll need to change this to return some pre-values to test the mappings - _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary())); - var contentType = MockedContentTypes.CreateTextpageContentType(); MockedContentTypes.EnsureAllIds(contentType, 8888); @@ -723,11 +708,6 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now - // TODO: but we'll need to change this to return some pre-values to test the mappings - _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary())); - _entityService.Setup(x => x.GetObjectType(It.IsAny())) .Returns(UmbracoObjectTypes.DocumentType); @@ -819,11 +799,6 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - // for any call to GetPreValuesCollectionByDataTypeId just return an empty dictionary for now - // TODO: but we'll need to change this to return some pre-values to test the mappings - _dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary())); - _entityService.Setup(x => x.GetObjectType(It.IsAny())) .Returns(UmbracoObjectTypes.DocumentType); diff --git a/src/Umbraco.Tests/Models/MediaXmlTest.cs b/src/Umbraco.Tests/Models/MediaXmlTest.cs index d86b9f03ad..2f8154ef29 100644 --- a/src/Umbraco.Tests/Models/MediaXmlTest.cs +++ b/src/Umbraco.Tests/Models/MediaXmlTest.cs @@ -29,7 +29,7 @@ namespace Umbraco.Tests.Models // reference, so static ctor runs, so event handlers register // and then, this will reset the width, height... because the file does not exist, of course ;-( - var ignored = new FileUploadPropertyEditor(Mock.Of(), new MediaFileSystem(Mock.Of()), Mock.Of(), Mock.Of()); + var ignored = new FileUploadPropertyEditor(Mock.Of(), new MediaFileSystem(Mock.Of())); var media = MockedMedia.CreateMediaImage(mediaType, -1); ServiceContext.MediaService.Save(media, 0); diff --git a/src/Umbraco.Tests/Models/PreValueCollectionTests.cs b/src/Umbraco.Tests/Models/PreValueCollectionTests.cs deleted file mode 100644 index e6f35ea3d3..0000000000 --- a/src/Umbraco.Tests/Models/PreValueCollectionTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NUnit.Framework; -using Umbraco.Core.Models; - -namespace Umbraco.Tests.Models -{ - [TestFixture] - public class PreValueCollectionTests - { - [Test] - public void Can_Deep_Clone() - { - var d = new PreValueCollection(new Dictionary - { - {"blah1", new PreValue(1, "test1", 1)}, - {"blah2", new PreValue(2, "test1", 3)}, - {"blah3", new PreValue(3, "test1", 2)} - }); - - var a = new PreValueCollection(new[] - { - new PreValue(1, "test1", 1), - new PreValue(2, "test1", 3), - new PreValue(3, "test1", 2) - }); - - var clone1 = (PreValueCollection)d.DeepClone(); - var clone2 = (PreValueCollection)a.DeepClone(); - - Action assert = (orig, clone) => - { - Assert.AreNotSame(orig, clone); - var oDic = orig.FormatAsDictionary(); - var cDic = clone.FormatAsDictionary(); - Assert.AreEqual(oDic.Keys.Count, cDic.Keys.Count); - foreach (var k in oDic.Keys) - { - Assert.AreNotSame(oDic[k], cDic[k]); - Assert.AreEqual(oDic[k].Id, cDic[k].Id); - Assert.AreEqual(oDic[k].SortOrder, cDic[k].SortOrder); - Assert.AreEqual(oDic[k].Value, cDic[k].Value); - } - }; - - assert(d, clone1); - assert(a, clone2); - } - } -} diff --git a/src/Umbraco.Tests/Models/PropertyGroupTests.cs b/src/Umbraco.Tests/Models/PropertyGroupTests.cs index cded8cb985..0552acf930 100644 --- a/src/Umbraco.Tests/Models/PropertyGroupTests.cs +++ b/src/Umbraco.Tests/Models/PropertyGroupTests.cs @@ -16,7 +16,7 @@ namespace Umbraco.Tests.Models var pg = new PropertyGroup( new PropertyTypeCollection(false, new[] { - new PropertyType("TestPropertyEditor", ValueStorageType.NVarChar, "test") + new PropertyType("TestPropertyEditor", ValueStorageType.Nvarchar, "test") { Id = 3, CreateDate = DateTime.Now, @@ -30,9 +30,9 @@ namespace Umbraco.Tests.Models SortOrder = 9, UpdateDate = DateTime.Now, ValidationRegExp = "xxxx", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar }, - new PropertyType("TestPropertyEditor", ValueStorageType.NVarChar, "test2") + new PropertyType("TestPropertyEditor", ValueStorageType.Nvarchar, "test2") { Id = 4, CreateDate = DateTime.Now, @@ -46,7 +46,7 @@ namespace Umbraco.Tests.Models SortOrder = 10, UpdateDate = DateTime.Now, ValidationRegExp = "yyyy", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar } })) { @@ -93,7 +93,7 @@ namespace Umbraco.Tests.Models var pg = new PropertyGroup( new PropertyTypeCollection(false, new[] { - new PropertyType("TestPropertyEditor", ValueStorageType.NVarChar, "test") + new PropertyType("TestPropertyEditor", ValueStorageType.Nvarchar, "test") { Id = 3, CreateDate = DateTime.Now, @@ -107,9 +107,9 @@ namespace Umbraco.Tests.Models SortOrder = 9, UpdateDate = DateTime.Now, ValidationRegExp = "xxxx", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar }, - new PropertyType("TestPropertyEditor2", ValueStorageType.NVarChar, "test2") + new PropertyType("TestPropertyEditor2", ValueStorageType.Nvarchar, "test2") { Id = 4, CreateDate = DateTime.Now, @@ -123,7 +123,7 @@ namespace Umbraco.Tests.Models SortOrder = 10, UpdateDate = DateTime.Now, ValidationRegExp = "yyyy", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar } })) { diff --git a/src/Umbraco.Tests/Models/PropertyTypeTests.cs b/src/Umbraco.Tests/Models/PropertyTypeTests.cs index 9f8417c381..568d12264d 100644 --- a/src/Umbraco.Tests/Models/PropertyTypeTests.cs +++ b/src/Umbraco.Tests/Models/PropertyTypeTests.cs @@ -13,7 +13,7 @@ namespace Umbraco.Tests.Models [Test] public void Can_Deep_Clone() { - var pt = new PropertyType("TestPropertyEditor", ValueStorageType.NVarChar, "test") + var pt = new PropertyType("TestPropertyEditor", ValueStorageType.Nvarchar, "test") { Id = 3, CreateDate = DateTime.Now, @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Models SortOrder = 9, UpdateDate = DateTime.Now, ValidationRegExp = "xxxx", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar }; var clone = (PropertyType)pt.DeepClone(); @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Models { var ss = new SerializationService(new JsonNetSerializer()); - var pt = new PropertyType("TestPropertyEditor", ValueStorageType.NVarChar, "test") + var pt = new PropertyType("TestPropertyEditor", ValueStorageType.Nvarchar, "test") { Id = 3, CreateDate = DateTime.Now, @@ -76,7 +76,7 @@ namespace Umbraco.Tests.Models SortOrder = 9, UpdateDate = DateTime.Now, ValidationRegExp = "xxxx", - ValueStorageType = ValueStorageType.NVarChar + ValueStorageType = ValueStorageType.Nvarchar }; var result = ss.ToStream(pt); diff --git a/src/Umbraco.Tests/Models/VariationTests.cs b/src/Umbraco.Tests/Models/VariationTests.cs index 23238a5ab8..b797b0c4be 100644 --- a/src/Umbraco.Tests/Models/VariationTests.cs +++ b/src/Umbraco.Tests/Models/VariationTests.cs @@ -21,7 +21,7 @@ namespace Umbraco.Tests.Models [Test] public void PropertyTests() { - var propertyType = new PropertyType("editor", ValueStorageType.NVarChar) { Alias = "prop" }; + var propertyType = new PropertyType("editor", ValueStorageType.Nvarchar) { Alias = "prop" }; var prop = new Property(propertyType); // can set value @@ -115,7 +115,7 @@ namespace Umbraco.Tests.Models [Test] public void ContentTests() { - var propertyType = new PropertyType("editor", ValueStorageType.NVarChar) { Alias = "prop" }; + var propertyType = new PropertyType("editor", ValueStorageType.Nvarchar) { Alias = "prop" }; var contentType = new ContentType(-1) { Alias = "contentType" }; contentType.AddPropertyType(propertyType); @@ -219,7 +219,7 @@ namespace Umbraco.Tests.Models [Test] public void IsDirtyTests() { - var propertyType = new PropertyType("editor", ValueStorageType.NVarChar) { Alias = "prop" }; + var propertyType = new PropertyType("editor", ValueStorageType.Nvarchar) { Alias = "prop" }; var prop = new Property(propertyType); var contentType = new ContentType(-1) { Alias = "contentType" }; contentType.AddPropertyType(propertyType); @@ -244,7 +244,7 @@ namespace Umbraco.Tests.Models [Test] public void ValidationTests() { - var propertyType = new PropertyType("editor", ValueStorageType.NVarChar) { Alias = "prop", IsPublishing = true }; + var propertyType = new PropertyType("editor", ValueStorageType.Nvarchar) { Alias = "prop", IsPublishing = true }; var prop = new Property(propertyType); prop.SetValue("a"); diff --git a/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs b/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs index 8cc5218263..f6908e6e26 100644 --- a/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs +++ b/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs @@ -149,7 +149,7 @@ namespace Umbraco.Tests.Persistence.Querying scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF ", SqlSyntax.GetQuotedTableName("umbracoNode")))); scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", SqlSyntax.GetQuotedTableName(Constants.DatabaseSchema.Tables.DataType)))); - scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 44444, NodeId = 55555, EditorAlias = Constants.PropertyEditors.Aliases.Textbox, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 55555, EditorAlias = Constants.PropertyEditors.Aliases.Textbox, DbType = "Nvarchar" }); scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF ", SqlSyntax.GetQuotedTableName(Constants.DatabaseSchema.Tables.DataType)))); scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", SqlSyntax.GetQuotedTableName("cmsContentType")))); diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs index f9d4299834..1b028de6a0 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentRepositoryTest.cs @@ -15,6 +15,7 @@ using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Persistence.SqlSyntax; +using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Tests.Testing; @@ -46,7 +47,8 @@ namespace Umbraco.Tests.Persistence.Repositories TemplateRepository tr; var ctRepository = CreateRepository(scopeAccessor, out contentTypeRepository, out tr); - dtdRepository = new DataTypeRepository(scopeAccessor, cacheHelper, Logger); + var editors = new PropertyEditorCollection(Enumerable.Empty()); + dtdRepository = new DataTypeRepository(scopeAccessor, cacheHelper, new Lazy(() => editors), Logger); return ctRepository; } diff --git a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs index 7571f1a118..d8323a13ab 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/ContentTypeRepositoryTest.cs @@ -763,7 +763,7 @@ namespace Umbraco.Tests.Persistence.Repositories Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(4)); // Act - var urlAlias = new PropertyType("test", ValueStorageType.NVarChar, "urlAlias") + var urlAlias = new PropertyType("test", ValueStorageType.Nvarchar, "urlAlias") { Name = "Url Alias", Description = "", diff --git a/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs index 8b9d690011..7fcacd939c 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/DataTypeDefinitionRepositoryTest.cs @@ -438,123 +438,6 @@ namespace Umbraco.Tests.Persistence.Repositories } } - [Test] - public void Can_Get_Pre_Value_Collection() - { - var provider = TestObjects.GetScopeProvider(Logger); - var accessor = (IScopeAccessor) provider; - - using (var scope = provider.CreateScope()) - { - var repository = CreateRepository(); - var dataTypeDefinition = new DataType(-1, Constants.PropertyEditors.Aliases.RadioButtonList) { Name = "test" }; - repository.Save(dataTypeDefinition); - - var dtid = dataTypeDefinition.Id; - - scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtid, SortOrder = 0, Value = "test1"}); - scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtid, SortOrder = 1, Value = "test2" }); - - var collection = repository.GetPreValuesCollectionByDataTypeId(dtid); - Assert.AreEqual(2, collection.PreValuesAsArray.Count()); - } - } - - [Test] - public void Can_Get_Pre_Value_As_String() - { - var provider = TestObjects.GetScopeProvider(Logger); - var accessor = (IScopeAccessor) provider; - - using (var scope = provider.CreateScope()) - { - var repository = CreateRepository(); - var dataTypeDefinition = new DataType(-1, Constants.PropertyEditors.Aliases.RadioButtonList) { Name = "test" }; - repository.Save(dataTypeDefinition); - - var dtid = dataTypeDefinition.Id; - - var id = scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtid, SortOrder = 0, Value = "test1" }); - scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtid, SortOrder = 1, Value = "test2" }); - - var val = repository.GetPreValueAsString(Convert.ToInt32(id)); - Assert.AreEqual("test1", val); - } - } - - [Test] - public void Can_Get_Pre_Value_Collection_With_Cache() - { - DataType dtd; - - var provider = TestObjects.GetScopeProvider(Logger); - var accessor = (IScopeAccessor) provider; - - using (var scope = provider.CreateScope()) - { - var repository = Container.GetInstance(); - dtd = new DataType(-1, Constants.PropertyEditors.Aliases.RadioButtonList) { Name = "test" }; - repository.Save(dtd); - - scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtd.Id, SortOrder = 0, Value = "test1" }); - scope.Database.Insert(new DataTypePreValueDto { DataTypeNodeId = dtd.Id, SortOrder = 1, Value = "test2" }); - - //this will cache the result - var collection = repository.GetPreValuesCollectionByDataTypeId(dtd.Id); - } - - // note: see CreateCacheHelper, this test uses a special cache - var cache = CacheHelper.IsolatedRuntimeCache.GetCache(); - Assert.IsTrue(cache); - var cached = cache.Result - .GetCacheItemsByKeySearch(CacheKeys.DataTypePreValuesCacheKey + "_" + dtd.Id); - - Assert.IsNotNull(cached); - Assert.AreEqual(1, cached.Count()); - Assert.AreEqual(2, cached.Single().FormatAsDictionary().Count); - } - - [Test] - public void Can_Get_Pre_Value_As_String_With_Cache() - { - DataType dtd; - object id; - - var provider = TestObjects.GetScopeProvider(Logger); - var accessor = (IScopeAccessor) provider; - - using (var scope = provider.CreateScope()) - { - var repository = Container.GetInstance(); - dtd = new DataType(-1, Constants.PropertyEditors.Aliases.RadioButtonList) { Name = "test" }; - repository.Save(dtd); - - id = scope.Database.Insert(new DataTypePreValueDto() { DataTypeNodeId = dtd.Id, SortOrder = 0, Value = "test1" }); - scope.Database.Insert(new DataTypePreValueDto() { DataTypeNodeId = dtd.Id, SortOrder = 1, Value = "test2" }); - - //this will cache the result - var val = repository.GetPreValueAsString(Convert.ToInt32(id)); - } - - // note: see CreateCacheHelper, this test uses a special cache - var cache = CacheHelper.IsolatedRuntimeCache.GetCache(); - Assert.IsTrue(cache); - var cached = cache.Result - .GetCacheItemsByKeySearch(CacheKeys.DataTypePreValuesCacheKey + "_" + dtd.Id); - - Assert.IsNotNull(cached); - Assert.AreEqual(1, cached.Count()); - Assert.AreEqual(2, cached.Single().FormatAsDictionary().Count); - - using (var scope = provider.CreateScope()) - { - var repository = Container.GetInstance(); - //ensure it still gets resolved! - var val = repository.GetPreValueAsString(Convert.ToInt32(id)); - Assert.AreEqual("test1", val); - } - } - [TearDown] public override void TearDown() { diff --git a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs index dbc4d31e1a..9d2c574743 100644 --- a/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs +++ b/src/Umbraco.Tests/Persistence/SqlCeTableByTableTest.cs @@ -145,21 +145,6 @@ namespace Umbraco.Tests.Persistence } } - [Test] - public void Can_Create_cmsDataTypePreValues_Table() - { - using (var scope = ScopeProvider.CreateScope()) - { - var helper = new DatabaseSchemaCreator(scope.Database, Mock.Of()); - - helper.CreateTable(); - helper.CreateTable(); - helper.CreateTable(); - - scope.Complete(); - } - } - [Test] public void Can_Create_cmsDictionary_Table() { diff --git a/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs b/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs index 7ca7767b40..9dc6dc921f 100644 --- a/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs +++ b/src/Umbraco.Tests/PropertyEditors/ImageCropperTest.cs @@ -12,6 +12,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.PropertyEditors.ValueConverters; using Umbraco.Core.Services; using Umbraco.Web.Models; using Umbraco.Web; @@ -43,7 +44,7 @@ namespace Umbraco.Tests.PropertyEditors var sourceObj = CropperJson3.SerializeToCropDataSet(); var destObj = sourceObj.TryConvertTo(); Assert.IsTrue(destObj.Success); - Assert.AreEqual(sourceObj, destObj.Result.ToObject()); + Assert.AreEqual(sourceObj, destObj.Result.ToObject()); } [Test] @@ -53,7 +54,7 @@ namespace Umbraco.Tests.PropertyEditors var destObj = sourceObj.TryConvertTo(); Assert.IsTrue(destObj.Success); Assert.IsTrue(destObj.Result.DetectIsJson()); - var obj = JsonConvert.DeserializeObject(CropperJson1, new JsonSerializerSettings {Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal}); + var obj = JsonConvert.DeserializeObject(CropperJson1, new JsonSerializerSettings {Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal}); Assert.AreEqual(sourceObj, obj); } @@ -67,10 +68,7 @@ namespace Umbraco.Tests.PropertyEditors container.ConfigureUmbracoCore(); container.RegisterCollectionBuilder(); - var dataTypeService = new Mock(); - dataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())).Returns(new PreValueCollection(Enumerable.Empty())); - - var converter = new Umbraco.Web.PropertyEditors.ValueConverters.ImageCropperValueConverter(dataTypeService.Object); + var converter = new Core.PropertyEditors.ValueConverters.ImageCropperValueConverter(); var factory = new PublishedContentTypeFactory(Mock.Of(), new PropertyValueConverterCollection(Array.Empty()), Mock.Of()); var result = converter.ConvertSourceToIntermediate(null, factory.CreatePropertyType("test", 0, "test"), val1, false); // does not use type for conversion diff --git a/src/Umbraco.Tests/PropertyEditors/LegacyPropertyEditorIdToAliasConverterTests.cs b/src/Umbraco.Tests/PropertyEditors/LegacyPropertyEditorIdToAliasConverterTests.cs deleted file mode 100644 index e756438aa6..0000000000 --- a/src/Umbraco.Tests/PropertyEditors/LegacyPropertyEditorIdToAliasConverterTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using NUnit.Framework; -using Umbraco.Core.PropertyEditors; - -namespace Umbraco.Tests.PropertyEditors -{ - [TestFixture] - public class LegacyPropertyEditorIdToAliasConverterTests - { - [TearDown] - public void Reset() - { - LegacyPropertyEditorIdToAliasConverter.Reset(); - } - - [Test] - public void Doesnt_Create_Duplicates_Without_Exception() - { - var id = Guid.NewGuid(); - LegacyPropertyEditorIdToAliasConverter.CreateMap(id, "test"); - LegacyPropertyEditorIdToAliasConverter.CreateMap(id, "test"); - Assert.AreEqual(1, LegacyPropertyEditorIdToAliasConverter.Count()); - } - - [Test] - public void Can_Get_Legacy_Id_From_Alias() - { - var id = Guid.NewGuid(); - LegacyPropertyEditorIdToAliasConverter.CreateMap(id, "test"); - - Assert.AreEqual( - id, - LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias( - "test", - LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.ThrowException)); - } - - [Test] - public void Can_Get_Alias_From_Legacy_Id() - { - var id = Guid.NewGuid(); - LegacyPropertyEditorIdToAliasConverter.CreateMap(id, "test"); - - Assert.AreEqual( - "test", - LegacyPropertyEditorIdToAliasConverter.GetAliasFromLegacyId( - id, - true)); - } - - [Test] - public void Can_Generate_Id_From_Missing_Alias() - { - var gen1 = LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias("Donotfindthisone", LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.GenerateId); - var gen2 = LegacyPropertyEditorIdToAliasConverter.GetLegacyIdFromAlias("Donotfindthisone", LegacyPropertyEditorIdToAliasConverter.NotFoundLegacyIdResponseBehavior.GenerateId); - - Assert.IsNotNull(gen1); - Assert.IsNotNull(gen2); - Assert.AreEqual(gen1, gen2); - } - - [Test] - public void Creates_Map_For_Core_Editors() - { - LegacyPropertyEditorIdToAliasConverter.CreateMappingsForCoreEditors(); - - Assert.AreEqual(36, LegacyPropertyEditorIdToAliasConverter.Count()); - } - } -} diff --git a/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs b/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs index 67cd91b4d8..7dcfef3c89 100644 --- a/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs +++ b/src/Umbraco.Tests/PropertyEditors/MultiValuePropertyEditorTests.cs @@ -29,8 +29,7 @@ namespace Umbraco.Tests.PropertyEditors public void DropDownMultipleValueEditor_With_Keys_Format_Data_For_Cache() { var dataTypeServiceMock = new Mock(); - var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValuesMultipleValueEditor(true, dataTypeService, Mock.Of(), new ValueEditor()); + var editor = new PublishValuesMultipleValueEditor(true, Mock.Of(), new ValueEditorAttribute("key", "nam", "view")); var prop = new Property(1, new PropertyType(new DataType(1, "Test.TestEditor"))); prop.SetValue("1234,4567,8910"); @@ -43,24 +42,31 @@ namespace Umbraco.Tests.PropertyEditors [Test] public void DropDownMultipleValueEditor_No_Keys_Format_Data_For_Cache() { - var dataTypeServiceMock = new Mock(); + var dataType = new DataType("editorAlias") + { + Configuration = new ValueListConfiguration + { + Items = new List + { + new ValueListConfiguration.ValueListItem { Id = 4567, Value = "Value 1" }, + new ValueListConfiguration.ValueListItem { Id = 1234, Value = "Value 2" }, + new ValueListConfiguration.ValueListItem { Id = 8910, Value = "Value 3" } + } + } + }; - dataTypeServiceMock - .Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary - { - {"key0", new PreValue(4567, "Value 1")}, - {"key1", new PreValue(1234, "Value 2")}, - {"key2", new PreValue(8910, "Value 3")} - })); + var dataTypeService = Mock.Of(); - var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValuesMultipleValueEditor(false, dataTypeService, Mock.Of(), new ValueEditor()); + Mock.Get(dataTypeService) + .Setup(x => x.GetDataType(It.IsAny())) + .Returns(x => x == 1 ? dataType : null); + + var editor = new PublishValuesMultipleValueEditor(false, Mock.Of(), new ValueEditorAttribute("alias", "name", "view")); var prop = new Property(1, new PropertyType(new DataType(1, "Test.TestEditor"))); prop.SetValue("1234,4567,8910"); - var result = editor.ConvertDbToString(prop.PropertyType, prop.GetValue(), new Mock().Object); + var result = editor.ConvertDbToString(prop.PropertyType, prop.GetValue(), dataTypeService); Assert.AreEqual("Value 1,Value 2,Value 3", result); } @@ -68,23 +74,31 @@ namespace Umbraco.Tests.PropertyEditors [Test] public void DropDownValueEditor_Format_Data_For_Cache() { - var dataTypeServiceMock = new Mock(); - dataTypeServiceMock - .Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns(new PreValueCollection(new Dictionary - { - {"key0", new PreValue(10, "Value 1")}, - {"key1", new PreValue(1234, "Value 2")}, - {"key2", new PreValue(11, "Value 3")} - })); + var dataType = new DataType("editorAlias") + { + Configuration = new ValueListConfiguration + { + Items = new List + { + new ValueListConfiguration.ValueListItem { Id = 10, Value = "Value 1" }, + new ValueListConfiguration.ValueListItem { Id = 1234, Value = "Value 2" }, + new ValueListConfiguration.ValueListItem { Id = 11, Value = "Value 3" } + } + } + }; - var dataTypeService = dataTypeServiceMock.Object; - var editor = new PublishValueValueEditor(dataTypeService, new ValueEditor(), Mock.Of()); + var dataTypeService = Mock.Of(); + + Mock.Get(dataTypeService) + .Setup(x => x.GetDataType(It.IsAny())) + .Returns(x => x == 1 ? dataType : null); + + var editor = new PublishValueValueEditor(new ValueEditorAttribute("alias", "name", "view"), Mock.Of()); var prop = new Property(1, new PropertyType(new DataType(1, "Test.TestEditor"))); prop.SetValue("1234"); - var result = editor.ConvertDbToString(prop.PropertyType, prop.GetValue(), new Mock().Object); + var result = editor.ConvertDbToString(prop.PropertyType, prop.GetValue(), dataTypeService); Assert.AreEqual("Value 2", result); } @@ -110,16 +124,19 @@ namespace Umbraco.Tests.PropertyEditors //Current.ApplicationContext = appContext; var defaultVals = new Dictionary(); - var persisted = new PreValueCollection(new Dictionary + var configuration = new ValueListConfiguration + { + Items = new List { - {"item1", new PreValue(1, "Item 1")}, - {"item2", new PreValue(2, "Item 2")}, - {"item3", new PreValue(3, "Item 3")} - }); + new ValueListConfiguration.ValueListItem { Id = 1, Value = "Item 1" }, + new ValueListConfiguration.ValueListItem { Id = 2, Value = "Item 2" }, + new ValueListConfiguration.ValueListItem { Id = 3, Value = "Item 3" } + } + }; - var editor = new ValueListConfigurationEditor(Mock.Of(), logger); + var editor = new ValueListConfigurationEditor(Mock.Of()); - var result = editor.ConvertDbToEditor(defaultVals, persisted); + var result = editor.ToEditor(defaultVals, configuration); Assert.AreEqual(1, result.Count); Assert.IsTrue(result.ContainsKey("items")); diff --git a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs index 9f335d88b1..ab95929c4c 100644 --- a/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs +++ b/src/Umbraco.Tests/PropertyEditors/PropertyEditorValueEditorTests.cs @@ -40,7 +40,7 @@ namespace Umbraco.Tests.PropertyEditors [TestCase("hello world", false)] public void Value_Editor_Can_Convert_To_Json_Object_For_Editor(string value, bool isOk) { - var prop = new Property(1, new PropertyType("test", ValueStorageType.NVarChar)); + var prop = new Property(1, new PropertyType("test", ValueStorageType.Nvarchar)); prop.SetValue(value); var valueEditor = new ValueEditor @@ -131,7 +131,7 @@ namespace Umbraco.Tests.PropertyEditors [TestCase(ValueTypes.DateTime, "", "")] //test empty string for date public void Value_Editor_Can_Serialize_Value(string valueType, object val, string expected) { - var prop = new Property(1, new PropertyType("test", ValueStorageType.NVarChar)); + var prop = new Property(1, new PropertyType("test", ValueStorageType.Nvarchar)); prop.SetValue(val); var valueEditor = new ValueEditor diff --git a/src/Umbraco.Tests/Published/NestedContentTests.cs b/src/Umbraco.Tests/Published/NestedContentTests.cs index 33c38d78b8..95320ab144 100644 --- a/src/Umbraco.Tests/Published/NestedContentTests.cs +++ b/src/Umbraco.Tests/Published/NestedContentTests.cs @@ -31,28 +31,45 @@ namespace Umbraco.Tests.Published var profiler = Mock.Of(); var proflog = new ProfilingLogger(logger, profiler); - var dataTypeService = new Mock(); + var dataType1 = new DataType("editorAlias1") + { + Configuration = new NestedContentConfiguration + { + MinItems = 1, + MaxItems = 2, + ContentTypes = new[] + { + new NestedContentConfiguration.ContentType { Alias = "contentN1" } + } + } + }; + + var dataType2 = new DataType("editorAlias2") + { + Configuration = new NestedContentConfiguration + { + MinItems = 1, + MaxItems = 99, + ContentTypes = new[] + { + new NestedContentConfiguration.ContentType { Alias = "contentN1" } + } + } + }; // mocked dataservice returns nested content preValues - dataTypeService - .Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny())) - .Returns((int id) => + var dataTypeService = Mock.Of(); + + Mock.Get(dataTypeService) + .Setup(x => x.GetDataType(It.IsAny())) + .Returns(x => { - if (id == 1) - return new PreValueCollection(new Dictionary - { - { "minItems", new PreValue("1") }, - { "maxItems", new PreValue("1") }, - { "contentTypes", new PreValue("[{\"ncAlias\":\"contentN1\",\"ncTabAlias\":\"\",\"nameTemplate\":\"\"}]") } - }); - if (id == 2) - return new PreValueCollection(new Dictionary - { - { "minItems", new PreValue("1") }, - { "maxItems", new PreValue("99") }, - { "contentTypes", new PreValue("[{\"ncAlias\":\"contentN1\",\"ncTabAlias\":\"\",\"nameTemplate\":\"\"}]") } - }); - return null; + switch (x) + { + case 1: return dataType1; + case 2: return dataType2; + default: return null; + } }); var publishedModelFactory = new Mock(); @@ -113,7 +130,7 @@ namespace Umbraco.Tests.Published new NestedContentPropertyEditor(Mock.Of(), new Lazy(() => editors)) }); - var source = new DataTypeConfigurationSource(dataTypeService.Object, editors); + var source = new DataTypeConfigurationSource(dataTypeService, editors); var factory = new PublishedContentTypeFactory(publishedModelFactory.Object, converters, source); var propertyType1 = factory.CreatePropertyType("property1", 1, Constants.PropertyEditors.Aliases.NestedContent); diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs index 0dfee8d725..b08376efec 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTests.cs @@ -573,7 +573,7 @@ namespace Umbraco.Tests.PublishedContent var factory = Container.GetInstance() as PublishedContentTypeFactory; var pt1 = factory.CreatePropertyType("legend", 0, Constants.PropertyEditors.Aliases.Textbox); - var pt2 = factory.CreatePropertyType("image", 0, Constants.PropertyEditors.MediaPickerAlias); + var pt2 = factory.CreatePropertyType("image", 0, Constants.PropertyEditors.Aliases.MediaPicker2); var pt3 = factory.CreatePropertyType("size", 0, Constants.PropertyEditors.Aliases.Integer); const string val1 = "boom bam"; const int val2 = 0; diff --git a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs index 70554951bf..8e5436cce1 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedMediaTests.cs @@ -81,7 +81,7 @@ namespace Umbraco.Tests.PublishedContent var mType = MockedContentTypes.CreateImageMediaType("image2"); //lets add an RTE to this mType.PropertyGroups.First().PropertyTypes.Add( - new PropertyType("test", ValueStorageType.NVarChar, "content") + new PropertyType("test", ValueStorageType.Nvarchar, "content") { Name = "Rich Text", DataTypeId = -87 //tiny mce diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index f52b67cd56..fa09de431e 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -22,6 +22,7 @@ using Umbraco.Core.Persistence.Repositories.Implement; using Umbraco.Core.Scoping; using Umbraco.Core.Services.Implement; using Umbraco.Tests.Testing; +using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Services { @@ -698,12 +699,15 @@ namespace Umbraco.Tests.Services var contentService = ServiceContext.ContentService; var contentTypeService = ServiceContext.ContentTypeService; var dataTypeService = ServiceContext.DataTypeService; - //set the pre-values - dataTypeService.SavePreValues(1041, new Dictionary + + //set configuration + var dataType = dataTypeService.GetDataType(1041); + dataType.Configuration = new TagConfiguration { - {"group", new PreValue("test")}, - {"storageType", new PreValue("Csv")} - }); + Group = "test", + StorageType = TagCacheStorageType.Csv + }; + var contentType = MockedContentTypes.CreateSimpleContentType("umbMandatory", "Mandatory Doc Type", true); contentType.PropertyGroups.First().PropertyTypes.Add( new PropertyType("test", ValueStorageType.Ntext, "tags") diff --git a/src/Umbraco.Tests/Services/DataTypeServiceTests.cs b/src/Umbraco.Tests/Services/DataTypeServiceTests.cs index 1d827216dc..2f5833f3a8 100644 --- a/src/Umbraco.Tests/Services/DataTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/DataTypeServiceTests.cs @@ -59,161 +59,6 @@ namespace Umbraco.Tests.Services Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(1)); } - [Test] - public void DataTypeService_Can_Persist_Dictionary_Based_Pre_Values() - { - // Arrange - var dataTypeService = ServiceContext.DataTypeService; - var textBoxAlias = Constants.PropertyEditors.Aliases.Textbox; - - // Act - IDataType dataType = new DataType(-1, textBoxAlias) { Name = "Testing prevals", DatabaseType = ValueStorageType.Ntext }; - dataTypeService.Save(dataType); - dataTypeService.SavePreValues(dataType, new Dictionary - { - {"preVal1", new PreValue("Hello")}, - {"preVal2", new PreValue("World")} - }); - //re-get - dataType = dataTypeService.GetDataType(dataType.Id); - var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - // Assert - Assert.That(dataType, Is.Not.Null); - Assert.That(dataType.HasIdentity, Is.True); - Assert.AreEqual(true, preVals.IsDictionaryBased); - Assert.AreEqual(2, preVals.PreValuesAsDictionary.Keys.Count); - Assert.AreEqual("preVal1", preVals.PreValuesAsDictionary.Keys.First()); - Assert.AreEqual("preVal2", preVals.PreValuesAsDictionary.Keys.Last()); - Assert.AreEqual("Hello", preVals.PreValuesAsDictionary["preVal1"].Value); - Assert.AreEqual("World", preVals.PreValuesAsDictionary["preVal2"].Value); - } - - [Test] - public void DataTypeService_Can_Persist_Dtd_And_Dictionary_Based_Pre_Values() - { - // Arrange - var dataTypeService = ServiceContext.DataTypeService; - var textBoxAlias = Constants.PropertyEditors.Aliases.Textbox; - - // Act - IDataType dataType = new DataType(-1, textBoxAlias) { Name = "Testing prevals", DatabaseType = ValueStorageType.Ntext }; - dataTypeService.SaveDataTypeAndPreValues(dataType, new Dictionary - { - {"preVal1", new PreValue("Hello")}, - {"preVal2", new PreValue("World")} - }); - //re-get - dataType = dataTypeService.GetDataType(dataType.Id); - var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - // Assert - Assert.That(dataType, Is.Not.Null); - Assert.That(dataType.HasIdentity, Is.True); - Assert.AreEqual(true, preVals.IsDictionaryBased); - Assert.AreEqual(2, preVals.PreValuesAsDictionary.Keys.Count); - Assert.AreEqual("preVal1", preVals.PreValuesAsDictionary.Keys.First()); - Assert.AreEqual("preVal2", preVals.PreValuesAsDictionary.Keys.Last()); - Assert.AreEqual("Hello", preVals.PreValuesAsDictionary["preVal1"].Value); - Assert.AreEqual("World", preVals.PreValuesAsDictionary["preVal2"].Value); - } - - [Test] - public void DataTypeService_Can_Update_Pre_Values() - { - // Arrange - var dataTypeService = ServiceContext.DataTypeService; - var textBoxAlias = Constants.PropertyEditors.Aliases.Textbox; - - // Act - IDataType dataType = new DataType(-1, textBoxAlias) { Name = "Testing prevals", DatabaseType = ValueStorageType.Ntext }; - dataTypeService.SaveDataTypeAndPreValues(dataType, new Dictionary - { - {"preVal1", new PreValue("Hello")}, - {"preVal2", new PreValue("World")} - }); - //re-get - dataType = dataTypeService.GetDataType(dataType.Id); - var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - //update them (ensure Ids are there!) - var asDictionary = preVals.FormatAsDictionary(); - asDictionary["preVal1"].Value = "Hello2"; - asDictionary["preVal2"].Value = "World2"; - - dataTypeService.SavePreValues(dataType, asDictionary); - - var preValsAgain = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - // Assert - - Assert.AreEqual(preVals.PreValuesAsDictionary.Values.First().Id, preValsAgain.PreValuesAsDictionary.Values.First().Id); - Assert.AreEqual(preVals.PreValuesAsDictionary.Values.Last().Id, preValsAgain.PreValuesAsDictionary.Values.Last().Id); - Assert.AreEqual("preVal1", preValsAgain.PreValuesAsDictionary.Keys.First()); - Assert.AreEqual("preVal2", preValsAgain.PreValuesAsDictionary.Keys.Last()); - Assert.AreEqual("Hello2", preValsAgain.PreValuesAsDictionary["preVal1"].Value); - Assert.AreEqual("World2", preValsAgain.PreValuesAsDictionary["preVal2"].Value); - } - - [Test] - public void DataTypeService_Can_Remove_Pre_Value() - { - // Arrange - var dataTypeService = ServiceContext.DataTypeService; - var textBoxAlias = Constants.PropertyEditors.Aliases.Textbox; - - // Act - IDataType dataType = new DataType(-1, textBoxAlias) { Name = "Testing prevals", DatabaseType = ValueStorageType.Ntext }; - dataTypeService.SaveDataTypeAndPreValues(dataType, new Dictionary - { - {"preVal1", new PreValue("Hello")}, - {"preVal2", new PreValue("World")} - }); - //re-get - dataType = dataTypeService.GetDataType(dataType.Id); - var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - //update them (ensure Ids are there!) - var asDictionary = preVals.FormatAsDictionary(); - asDictionary.Remove("preVal2"); - - dataTypeService.SavePreValues(dataType, asDictionary); - - var preValsAgain = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - // Assert - - Assert.AreEqual(1, preValsAgain.FormatAsDictionary().Count); - Assert.AreEqual(preVals.PreValuesAsDictionary.Values.First().Id, preValsAgain.PreValuesAsDictionary.Values.First().Id); - Assert.AreEqual("preVal1", preValsAgain.PreValuesAsDictionary.Keys.First()); - - } - - [Test] - public void DataTypeService_Can_Persist_Array_Based_Pre_Values() - { - // Arrange - var dataTypeService = ServiceContext.DataTypeService; - var textBoxAlias = Constants.PropertyEditors.Aliases.Textbox; - - // Act - IDataType dataType = new DataType(-1, textBoxAlias) { Name = "Testing prevals", DatabaseType = ValueStorageType.Ntext }; - dataTypeService.Save(dataType); - dataTypeService.SavePreValues(dataType.Id, new[] {"preVal1", "preVal2"}); - - //re-get - dataType = dataTypeService.GetDataType(dataType.Id); - var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); - - // Assert - Assert.That(dataType, Is.Not.Null); - Assert.That(dataType.HasIdentity, Is.True); - Assert.AreEqual(false, preVals.IsDictionaryBased); - Assert.AreEqual(2, preVals.PreValuesAsArray.Count()); - Assert.AreEqual("preVal1", preVals.PreValuesAsArray.First().Value); - Assert.AreEqual("preVal2", preVals.PreValuesAsArray.Last().Value); - } - [Test] public void Cannot_Save_DataType_With_Empty_Name() { diff --git a/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs b/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs index a3974c6e16..39c1b3bc55 100644 --- a/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs +++ b/src/Umbraco.Tests/Services/Importing/PackageImportTests.cs @@ -308,14 +308,15 @@ namespace Umbraco.Tests.Services.Importing where (string)doc.Attribute("isDoc") == "" select doc).Count(); - DataTypePreValueDto preValueKey; - using (var scope = ScopeProvider.CreateScope()) - { - var dtos = scope.Database.Fetch("WHERE datatypeNodeId = @Id", new { dataTypeDefinitions.First().Id }); - int preValueId; - int.TryParse(contents.First().GetValue("testList"), out preValueId); - preValueKey = dtos.SingleOrDefault(x => x.Id == preValueId); - } + Assert.Fail("ARE WE REALLY IMPORTING PREVALUES IN PACKAGES?!"); + //DataTypePreValueDto preValueKey; + //using (var scope = ScopeProvider.CreateScope()) + //{ + // var dtos = scope.Database.Fetch("WHERE datatypeNodeId = @Id", new { dataTypeDefinitions.First().Id }); + // int preValueId; + // int.TryParse(contents.First().GetValue("testList"), out preValueId); + // preValueKey = dtos.SingleOrDefault(x => x.Id == preValueId); + //} // Assert Assert.That(dataTypeDefinitions, Is.Not.Null); @@ -325,8 +326,8 @@ namespace Umbraco.Tests.Services.Importing Assert.That(contentTypes.Any(), Is.True); Assert.That(contents.Any(), Is.True); Assert.That(contents.Count(), Is.EqualTo(numberOfDocs)); - Assert.That(preValueKey, Is.Not.Null); - Assert.That(preValueKey.Value, Is.EqualTo("test3")); + //Assert.That(preValueKey, Is.Not.Null); + //Assert.That(preValueKey.Value, Is.EqualTo("test3")); } [Test] diff --git a/src/Umbraco.Tests/Services/PreValueConverterTests.cs b/src/Umbraco.Tests/Services/PreValueConverterTests.cs deleted file mode 100644 index 9dd088704b..0000000000 --- a/src/Umbraco.Tests/Services/PreValueConverterTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NUnit.Framework; -using Umbraco.Core.Models; -using Umbraco.Core.Persistence.Repositories; -using Umbraco.Core.Persistence.Repositories.Implement; -using Umbraco.Core.Services; - -namespace Umbraco.Tests.Services -{ - [TestFixture] - public class PreValueConverterTests - { - [Test] - public void Can_Convert_To_Dictionary_Pre_Value_Collection() - { - var list = new List> - { - new Tuple(new PreValue(10, "value1"), "key1", 0), - new Tuple(new PreValue(11, "value2"), "key2", 3), - new Tuple(new PreValue(12, "value3"), "key3", 2), - new Tuple(new PreValue(13, "value4"), "key4", 1) - }; - - var result = DataTypeRepository.PreValueConverter.ConvertToPreValuesCollection(list); - - Assert.Throws(() => - { - var blah = result.PreValuesAsArray; - }); - - Assert.AreEqual(4, result.PreValuesAsDictionary.Count); - Assert.AreEqual("key1", result.PreValuesAsDictionary.ElementAt(0).Key); - Assert.AreEqual("key4", result.PreValuesAsDictionary.ElementAt(1).Key); - Assert.AreEqual("key3", result.PreValuesAsDictionary.ElementAt(2).Key); - Assert.AreEqual("key2", result.PreValuesAsDictionary.ElementAt(3).Key); - - } - - [Test] - public void Can_Convert_To_Array_Pre_Value_Collection_When_Empty_Key() - { - var list = new List> - { - new Tuple(new PreValue(10, "value1"), "", 0), - new Tuple(new PreValue(11, "value2"), "", 3), - new Tuple(new PreValue(12, "value3"), "", 2), - new Tuple(new PreValue(13, "value4"), "", 1) - }; - - var result = DataTypeRepository.PreValueConverter.ConvertToPreValuesCollection(list); - - Assert.Throws(() => - { - var blah = result.PreValuesAsDictionary; - }); - - Assert.AreEqual(4, result.PreValuesAsArray.Count()); - Assert.AreEqual("value1", result.PreValuesAsArray.ElementAt(0).Value); - Assert.AreEqual("value4", result.PreValuesAsArray.ElementAt(1).Value); - Assert.AreEqual("value3", result.PreValuesAsArray.ElementAt(2).Value); - Assert.AreEqual("value2", result.PreValuesAsArray.ElementAt(3).Value); - - } - - [Test] - public void Can_Convert_To_Array_Pre_Value_Collection() - { - var list = new List> - { - new Tuple(new PreValue(10, "value1"), "key1", 0), - new Tuple(new PreValue(11, "value2"), "key1", 3), - new Tuple(new PreValue(12, "value3"), "key3", 2), - new Tuple(new PreValue(13, "value4"), "key4", 1) - }; - - var result = DataTypeRepository.PreValueConverter.ConvertToPreValuesCollection(list); - - Assert.Throws(() => - { - var blah = result.PreValuesAsDictionary; - }); - - Assert.AreEqual(4, result.PreValuesAsArray.Count()); - Assert.AreEqual("value1", result.PreValuesAsArray.ElementAt(0).Value); - Assert.AreEqual("value4", result.PreValuesAsArray.ElementAt(1).Value); - Assert.AreEqual("value3", result.PreValuesAsArray.ElementAt(2).Value); - Assert.AreEqual("value2", result.PreValuesAsArray.ElementAt(3).Value); - - } - } -} diff --git a/src/Umbraco.Tests/TestHelpers/Entities/MockedContentTypes.cs b/src/Umbraco.Tests/TestHelpers/Entities/MockedContentTypes.cs index f97ea949d9..b1ba59e5c1 100644 --- a/src/Umbraco.Tests/TestHelpers/Entities/MockedContentTypes.cs +++ b/src/Umbraco.Tests/TestHelpers/Entities/MockedContentTypes.cs @@ -338,19 +338,19 @@ namespace Umbraco.Tests.TestHelpers.Entities contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.Boolean, ValueStorageType.Integer) { Alias = "isTrue", Name = "Is True or False", Mandatory = false, SortOrder = 1, DataTypeId = -49 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.Integer, ValueStorageType.Integer) { Alias = "number", Name = "Number", Mandatory = false, SortOrder = 2, DataTypeId = -51 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.TinyMce, ValueStorageType.Ntext) { Alias = "bodyText", Name = "Body Text", Mandatory = false, SortOrder = 3, DataTypeId = -87 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.Textbox, ValueStorageType.NVarChar) { Alias = "singleLineText", Name = "Text String", Mandatory = false, SortOrder = 4, DataTypeId = -88 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.Textbox, ValueStorageType.Nvarchar) { Alias = "singleLineText", Name = "Text String", Mandatory = false, SortOrder = 4, DataTypeId = -88 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.TextboxMultiple, ValueStorageType.Ntext) { Alias = "multilineText", Name = "Multiple Text Strings", Mandatory = false, SortOrder = 5, DataTypeId = -89 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.UploadField, ValueStorageType.NVarChar) { Alias = "upload", Name = "Upload Field", Mandatory = false, SortOrder = 6, DataTypeId = -90 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.NVarChar) { Alias = "label", Name = "Label", Mandatory = false, SortOrder = 7, DataTypeId = -92 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.UploadField, ValueStorageType.Nvarchar) { Alias = "upload", Name = "Upload Field", Mandatory = false, SortOrder = 6, DataTypeId = -90 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.Nvarchar) { Alias = "label", Name = "Label", Mandatory = false, SortOrder = 7, DataTypeId = -92 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.DateTime, ValueStorageType.Date) { Alias = "dateTime", Name = "Date Time", Mandatory = false, SortOrder = 8, DataTypeId = -36 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.ColorPicker, ValueStorageType.NVarChar) { Alias = "colorPicker", Name = "Color Picker", Mandatory = false, SortOrder = 9, DataTypeId = -37 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.ColorPicker, ValueStorageType.Nvarchar) { Alias = "colorPicker", Name = "Color Picker", Mandatory = false, SortOrder = 9, DataTypeId = -37 }); //that one is gone in 7.4 //contentCollection.Add(new PropertyType(Constants.PropertyEditors.FolderBrowserAlias, DataTypeDatabaseType.Nvarchar) { Alias = "folderBrowser", Name = "Folder Browser", Mandatory = false, SortOrder = 10, DataTypeDefinitionId = -38 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.DropDownListMultiple, ValueStorageType.NVarChar) { Alias = "ddlMultiple", Name = "Dropdown List Multiple", Mandatory = false, SortOrder = 11, DataTypeId = -39 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.RadioButtonList, ValueStorageType.NVarChar) { Alias = "rbList", Name = "Radio Button List", Mandatory = false, SortOrder = 12, DataTypeId = -40 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.DropDownListMultiple, ValueStorageType.Nvarchar) { Alias = "ddlMultiple", Name = "Dropdown List Multiple", Mandatory = false, SortOrder = 11, DataTypeId = -39 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.RadioButtonList, ValueStorageType.Nvarchar) { Alias = "rbList", Name = "Radio Button List", Mandatory = false, SortOrder = 12, DataTypeId = -40 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.Date, ValueStorageType.Date) { Alias = "date", Name = "Date", Mandatory = false, SortOrder = 13, DataTypeId = -41 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.DropDownList, ValueStorageType.Integer) { Alias = "ddl", Name = "Dropdown List", Mandatory = false, SortOrder = 14, DataTypeId = -42 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.CheckBoxList, ValueStorageType.NVarChar) { Alias = "chklist", Name = "Checkbox List", Mandatory = false, SortOrder = 15, DataTypeId = -43 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.CheckBoxList, ValueStorageType.Nvarchar) { Alias = "chklist", Name = "Checkbox List", Mandatory = false, SortOrder = 15, DataTypeId = -43 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.ContentPicker2Alias, ValueStorageType.Integer) { Alias = "contentPicker", Name = "Content Picker", Mandatory = false, SortOrder = 16, DataTypeId = 1046 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.MediaPicker2, ValueStorageType.Integer) { Alias = "mediaPicker", Name = "Media Picker", Mandatory = false, SortOrder = 17, DataTypeId = 1048 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.MemberPicker2, ValueStorageType.Integer) { Alias = "memberPicker", Name = "Member Picker", Mandatory = false, SortOrder = 18, DataTypeId = 1047 }); @@ -383,7 +383,7 @@ namespace Umbraco.Tests.TestHelpers.Entities var contentCollection = new PropertyTypeCollection(false); contentCollection.Add(new PropertyType("test", ValueStorageType.Ntext) { Alias = "title", Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); - contentCollection.Add(new PropertyType("test", ValueStorageType.NVarChar) { Alias = "videoFile", Name = "Video File", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); + contentCollection.Add(new PropertyType("test", ValueStorageType.Nvarchar) { Alias = "videoFile", Name = "Video File", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); mediaType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Media", SortOrder = 1 }); @@ -408,11 +408,11 @@ namespace Umbraco.Tests.TestHelpers.Entities }; var contentCollection = new PropertyTypeCollection(false); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.UploadField, ValueStorageType.NVarChar) { Alias = Constants.Conventions.Media.File, Name = "File", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -90 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.UploadField, ValueStorageType.Nvarchar) { Alias = Constants.Conventions.Media.File, Name = "File", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -90 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.Integer) { Alias = Constants.Conventions.Media.Width, Name = "Width", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.Integer) { Alias = Constants.Conventions.Media.Height, Name = "Height", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.Integer) { Alias = Constants.Conventions.Media.Bytes, Name = "Bytes", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); - contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.NVarChar) { Alias = Constants.Conventions.Media.Extension, Name = "File Extension", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); + contentCollection.Add(new PropertyType(Constants.PropertyEditors.Aliases.NoEdit, ValueStorageType.Nvarchar) { Alias = Constants.Conventions.Media.Extension, Name = "File Extension", Description = "", Mandatory = false, SortOrder = 2, DataTypeId = -90 }); mediaType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Media", SortOrder = 1 }); diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index 7f706a425d..1256a7a130 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; @@ -15,6 +16,7 @@ using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Mappers; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.SqlSyntax; +using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Services.Implement; @@ -175,7 +177,7 @@ namespace Umbraco.Tests.TestHelpers GetRepo(c))); var macroService = GetLazyService(container, c => new MacroService(scopeProvider, logger, eventMessagesFactory, GetRepo(c), GetRepo(c))); - var packagingService = GetLazyService(container, c => new PackagingService(logger, contentService.Value, contentTypeService.Value, mediaService.Value, macroService.Value, dataTypeService.Value, fileService.Value, localizationService.Value, entityService.Value, userService.Value, scopeProvider, urlSegmentProviders, GetRepo(c), GetRepo(c))); + var packagingService = GetLazyService(container, c => new PackagingService(logger, contentService.Value, contentTypeService.Value, mediaService.Value, macroService.Value, dataTypeService.Value, fileService.Value, localizationService.Value, entityService.Value, userService.Value, scopeProvider, urlSegmentProviders, GetRepo(c), GetRepo(c), new PropertyEditorCollection(Enumerable.Empty()))); var relationService = GetLazyService(container, c => new RelationService(scopeProvider, logger, eventMessagesFactory, entityService.Value, GetRepo(c), GetRepo(c))); var treeService = GetLazyService(container, c => new ApplicationTreeService(logger, cache)); var tagService = GetLazyService(container, c => new TagService(scopeProvider, logger, eventMessagesFactory, GetRepo(c))); diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index 70b2905297..e8c5361a48 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -350,7 +350,6 @@ - @@ -420,7 +419,6 @@ - @@ -437,7 +435,6 @@ - diff --git a/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs b/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs index 9e91fcf7ba..9632737515 100644 --- a/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs +++ b/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs @@ -54,9 +54,11 @@ namespace Umbraco.Web.Migrations if (syntax.SupportsIdentityInsert()) scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", syntax.GetQuotedTableName(Constants.DatabaseSchema.Tables.DataType)))); + const string memberListViewConfiguration = "{\"pageSize\":10,\"orderBy\":Name,\"orderDirection\":asc,includeProperties:[{\"alias\":\"email\",\"isSystem\":1},{\"alias\":\"username\",\"isSystem\":1},{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1}]}"; + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultContentListView, EditorAlias = Constants.PropertyEditors.Aliases.ListView, DbType = "Nvarchar" }); scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultMediaListView, EditorAlias = Constants.PropertyEditors.Aliases.ListView, DbType = "Nvarchar" }); - scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.Aliases.ListView, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.Aliases.ListView, DbType = "Nvarchar", Configuration = memberListViewConfiguration }); } finally { @@ -64,25 +66,6 @@ namespace Umbraco.Web.Migrations if (syntax.SupportsIdentityInsert()) scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", syntax.GetQuotedTableName(Constants.DatabaseSchema.Tables.DataType)))); } - - try - { - //Turn on identity insert if db provider is not mysql - if (syntax.SupportsIdentityInsert()) - scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", syntax.GetQuotedTableName("cmsDataTypePreValues")))); - - //defaults for the member list - scope.Database.Insert("cmsDataTypePreValues", "id", false, new DataTypePreValueDto { Id = -1, Alias = "pageSize", SortOrder = 1, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "10" }); - scope.Database.Insert("cmsDataTypePreValues", "id", false, new DataTypePreValueDto { Id = -2, Alias = "orderBy", SortOrder = 2, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "Name" }); - scope.Database.Insert("cmsDataTypePreValues", "id", false, new DataTypePreValueDto { Id = -3, Alias = "orderDirection", SortOrder = 3, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "asc" }); - scope.Database.Insert("cmsDataTypePreValues", "id", false, new DataTypePreValueDto { Id = -4, Alias = "includeProperties", SortOrder = 4, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "[{\"alias\":\"email\",\"isSystem\":1},{\"alias\":\"username\",\"isSystem\":1},{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1}]" }); - } - finally - { - //Turn off identity insert if db provider is not mysql - if (syntax.SupportsIdentityInsert()) - scope.Database.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", syntax.GetQuotedTableName("cmsDataTypePreValues")))); - } } } } diff --git a/src/Umbraco.Web/Models/Mapping/ContentPropertyDisplayConverter.cs b/src/Umbraco.Web/Models/Mapping/ContentPropertyDisplayConverter.cs index ab0381f008..bc047dbc07 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentPropertyDisplayConverter.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentPropertyDisplayConverter.cs @@ -27,7 +27,7 @@ namespace Umbraco.Web.Models.Mapping //configure the editor for display with the pre-values var valEditor = display.PropertyEditor.ValueEditor; - valEditor.ConfigureForDisplay(config); + valEditor.Configuration = config; //set the display properties after mapping display.Alias = originalProp.Alias; @@ -49,7 +49,7 @@ namespace Umbraco.Web.Models.Mapping else { //let the property editor format the pre-values - display.Config = display.PropertyEditor.ConfigurationEditor.ConvertDbToEditor(display.PropertyEditor.DefaultPreValues, preVals); + display.Config = display.PropertyEditor.ConfigurationEditor.ToEditor(display.PropertyEditor.DefaultConfiguration, config); display.View = valEditor.View; } diff --git a/src/Umbraco.Web/Models/Mapping/DataTypeConfigurationFieldDisplayResolver.cs b/src/Umbraco.Web/Models/Mapping/DataTypeConfigurationFieldDisplayResolver.cs index d948357d5d..d86ad1cf3b 100644 --- a/src/Umbraco.Web/Models/Mapping/DataTypeConfigurationFieldDisplayResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/DataTypeConfigurationFieldDisplayResolver.cs @@ -49,7 +49,7 @@ namespace Umbraco.Web.Models.Mapping if (editor != null) { fields = editor.ConfigurationEditor.Fields.Select(Mapper.Map).ToArray(); - configuration = editor.ConfigurationEditor.ToEditor(editor.DefaultPreValues, configuration); + configuration = editor.ConfigurationEditor.ToEditor(editor.DefaultConfiguration, configuration); } // either it's a dictionary already, or convert diff --git a/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs index c1c886bac1..1044b0f104 100644 --- a/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs @@ -105,7 +105,7 @@ namespace Umbraco.Web.Models.Mapping .ConvertUsing(src => { //this is a new data type, so just return the field editors, there are no values yet - var defaultVals = src.DefaultPreValues; + var defaultVals = src.DefaultConfiguration; var fields = src.ConfigurationEditor.Fields.Select(Mapper.Map).ToArray(); if (defaultVals != null) { diff --git a/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs b/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs index 9d2270db54..be19be9c50 100644 --- a/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/PropertyTypeGroupResolver.cs @@ -213,7 +213,7 @@ namespace Umbraco.Web.Models.Mapping Validation = new PropertyTypeValidation {Mandatory = p.Mandatory, Pattern = p.ValidationRegExp}, Label = p.Name, View = propertyEditor.ValueEditor.View, - Config = propertyEditor.ConfigurationEditor.ConvertDbToEditor(propertyEditor.DefaultPreValues, configuration), + Config = propertyEditor.ConfigurationEditor.ToEditor(propertyEditor.DefaultConfiguration, configuration), //Value = "", GroupId = groupId, Inherited = inherited, diff --git a/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs b/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs index df843ed178..78812e0f4e 100644 --- a/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs @@ -162,7 +162,7 @@ namespace Umbraco.Web.Models.Mapping IsActive = true }; - var listViewConfig = editor.ConfigurationEditor.ConvertDbToEditor(editor.DefaultPreValues, dt.Configuration); + var listViewConfig = editor.ConfigurationEditor.ToEditor(editor.DefaultConfiguration, dt.Configuration); //add the entity type to the config listViewConfig["entityType"] = entityType; diff --git a/src/Umbraco.Web/PropertyEditors/ContentPicker2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/ContentPicker2PropertyEditor.cs index 47e670081f..a4f4c573a2 100644 --- a/src/Umbraco.Web/PropertyEditors/ContentPicker2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ContentPicker2PropertyEditor.cs @@ -26,7 +26,7 @@ namespace Umbraco.Web.PropertyEditors internal IDictionary InternalPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => InternalPreValues; set => InternalPreValues = value; diff --git a/src/Umbraco.Web/PropertyEditors/DatePropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/DatePropertyEditor.cs index 9600c96f92..9b0aa53a4c 100644 --- a/src/Umbraco.Web/PropertyEditors/DatePropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DatePropertyEditor.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.PropertyEditors private IDictionary _defaultPreVals; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get { return _defaultPreVals; } set { _defaultPreVals = value; } diff --git a/src/Umbraco.Web/PropertyEditors/DateTimePropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/DateTimePropertyEditor.cs index 943f41ffb7..e4f2dd7683 100644 --- a/src/Umbraco.Web/PropertyEditors/DateTimePropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DateTimePropertyEditor.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web.PropertyEditors /// /// Overridden because we ONLY support Date + Time format /// - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get { return _defaultPreVals; } set { _defaultPreVals = value; } diff --git a/src/Umbraco.Web/PropertyEditors/DropDownMultipleConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/DropDownMultipleConfigurationEditor.cs index 4099cd1310..e6b237c8bf 100644 --- a/src/Umbraco.Web/PropertyEditors/DropDownMultipleConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/DropDownMultipleConfigurationEditor.cs @@ -60,9 +60,9 @@ namespace Umbraco.Web.PropertyEditors // FromEditor can totally ignore 'multiple' /// - public override Dictionary ToEditor(ValueListConfiguration defaultConfiguration, ValueListConfiguration configuration) + public override Dictionary ToEditor(ValueListConfiguration configuration) { - var dictionary = base.ToEditor(defaultConfiguration, configuration); + var dictionary = base.ToEditor(configuration); // always add the multiple field, as 'true' dictionary["multiple"] = 1; diff --git a/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs index 58c3281b4f..12271e94af 100644 --- a/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/FileUploadPropertyEditor.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; using System.Linq; -using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -16,13 +14,11 @@ namespace Umbraco.Web.PropertyEditors public class FileUploadPropertyEditor : PropertyEditor { private readonly MediaFileSystem _mediaFileSystem; - private readonly ILocalizedTextService _textService; - public FileUploadPropertyEditor(ILogger logger, MediaFileSystem mediaFileSystem,ILocalizedTextService textService) + public FileUploadPropertyEditor(ILogger logger, MediaFileSystem mediaFileSystem) : base(logger) { _mediaFileSystem = mediaFileSystem ?? throw new ArgumentNullException(nameof(mediaFileSystem)); - _textService = textService ?? throw new ArgumentNullException(nameof(textService)); } /// @@ -36,12 +32,6 @@ namespace Umbraco.Web.PropertyEditors return editor; } - /// - /// Creates the corresponding preValue editor. - /// - /// The corresponding preValue editor. - protected override ConfigurationEditor CreateConfigurationEditor() => new FileUploadConfigurationEditor(_textService); - /// /// Gets a value indicating whether a property is an upload field. /// @@ -161,92 +151,5 @@ namespace Umbraco.Web.PropertyEditors } } } - - /// - /// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in - /// - internal class FileUploadConfigurationEditor : ValueListConfigurationEditor - { - public FileUploadConfigurationEditor(ILocalizedTextService textService) - : base(textService) - { - var field = Fields.First(); - field.Description = "Enter a max width/height for each thumbnail"; - field.Name = "Add thumbnail size"; - //need to have some custom validation happening here - field.Validators.Add(new ThumbnailListValidator()); - } - - /// - public override Dictionary ToEditor(ValueListConfiguration defaultConfiguration, ValueListConfiguration configuration) - { - var result = new List(); - - //the pre-values just take up one field with a semi-colon delimiter so we'll just parse - var dictionary = configuration.FormatAsDictionary(); - if (dictionary.Any()) - { - //there should only be one val - var delimited = dictionary.First().Value.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - var i = 0; - result.AddRange(delimited.Select(x => new PreValue(i++, x))); - } - - //the items list will be a dictionary of it's id -> value we need to use the id for persistence for backwards compatibility - return new Dictionary { { "items", result.ToDictionary(x => x.Id, PreValueAsDictionary) } }; - } - - private IDictionary PreValueAsDictionary(PreValue preValue) - { - return new Dictionary { { "value", preValue.Value }, { "sortOrder", preValue.SortOrder } }; - } - /// - /// Take the posted values and convert them to a semi-colon separated list so that its backwards compatible - /// - /// - /// - /// - public override ValueListConfiguration FromEditor(Dictionary editorValue, ValueListConfiguration configuration) - { - var result = base.ConvertEditorToDb(editorValue, configuration); - - //this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is - // semi-colon delimited - var values = result.Select(item => item.Value.Value).ToList(); - - result.Clear(); - result.Add("thumbs", new PreValue(string.Join(";", values))); - return result; - } - - internal class ThumbnailListValidator : IValueValidator - { - public IEnumerable Validate(object value, string valueType, object dataTypeConfiguration) - { - if (!(value is JArray json)) yield break; - - //validate each item which is a json object - for (var index = 0; index < json.Count; index++) - { - var i = json[index]; - var jItem = i as JObject; - if (jItem?["value"] == null) continue; - - //NOTE: we will be removing empty values when persisting so no need to validate - var asString = jItem["value"].ToString(); - if (asString.IsNullOrWhiteSpace()) continue; - - if (int.TryParse(asString, out _) == false) - { - yield return new ValidationResult("The value " + asString + " is not a valid number", new[] - { - //we'll make the server field the index number of the value so it can be wired up to the view - "item_" + index.ToInvariantString() - }); - } - } - } - } - } } } diff --git a/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyEditor.cs index 3f3b6f6e6f..16239ec741 100644 --- a/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ImageCropperPropertyEditor.cs @@ -41,7 +41,7 @@ namespace Umbraco.Web.PropertyEditors _autoFillProperties = new UploadAutoFillProperties(_mediaFileSystem, Logger, contentSettings1); } - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => _internalPreValues; set => _internalPreValues = value; @@ -51,20 +51,13 @@ namespace Umbraco.Web.PropertyEditors /// Creates the corresponding property value editor. /// /// The corresponding property value editor. - protected override ValueEditor CreateValueEditor() - { - var baseEditor = base.CreateValueEditor(); - return new ImageCropperPropertyValueEditor(baseEditor, Logger, _mediaFileSystem); - } + protected override ValueEditor CreateValueEditor() => new ImageCropperPropertyValueEditor(Attribute, Logger, _mediaFileSystem); /// /// Creates the corresponding preValue editor. /// /// The corresponding preValue editor. - protected override ConfigurationEditor CreateConfigurationEditor() - { - return new ImageCropperConfigurationEditor(); - } + protected override ConfigurationEditor CreateConfigurationEditor() => new ImageCropperConfigurationEditor(); /// /// Gets a value indicating whether a property is an image cropper field. diff --git a/src/Umbraco.Web/PropertyEditors/ListViewConfiguration.cs b/src/Umbraco.Web/PropertyEditors/ListViewConfiguration.cs index 210943aa0b..b4ac776d7b 100644 --- a/src/Umbraco.Web/PropertyEditors/ListViewConfiguration.cs +++ b/src/Umbraco.Web/PropertyEditors/ListViewConfiguration.cs @@ -1,4 +1,5 @@ -using Umbraco.Core.PropertyEditors; +using Newtonsoft.Json; +using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { @@ -7,44 +8,88 @@ namespace Umbraco.Web.PropertyEditors /// public class ListViewConfiguration { - [ConfigurationField("tabName", "Tab Name", "textstring", Description = "The name of the listview tab (default if empty: 'Child Items')")] - public int TabName { get; set; } - - [ConfigurationField("displayAtTabNumber", "Display At Tab Number", "number", Description = "Which tab position that the list of child items will be displayed")] - public int DisplayAtTabNumber { get; set; } - [ConfigurationField("pageSize", "Page Size", "number", Description = "Number of items per page")] + [JsonProperty("pageSize")] public int PageSize { get; set; } - [ConfigurationField("layouts", "Layouts", "views/propertyeditors/listview/layouts.prevalues.html")] - public int Layouts { get; set; } - - [ConfigurationField("includeProperties", "Columns Displayed", "views/propertyeditors/listview/includeproperties.prevalues.html", - Description = "The properties that will be displayed for each column")] - public object IncludeProperties { get; set; } // fixme object ?! + [ConfigurationField("displayAtTabNumber", "Display At Tab Number", "number", Description = "Which tab position that the list of child items will be displayed")] + [JsonProperty("displayAtNumber")] + public int DisplayAtTabNumber { get; set; } [ConfigurationField("orderBy", "Order By", "views/propertyeditors/listview/sortby.prevalues.html", Description = "The default sort order for the list")] - public int OrderBy { get; set; } + [JsonProperty("orderBy")] + public string OrderBy { get; set; } [ConfigurationField("orderDirection", "Order Direction", "views/propertyeditors/listview/orderdirection.prevalues.html")] - public int OrderDirection { get; set; } + [JsonProperty("orderDirection")] + public string OrderDirection { get; set; } + + + [ConfigurationField("includeProperties", "Columns Displayed", "views/propertyeditors/listview/includeproperties.prevalues.html", + Description = "The properties that will be displayed for each column")] + [JsonProperty("includeProperties")] + public Property[] IncludeProperties { get; set; } + + [ConfigurationField("layouts", "Layouts", "views/propertyeditors/listview/layouts.prevalues.html")] + [JsonProperty("layouts")] + public Layout[] Layouts { get; set; } [ConfigurationField("bulkActionPermissions", "Bulk Action Permissions", "views/propertyeditors/listview/bulkactionpermissions.prevalues.html", Description = "The bulk actions that are allowed from the list view")] - public BulkActionPermissionSettings BulkActionPermissions { get; set; } + [JsonProperty("bulkActionPermissions")] + public BulkActionPermissionSettings BulkActionPermissions { get; set; } = new BulkActionPermissionSettings(); // fixme managing defaults? + + [ConfigurationField("tabName", "Tab Name", "textstring", Description = "The name of the listview tab (default if empty: 'Child Items')")] + [JsonProperty("tabName")] + public int TabName { get; set; } + + public class Property + { + [JsonProperty("alias")] + public string Alias { get; set; } + + [JsonProperty("header")] + public string Header { get; set; } + + [JsonProperty("isSystem")] + public int IsSystem { get; set; } // fixme bool + } + + public class Layout + { + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("path")] + public string Path { get; set; } + + [JsonProperty("icon")] + public string Icon { get; set; } + + [JsonProperty("isSystem")] + public int IsSystem { get; set; } // fixme bool + + [JsonProperty("selected")] + public bool Selected { get; set; } + } public class BulkActionPermissionSettings { - public bool AllowBulkPublish { get; set; } + [JsonProperty("allowBulkPublish")] + public bool AllowBulkPublish { get; set; } = true; - public bool AllowBulkUnpublish { get; set; } + [JsonProperty("allowBulkUnpublish")] + public bool AllowBulkUnpublish { get; set; } = true; - public bool AllowBulkCopy { get; set; } + [JsonProperty("allowBulkCopy")] + public bool AllowBulkCopy { get; set; } = true; - public bool AllowBulkMove { get; set; } + [JsonProperty("allowBulkMove")] + public bool AllowBulkMove { get; set; } = true; - public bool AllowBulkDelete { get; set; } + [JsonProperty("allowBulkDelete")] + public bool AllowBulkDelete { get; set; } = true; } } } \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/ListViewPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/ListViewPropertyEditor.cs index 39b1969dd6..94f75783f7 100644 --- a/src/Umbraco.Web/PropertyEditors/ListViewPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ListViewPropertyEditor.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.PropertyEditors return new ListViewConfigurationEditor(); } - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get { diff --git a/src/Umbraco.Web/PropertyEditors/MediaPicker2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MediaPicker2PropertyEditor.cs index b2b2cd2965..3ac1bbd7fc 100644 --- a/src/Umbraco.Web/PropertyEditors/MediaPicker2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MediaPicker2PropertyEditor.cs @@ -22,7 +22,7 @@ namespace Umbraco.Web.PropertyEditors internal IDictionary InternalPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => InternalPreValues; set => InternalPreValues = value; diff --git a/src/Umbraco.Web/PropertyEditors/MemberPicker2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MemberPicker2PropertyEditor.cs index e70ee1fae5..d1ffe3e372 100644 --- a/src/Umbraco.Web/PropertyEditors/MemberPicker2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MemberPicker2PropertyEditor.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.PropertyEditors internal IDictionary InternalPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => InternalPreValues; set => InternalPreValues = value; diff --git a/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationEditor.cs index 825f9ce506..5cbe1be47a 100644 --- a/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultiNodePickerConfigurationEditor.cs @@ -76,10 +76,10 @@ namespace Umbraco.Web.PropertyEditors } /// - public override Dictionary ToEditor(MultiNodePickerConfiguration defaultConfiguration, MultiNodePickerConfiguration configuration) + public override Dictionary ToEditor(MultiNodePickerConfiguration configuration) { // sanitize configuraiton - var output = base.ToEditor(defaultConfiguration, configuration); + var output = base.ToEditor(configuration); output["multiPicker"] = configuration.MaxNumber > 1 ? "1" : "0"; diff --git a/src/Umbraco.Web/PropertyEditors/MultiNodeTreePicker2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MultiNodeTreePicker2PropertyEditor.cs index 07b498349e..e6d8b8980a 100644 --- a/src/Umbraco.Web/PropertyEditors/MultiNodeTreePicker2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultiNodeTreePicker2PropertyEditor.cs @@ -28,7 +28,7 @@ namespace Umbraco.Web.PropertyEditors internal IDictionary InternalPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => InternalPreValues; set => InternalPreValues = value; diff --git a/src/Umbraco.Web/PropertyEditors/MultipleTextStringConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/MultipleTextStringConfigurationEditor.cs index 3c3741abe2..f3b4cf4d0e 100644 --- a/src/Umbraco.Web/PropertyEditors/MultipleTextStringConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultipleTextStringConfigurationEditor.cs @@ -48,7 +48,7 @@ namespace Umbraco.Web.PropertyEditors } /// - public override Dictionary ToEditor(MultipleTestStringConfiguration defaultConfiguration, MultipleTestStringConfiguration configuration) + public override Dictionary ToEditor(MultipleTestStringConfiguration configuration) { return new Dictionary { diff --git a/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs index 6b2b935941..e7a3cf1e4b 100644 --- a/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultipleTextStringPropertyEditor.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.Logging; @@ -50,21 +49,9 @@ namespace Umbraco.Web.PropertyEditors return null; } - var preVals = editorValue.PreValues.FormatAsDictionary(); - var max = -1; - if (preVals.Any()) - { - try - { - var json = JsonConvert.DeserializeObject(preVals.First().Value.Value); - max = int.Parse(json["Maximum"].ToString()); - } - catch (Exception) - { - //swallow - max = -1; - } - } + if (!(editorValue.DataTypeConfiguration is MultipleTestStringConfiguration config)) + throw new Exception("panic"); + var max = config.Maximum; //The legacy property editor saved this data as new line delimited! strange but we have to maintain that. var array = asArray.OfType() diff --git a/src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs b/src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs index 4356c6786d..1fabe5ee7a 100644 --- a/src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs +++ b/src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs @@ -1,20 +1,21 @@ -using Umbraco.Core.PropertyEditors; +using Newtonsoft.Json; +using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// /// Represents the configuration for the nested content value editor. /// - public class NestedContentConfiguration : ConfigurationEditor + public class NestedContentConfiguration { [ConfigurationField("contentTypes", "Doc Types", "views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html", Description = "Select the doc types to use as the data blueprint.")] - public string[] ContentTypes { get; set; } + public ContentType[] ContentTypes { get; set; } [ConfigurationField("minItems", "Min Items", "number", Description = "Set the minimum number of items allowed.")] - public int MinItems { get; set; } + public int? MinItems { get; set; } [ConfigurationField("maxItems", "Max Items", "number", Description = "Set the maximum number of items allowed.")] - public int MaxItems { get; set; } + public int? MaxItems { get; set; } [ConfigurationField("confirmDeletes", "Confirm Deletes", "boolean", Description = "Set whether item deletions should require confirming.")] public string ConfirmDeletes { get; set; } // fixme bool @@ -24,5 +25,17 @@ namespace Umbraco.Web.PropertyEditors [ConfigurationField("hideLabel", "Hide Label", "boolean", Description = "Set whether to hide the editor label and have the list take up the full width of the editor window.")] public string HideLabel { get; set; } // fixme bool + + public class ContentType + { + [JsonProperty("ncAlias")] + public string Alias { get; set; } + + [JsonProperty("ncTabAlias")] + public string TabAlias { get; set; } + + [JsonProperty("nameTemplate")] + public string Template { get; set; } + } } } \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs index 3e5b25106d..8d3ef378b1 100644 --- a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.PropertyEditors internal const string ContentTypeAliasPropertyKey = "ncContentTypeAlias"; private IDictionary _defaultPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => _defaultPreValues; set => _defaultPreValues = value; @@ -37,7 +37,7 @@ namespace Umbraco.Web.PropertyEditors // Setup default values _defaultPreValues = new Dictionary { - {NestedContentConfigurationEditor.ContentTypesPreValueKey, ""}, + {"contentTypes", ""}, {"minItems", 0}, {"maxItems", 0}, {"confirmDeletes", "1"}, @@ -65,49 +65,6 @@ namespace Umbraco.Web.PropertyEditors #endregion - #region DataType Configuration - - public class Configuration - { - public NestedContentType[] ContentTypes { get; set; } - public int? MinItems { get; set; } - public int? MaxItems { get; set; } - public bool ConfirmDeletes { get; set; } - public bool ShowIcons { get; set; } - public bool HideLabel { get; set; } - - public class NestedContentType - { - [JsonProperty("ncAlias")] - public string Alias { get; set; } - [JsonProperty("ncTabAlias")] - public string Tab { get; set; } - [JsonProperty("nameTemplate")] - public string Template { get; set; } - } - } - - public override object DeserializeConfiguration(string json) - { - return JsonConvert.DeserializeObject(json); - - // fixme - can we have issues converting true/1 and false/0? - //var d = preValues.PreValuesAsDictionary; - //return new Configuration - //{ - // ContentTypes = d.TryGetValue("contentTypes", out var preValue) - // ? JsonConvert.DeserializeObject(preValue.Value) - // : Array.Empty(), - // MinItems = d.TryGetValue("minItems", out preValue) && int.TryParse(preValue.Value, out var minItems) ? (int?) minItems : null, - // MaxItems = d.TryGetValue("maxItems", out preValue) && int.TryParse(preValue.Value, out var maxItems) ? (int?) maxItems : null, - // ConfirmDeletes = d.TryGetValue("confirmDeletes", out preValue) && preValue.Value == "1", - // ShowIcons = d.TryGetValue("showIcons", out preValue) && preValue.Value == "1", - // HideLabel = d.TryGetValue("hideLabel", out preValue) && preValue.Value == "1" - //}; - } - - #endregion - #region Value Editor protected override ValueEditor CreateValueEditor() => new NestedContentPropertyValueEditor(Attribute, PropertyEditors); @@ -125,18 +82,18 @@ namespace Umbraco.Web.PropertyEditors internal ServiceContext Services => Current.Services; - public override void ConfigureForDisplay(PreValueCollection preValues) + /// + public override object Configuration { - base.ConfigureForDisplay(preValues); - - var asDictionary = preValues.PreValuesAsDictionary.ToDictionary(x => x.Key, x => x.Value.Value); - if (asDictionary.ContainsKey("hideLabel")) + get => base.Configuration; + set { - var boolAttempt = asDictionary["hideLabel"].TryConvertTo(); - if (boolAttempt.Success) - { - HideLabel = boolAttempt.Result; - } + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (!(value is NestedContentConfiguration configuration)) + throw new ArgumentException($"Expected a {typeof(RichTextConfiguration).Name} instance, but got {value.GetType().Name}.", nameof(value)); + HideLabel = configuration.HideLabel.TryConvertTo().Result; + base.Configuration = value; } } diff --git a/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs b/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs index e734ed5eb3..6f5ad91aa5 100644 --- a/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/PublishValueValueEditor.cs @@ -18,62 +18,37 @@ namespace Umbraco.Web.PropertyEditors /// internal class PublishValueValueEditor : ValueEditor { - private readonly IDataTypeService _dataTypeService; private readonly ILogger _logger; - internal PublishValueValueEditor(IDataTypeService dataTypeService, ValueEditorAttribute attribute, ILogger logger) + internal PublishValueValueEditor(ValueEditorAttribute attribute, ILogger logger) : base(attribute) { - _dataTypeService = dataTypeService; _logger = logger; } - public PublishValueValueEditor(ValueEditorAttribute attribute, ILogger logger) - : this(Current.Services.DataTypeService, attribute, logger) - { - } - - /// - /// Need to lookup the pre-values and put the string version in cache, not the ID (which is what is stored in the db) - /// - /// - /// - /// - /// + /// public override string ConvertDbToString(PropertyType propertyType, object value, IDataTypeService dataTypeService) { if (value == null) return null; + // fixme we should probably completely kill this editor + + var configuration = dataTypeService.GetDataType(propertyType.DataTypeId).ConfigurationAs(); + var items = configuration.Items; + var idAttempt = value.TryConvertTo(); if (idAttempt.Success) { - var preValId = idAttempt.Result; - var preVals = GetPreValues(propertyType); - if (preVals != null) - { - if (preVals.Any(x => x.Value.Id == preValId)) - { - return preVals.Single(x => x.Value.Id == preValId).Value.Value; - } + var itemId = idAttempt.Result; + var item = items.FirstOrDefault(x => x.Id == itemId); + if (item != null) return item.Value; - _logger.Warn("Could not find a pre value with ID " + preValId + " for property alias " + propertyType.Alias); - } + _logger.Warn("Could not find a configuration item with ID " + itemId + " for property alias " + propertyType.Alias); } // fallback to default return base.ConvertDbToString(propertyType, value, dataTypeService); } - - protected IDictionary GetPreValues(PropertyType propertyType) - { - var config = _dataTypeService.GetDataType(propertyType.DataTypeId).Configuration; - if (preVals != null) - { - var dictionary = preVals.FormatAsDictionary(); - return dictionary; - } - return null; - } } } diff --git a/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs b/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs index 91687c17de..378419b02f 100644 --- a/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/PublishValuesMultipleValueEditor.cs @@ -21,14 +21,14 @@ namespace Umbraco.Web.PropertyEditors { private readonly bool _publishIds; - internal PublishValuesMultipleValueEditor(bool publishIds, IDataTypeService dataTypeService, ILogger logger, ValueEditorAttribute attribute) - : base(dataTypeService, attribute, logger) + internal PublishValuesMultipleValueEditor(bool publishIds, ILogger logger, ValueEditorAttribute attribute) + : base(attribute, logger) { _publishIds = publishIds; } public PublishValuesMultipleValueEditor(bool publishIds, ValueEditorAttribute attribute) - : this(publishIds, Current.Services.DataTypeService, Current.Logger, attribute) + : this(publishIds, Current.Logger, attribute) { } /// @@ -57,15 +57,10 @@ namespace Umbraco.Web.PropertyEditors return base.ConvertDbToString(propertyType, propertyValue, dataTypeService); } - var preValues = GetPreValues(propertyType); - if (preValues != null) - { - //get all pre-values matching our Ids - return string.Join(",", preValues.Where(x => selectedIds.Contains(x.Value.Id.ToInvariantString())).Select(x => x.Value.Value)); - } - - // bah, fallback to base - return base.ConvertDbToString(propertyType, propertyValue, dataTypeService); + // fixme I have no idea what I'm doing here + var configuration = dataTypeService.GetDataType(propertyType.DataTypeId).ConfigurationAs(); + var items = configuration.Items.Where(x => selectedIds.Contains(x.Id.ToInvariantString())).Select(x => x.Value); + return string.Join(",", items); } /// diff --git a/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs index 73bddcb29f..fd2b8d490e 100644 --- a/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/RelatedLinks2PropertyEditor.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.PropertyEditors internal IDictionary InternalPreValues; - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get => InternalPreValues; set => InternalPreValues = value; diff --git a/src/Umbraco.Web/PropertyEditors/RichTextConfiguration.cs b/src/Umbraco.Web/PropertyEditors/RichTextConfiguration.cs new file mode 100644 index 0000000000..420abe61cc --- /dev/null +++ b/src/Umbraco.Web/PropertyEditors/RichTextConfiguration.cs @@ -0,0 +1,16 @@ +using Umbraco.Core.PropertyEditors; + +namespace Umbraco.Web.PropertyEditors +{ + /// + /// Represents the configuration for the rich text value editor. + /// + public class RichTextConfiguration + { + [ConfigurationField("editor", "Editor", "views/propertyeditors/rte/rte.prevalues.html", HideLabel = true)] + public string Editor { get; set; } + + [ConfigurationField("hideLabel", "Hide Label", "boolean")] + public bool HideLabel { get; set; } + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/RichTextConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/RichTextConfigurationEditor.cs index 0701f2b624..4777b5ebb0 100644 --- a/src/Umbraco.Web/PropertyEditors/RichTextConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/RichTextConfigurationEditor.cs @@ -1,65 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Umbraco.Core.PropertyEditors; +using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { - //need to figure out how to use this... - internal class RichTextConfigurationEditor : ConfigurationEditor - { - public RichTextConfigurationEditor() - { - //SD: You can add pre-val fields here like you are doing, or you can add fields using attributes (http://issues.umbraco.org/issue/U4-2692), - // see below for examples. - - //use a custom editor too - Fields.Add(new ConfigurationField() - { - View = "views/propertyeditors/rte/rte.prevalues.html", - HideLabel = true, - Key = "editor" - }); - - Fields.Add(new ConfigurationField() - { - Name = "Hide Label", - View = "boolean", - Key = "hideLabel" - }); - } - - //SD: You can declare a field like this if you want to instead of in the ctor, there's some options here: - //#1 - the property name becomes the Key: - // - // [PreValueField("", "views/propertyeditors/rte/rte.prevalues.html", HideLabel = true)] - // public string Editor { get; set; } - - //#2 - You can specify a custom Key: - // - // [PreValueField("editor", "", "views/propertyeditors/rte/rte.prevalues.html", HideLabel = true)] - // public string Editor { get; set; } - - //#3 - If you require custom server side validation for your field then you have to specify a custom PreValueField type to use, - // this is why in this case I find it easier to use the ctor logic but thats just an opinion - // - Any value specified for this property attribute will override the values set in on the class instance of the field, this - // allows you to re-use class instances of fields if you want. - // - // [PreValueField(typeof(EditorPreValueField))] - // public string Editor { get; set; } - - // [PreValueField("", "views/propertyeditors/rte/rte.prevalues.html", HideLabel = true)] - // public class EditorPreValueField : PreValueField - // { - // public EditorPreValueField() - // { - // //add any required server validators for this field - // Validators.Add(new RegexValidator("^\\d*$")); - // //You could also set the field properties directly here if you wanted instead of the attribute - // } - // } - - } + /// + /// Represents the configuration editor for the rich text value editor. + /// + internal class RichTextConfigurationEditor : ConfigurationEditor + { } } diff --git a/src/Umbraco.Web/PropertyEditors/RichTextPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/RichTextPropertyEditor.cs index 2cf68af071..265572636f 100644 --- a/src/Umbraco.Web/PropertyEditors/RichTextPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/RichTextPropertyEditor.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Macros; @@ -36,22 +37,20 @@ namespace Umbraco.Web.PropertyEditors : base(attribute) { } - /// - /// override so that we can hide the label based on the pre-value - /// - /// - public override void ConfigureForDisplay(Core.Models.PreValueCollection preValues) + /// + public override object Configuration { - base.ConfigureForDisplay(preValues); - var asDictionary = preValues.FormatAsDictionary(); - if (asDictionary.ContainsKey("hideLabel")) + get => base.Configuration; + set { - var boolAttempt = asDictionary["hideLabel"].Value.TryConvertTo(); - if (boolAttempt.Success) - { - HideLabel = boolAttempt.Result; - } + if (value == null) + throw new ArgumentNullException(nameof(value)); + if (!(value is RichTextConfiguration configuration)) + throw new ArgumentException($"Expected a {typeof(RichTextConfiguration).Name} instance, but got {value.GetType().Name}.", nameof(value)); + HideLabel = configuration.HideLabel; + base.Configuration = value; } + } /// diff --git a/src/Umbraco.Web/PropertyEditors/TagConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/TagConfigurationEditor.cs index 586cafb07d..b8829f0f63 100644 --- a/src/Umbraco.Web/PropertyEditors/TagConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/TagConfigurationEditor.cs @@ -33,9 +33,9 @@ namespace Umbraco.Web.PropertyEditors }); } - public override Dictionary ToEditor(TagConfiguration defaultConfiguration, TagConfiguration configuration) + public override Dictionary ToEditor(TagConfiguration configuration) { - var dictionary = base.ToEditor(defaultConfiguration, configuration); + var dictionary = base.ToEditor(configuration); // the front-end editor expects the string value of the storage type dictionary["storageType"] = dictionary["storageType"].ToString(); diff --git a/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs index 8976292baa..c839ce2206 100644 --- a/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.PropertyEditors /// /// Override to supply the default group /// - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get { return _defaultPreVals; } set { _defaultPreVals = value; } diff --git a/src/Umbraco.Web/PropertyEditors/TextOnlyValueEditor.cs b/src/Umbraco.Web/PropertyEditors/TextOnlyValueEditor.cs index 7951906b3b..8616fbcf97 100644 --- a/src/Umbraco.Web/PropertyEditors/TextOnlyValueEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/TextOnlyValueEditor.cs @@ -32,7 +32,7 @@ namespace Umbraco.Web.PropertyEditors switch (GetDatabaseType()) { case ValueStorageType.Ntext: - case ValueStorageType.NVarChar: + case ValueStorageType.Nvarchar: return property.GetValue().ToString(); case ValueStorageType.Integer: case ValueStorageType.Decimal: diff --git a/src/Umbraco.Web/PropertyEditors/TextboxConfiguration.cs b/src/Umbraco.Web/PropertyEditors/TextboxConfiguration.cs index f5c5f24875..121fa23b7b 100644 --- a/src/Umbraco.Web/PropertyEditors/TextboxConfiguration.cs +++ b/src/Umbraco.Web/PropertyEditors/TextboxConfiguration.cs @@ -8,6 +8,6 @@ namespace Umbraco.Web.PropertyEditors public class TextboxConfiguration { [ConfigurationField("maxChars", "Maximum allowed characters", "number", Description = "If empty, no character limit")] - public int MaxChars { get; set; } + public int? MaxChars { get; set; } } } \ No newline at end of file diff --git a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs index ba01276f82..f49800f9d5 100644 --- a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs +++ b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs @@ -2,14 +2,11 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; -using System.Linq; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.Services; using Umbraco.Core.Configuration; -using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; -using umbraco; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Web.Composing; @@ -19,26 +16,19 @@ namespace Umbraco.Web.PropertyEditors { public IEnumerable Validate(object value, string valueType, object dataTypeConfiguration) { + if (!(value is JObject jobject) || jobject["selectedFiles"] == null) yield break; + + var fileNames = jobject["selectedFiles"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - //now check the file type - var asJson = value as JObject; - if (asJson == null) yield break; - if (asJson["selectedFiles"] == null) yield break; - var fileNames = asJson["selectedFiles"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var fileName in fileNames) { if (ValidateFileExtension(fileName) == false) { - yield return new ValidationResult(Current.Services.TextService.Localize("errors/dissallowedMediaType"), - new[] - { - //we only store a single value for this editor so the 'member' or 'field' - // we'll associate this error with will simply be called 'value' - "value" - }); + //we only store a single value for this editor so the 'member' or 'field' + // we'll associate this error with will simply be called 'value' + yield return new ValidationResult(Current.Services.TextService.Localize("errors/dissallowedMediaType"), new[] { "value" }); } } - } internal static bool ValidateFileExtension(string fileName) @@ -47,6 +37,5 @@ namespace Umbraco.Web.PropertyEditors var extension = Path.GetExtension(fileName).TrimStart("."); return UmbracoConfig.For.UmbracoSettings().Content.IsFileAllowedForUpload(extension); } - } } diff --git a/src/Umbraco.Web/PropertyEditors/UserPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/UserPickerPropertyEditor.cs index cb4bc211a1..2ec6e6d226 100644 --- a/src/Umbraco.Web/PropertyEditors/UserPickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/UserPickerPropertyEditor.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.PropertyEditors }; } - public override IDictionary DefaultPreValues + public override IDictionary DefaultConfiguration { get { return _defaultPreValues; } set { _defaultPreValues = value; } diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs index 078625547b..7cd631d663 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs @@ -34,7 +34,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters /// public override Type GetPropertyValueType(PublishedPropertyType propertyType) { - var contentTypes = propertyType.DataType.ConfigurationAs().ContentTypes; + var contentTypes = propertyType.DataType.ConfigurationAs().ContentTypes; return contentTypes.Length > 1 ? typeof (IEnumerable) : typeof (IEnumerable<>).MakeGenericType(ModelType.For(contentTypes[0].Alias)); @@ -66,7 +66,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters var contentTypes = configuration.ContentTypes; var elements = contentTypes.Length > 1 ? new List() - : PublishedModelFactory.CreateModelList(contentTypes[0]); + : PublishedModelFactory.CreateModelList(contentTypes[0].Alias); foreach (var sourceObject in objects) { diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs index 06fc771161..52d6c7d53a 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs @@ -33,7 +33,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters /// public override Type GetPropertyValueType(PublishedPropertyType propertyType) { - var contentTypes = propertyType.DataType.ConfigurationAs().ContentTypes; + var contentTypes = propertyType.DataType.ConfigurationAs().ContentTypes; return contentTypes.Length > 1 ? typeof(IPublishedElement) : ModelType.For(contentTypes[0].Alias); diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentValueConverterBase.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentValueConverterBase.cs index ba9d550dd0..7e9b1dfe88 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentValueConverterBase.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentValueConverterBase.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters if (!IsNested(publishedProperty)) return false; - var config = publishedProperty.DataType.ConfigurationAs(); + var config = publishedProperty.DataType.ConfigurationAs(); return config.MinItems == 1 && config.MaxItems == 1; } diff --git a/src/Umbraco.Web/PropertyEditors/ValueListConfigurationEditor.cs b/src/Umbraco.Web/PropertyEditors/ValueListConfigurationEditor.cs index b20a08436a..3ffbaeaee9 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueListConfigurationEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueListConfigurationEditor.cs @@ -47,7 +47,7 @@ namespace Umbraco.Web.PropertyEditors // the sort order that comes back makes no sense /// - public override Dictionary ToEditor(ValueListConfiguration defaultConfiguration, ValueListConfiguration configuration) + public override Dictionary ToEditor(ValueListConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs index 97f8ee4634..558580d7c0 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedContent.cs @@ -187,7 +187,7 @@ namespace Umbraco.Web.PublishedCache.NuCache case PublishedItemType.Media: return GetMediaById(IsPreviewing, _contentNode.ParentContentId); default: - throw new Exception("oops"); + throw new Exception($"Panic: unsupported item type \"{_contentNode.ContentType.ItemType}\"."); } } } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index ce976fd000..eb282ccf50 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -275,6 +275,7 @@ + diff --git a/src/Umbraco.Web/umbraco.presentation/library.cs b/src/Umbraco.Web/umbraco.presentation/library.cs index af2a5359dc..0e24f2bbd8 100644 --- a/src/Umbraco.Web/umbraco.presentation/library.cs +++ b/src/Umbraco.Web/umbraco.presentation/library.cs @@ -1020,60 +1020,6 @@ namespace umbraco return Text.LastIndexOf(Value); } - /// - /// Gets the prevalues from a umbraco DataType with the specified data type id. - /// - /// The data type id. - /// Returns the prevalues as a XPathNodeIterator in the format: - /// - /// [value] - /// - /// - public static XPathNodeIterator GetPreValues(int DataTypeId) - { - var xd = new XmlDocument(); - xd.LoadXml(""); - - using (var scope = Current.ScopeProvider.CreateScope()) - { - foreach (var dr in scope.Database.Query( - "Select id, [value] from cmsDataTypeprevalues where DataTypeNodeId = @dataTypeId order by sortorder", - new { dataTypeId = DataTypeId })) - { - XmlNode n = XmlHelper.AddTextNode(xd, "preValue", dr.value); - n.Attributes.Append(XmlHelper.AddAttribute(xd, "id", dr.id.ToString())); - xd.DocumentElement.AppendChild(n); - } - scope.Complete(); - } - - var xp = xd.CreateNavigator(); - return xp.Select("/preValues"); - } - - /// - /// Gets the umbraco data type prevalue with the specified Id as string. - /// - /// The id. - /// Returns the prevalue as a string - public static string GetPreValueAsString(int id) - { - using (var scope = Current.ScopeProvider.CreateScope()) - { - string ret; - try - { - ret = scope.Database.ExecuteScalar("select [value] from cmsDataTypePreValues where id = @id", new { id }); - } - catch - { - ret = string.Empty; - } - scope.Complete(); - return ret; - } - } - /// /// Gets the dictionary item with the specified key. ///