From e30d8f79ef342bf67127fb8cf64517622d8f4116 Mon Sep 17 00:00:00 2001 From: Stephan Date: Mon, 15 Jan 2018 17:32:45 +0100 Subject: [PATCH] DataType refactoring --- .../Migrations/Install/DatabaseDataCreator.cs | 93 +++--- src/Umbraco.Core/Migrations/MigrationBase.cs | 2 +- .../Migrations/MigrationBase_Extra.cs | 60 ++++ .../Migrations/Upgrade/UmbracoPlan.cs | 8 +- .../Upgrade/V_8_0_0/RefactorDataType.cs | 94 ++++++ .../Upgrade/V_8_0_0/VariantsMigration.cs | 46 --- src/Umbraco.Core/Models/DataType.cs | 60 +++- .../DataTypeConfigurationSource.cs | 10 +- .../Persistence/Constants-DatabaseSchema.cs | 3 +- .../Persistence/Dtos/DataTypeDto.cs | 15 +- .../Persistence/Dtos/DataTypePreValueDto.cs | 2 +- .../Persistence/Factories/DataTypeFactory.cs | 107 +++--- .../Repositories/IDataTypeRepository.cs | 6 - .../Implement/ContentTypeRepositoryBase.cs | 10 +- .../Implement/DataTypeRepository.cs | 304 +----------------- .../Implement/EntityRepository.cs | 4 +- .../Implement/MemberRepository.cs | 2 +- .../Implement/MemberTypeRepository.cs | 4 +- .../PropertyEditors/DecimalValidator.cs | 22 +- .../DelimitedManifestValueValidator.cs | 15 +- .../PropertyEditors/EmailValidator.cs | 8 +- .../PropertyEditors/IPropertyValidator.cs | 23 +- .../PropertyEditors/IntegerValidator.cs | 6 +- .../ManifestPropertyValidator.cs | 8 +- .../PropertyEditors/ManifestValueValidator.cs | 37 +-- .../PropertyEditors/PreValueEditor.cs | 70 ++-- .../PropertyEditors/PropertyEditor.cs | 23 +- .../PropertyEditors/RegexValidator.cs | 13 +- .../RequiredManifestValueValidator.cs | 2 +- .../ValueConverters/SliderValueConverter.cs | 4 + .../Services/EntityXmlSerializer.cs | 4 +- src/Umbraco.Core/Services/IDataTypeService.cs | 62 +--- .../Services/Implement/DataTypeService.cs | 153 +-------- .../Services/Implement/EntityService.cs | 2 +- .../Services/Implement/PackagingService.cs | 10 +- src/Umbraco.Core/Umbraco.Core.csproj | 2 + .../Mapping/ContentTypeModelMappingTests.cs | 22 +- .../Mapping/ContentWebModelMappingTests.cs | 2 +- .../ContentTypeRepositorySqlClausesTest.cs | 4 +- .../Querying/ContentTypeSqlMappingTests.cs | 2 +- ...aTypeDefinitionRepositorySqlClausesTest.cs | 2 +- .../Repositories/MemberRepositoryTest.cs | 4 +- .../Services/CachedDataTypeServiceTests.cs | 4 +- .../Services/ContentTypeServiceTests.cs | 2 +- .../Services/DataTypeServiceTests.cs | 16 +- .../Editors/ContentTypeController.cs | 2 +- src/Umbraco.Web/Editors/DataTypeController.cs | 18 +- .../Editors/DataTypeValidateAttribute.cs | 2 +- .../Editors/PackageInstallController.cs | 2 +- .../EnsureListViewDataTypeIsCreated.cs | 6 +- .../Mapping/ContentPropertyDtoConverter.cs | 2 +- .../Mapping/ContentTypeMapperProfile.cs | 6 +- .../Mapping/TabsAndPropertiesResolver.cs | 4 +- .../PropertyEditors/DateTimeValidator.cs | 2 +- .../NestedContentPropertyEditor.cs | 31 +- .../PropertyEditors/SliderPropertyEditor.cs | 1 - .../UploadFileTypeValidator.cs | 2 +- .../MediaPickerLegacyValueConverter.cs | 2 +- .../NestedContentManyValueConverter.cs | 4 +- .../NestedContentSingleValueConverter.cs | 2 +- .../NestedContentValueConverterBase.cs | 2 +- .../PackageInstance/InstalledPackage.cs | 2 +- 62 files changed, 516 insertions(+), 926 deletions(-) create mode 100644 src/Umbraco.Core/Migrations/MigrationBase_Extra.cs create mode 100644 src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs diff --git a/src/Umbraco.Core/Migrations/Install/DatabaseDataCreator.cs b/src/Umbraco.Core/Migrations/Install/DatabaseDataCreator.cs index f8042e7220..dc1da2b00e 100644 --- a/src/Umbraco.Core/Migrations/Install/DatabaseDataCreator.cs +++ b/src/Umbraco.Core/Migrations/Install/DatabaseDataCreator.cs @@ -66,9 +66,6 @@ namespace Umbraco.Core.Migrations.Install if (tableName.Equals(Constants.DatabaseSchema.Tables.DataType)) CreateDataTypeData(); - if (tableName.Equals(Constants.DatabaseSchema.Tables.DataTypePreValue)) - CreateDataTypePreValueData(); - if (tableName.Equals(Constants.DatabaseSchema.Tables.RelationType)) CreateRelationTypeData(); @@ -223,64 +220,48 @@ namespace Umbraco.Core.Migrations.Install private void CreateDataTypeData() { + //layouts for the list view + const string cardLayout = "{\"name\": \"Grid\",\"path\": \"views/propertyeditors/listview/layouts/grid/grid.html\", \"icon\": \"icon-thumbnails-small\", \"isSystem\": 1, \"selected\": true}"; + const string listLayout = "{\"name\": \"List\",\"path\": \"views/propertyeditors/listview/layouts/list/list.html\",\"icon\": \"icon-list\", \"isSystem\": 1,\"selected\": true}"; + const string layouts = "[" + cardLayout + "," + listLayout + "]"; + //TODO Check which of the DataTypeIds below doesn't exist in umbracoNode, which results in a foreign key constraint errors. - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 1, DataTypeId = -49, EditorAlias = Constants.PropertyEditors.TrueFalseAlias, DbType = "Integer" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 2, DataTypeId = -51, EditorAlias = Constants.PropertyEditors.IntegerAlias, DbType = "Integer" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 3, DataTypeId = -87, EditorAlias = Constants.PropertyEditors.TinyMCEAlias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 4, DataTypeId = -88, EditorAlias = Constants.PropertyEditors.TextboxAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 5, DataTypeId = -89, EditorAlias = Constants.PropertyEditors.TextboxMultipleAlias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 6, DataTypeId = -90, EditorAlias = Constants.PropertyEditors.UploadFieldAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 7, DataTypeId = -92, EditorAlias = Constants.PropertyEditors.NoEditAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 8, DataTypeId = -36, EditorAlias = Constants.PropertyEditors.DateTimeAlias, DbType = "Date" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 9, DataTypeId = -37, EditorAlias = Constants.PropertyEditors.ColorPickerAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 11, DataTypeId = -39, EditorAlias = Constants.PropertyEditors.DropDownListMultipleAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 12, DataTypeId = -40, EditorAlias = Constants.PropertyEditors.RadioButtonListAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 13, DataTypeId = -41, EditorAlias = Constants.PropertyEditors.DateAlias, DbType = "Date" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 14, DataTypeId = -42, EditorAlias = Constants.PropertyEditors.DropDownListAlias, DbType = "Integer" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 15, DataTypeId = -43, EditorAlias = Constants.PropertyEditors.CheckBoxListAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 22, DataTypeId = 1041, EditorAlias = Constants.PropertyEditors.TagsAlias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 24, DataTypeId = 1043, EditorAlias = Constants.PropertyEditors.ImageCropperAlias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -26, DataTypeId = Constants.DataTypes.DefaultContentListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -27, DataTypeId = Constants.DataTypes.DefaultMediaListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -28, DataTypeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -49, EditorAlias = Constants.PropertyEditors.TrueFalseAlias, DbType = "Integer" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -51, EditorAlias = Constants.PropertyEditors.IntegerAlias, DbType = "Integer" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -87, EditorAlias = Constants.PropertyEditors.TinyMCEAlias, DbType = "Ntext", + Configuration = "{\"value\":\",code,undo,redo,cut,copy,mcepasteword,stylepicker,bold,italic,bullist,numlist,outdent,indent,mcelink,unlink,mceinsertanchor,mceimage,umbracomacro,mceinserttable,umbracoembed,mcecharmap,|1|1,2,3,|0|500,400|1049,|true|\"}" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -88, EditorAlias = Constants.PropertyEditors.TextboxAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -89, EditorAlias = Constants.PropertyEditors.TextboxMultipleAlias, DbType = "Ntext" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -90, EditorAlias = Constants.PropertyEditors.UploadFieldAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -92, EditorAlias = Constants.PropertyEditors.NoEditAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -36, EditorAlias = Constants.PropertyEditors.DateTimeAlias, DbType = "Date" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -37, EditorAlias = Constants.PropertyEditors.ColorPickerAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -39, EditorAlias = Constants.PropertyEditors.DropDownListMultipleAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -40, EditorAlias = Constants.PropertyEditors.RadioButtonListAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -41, EditorAlias = Constants.PropertyEditors.DateAlias, DbType = "Date" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -42, EditorAlias = Constants.PropertyEditors.DropDownListAlias, DbType = "Integer" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = -43, EditorAlias = Constants.PropertyEditors.CheckBoxListAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1041, EditorAlias = Constants.PropertyEditors.TagsAlias, DbType = "Ntext", + Configuration = "{\"group\":\"default\"}" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1043, EditorAlias = Constants.PropertyEditors.ImageCropperAlias, DbType = "Ntext" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultContentListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultMediaListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar", + Configuration = "{\"pageSize\":100, \"orderBy\":\"updateDate\", \"orderDirection\":\"desc\", \"layouts\":" + layouts + ", \"includeProperties\":[{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1},{\"alias\":\"owner\",\"header\":\"Updated by\",\"isSystem\":1}]}" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar", + Configuration = "{\"pageSize\":10, \"orderBy\":\"username\", \"orderDirection\":\"asc\", \"includeProperties\":[{\"alias\":\"username\",\"isSystem\":1},{\"alias\":\"email\",\"isSystem\":1},{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1}]}" }); //New UDI pickers with newer Ids - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 26, DataTypeId = 1046, EditorAlias = Constants.PropertyEditors.ContentPicker2Alias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 27, DataTypeId = 1047, EditorAlias = Constants.PropertyEditors.MemberPicker2Alias, DbType = "Nvarchar" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 28, DataTypeId = 1048, EditorAlias = Constants.PropertyEditors.MediaPicker2Alias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 29, DataTypeId = 1049, EditorAlias = Constants.PropertyEditors.MediaPicker2Alias, DbType = "Ntext" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 30, DataTypeId = 1050, EditorAlias = Constants.PropertyEditors.RelatedLinks2Alias, DbType = "Ntext" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1046, EditorAlias = Constants.PropertyEditors.ContentPicker2Alias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1047, EditorAlias = Constants.PropertyEditors.MemberPicker2Alias, DbType = "Nvarchar" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1048, EditorAlias = Constants.PropertyEditors.MediaPicker2Alias, DbType = "Ntext" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1049, EditorAlias = Constants.PropertyEditors.MediaPicker2Alias, DbType = "Ntext", + Configuration = "{\"multiPicker\":1}" }); + _database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { NodeId = 1050, EditorAlias = Constants.PropertyEditors.RelatedLinks2Alias, DbType = "Ntext" }); //TODO: We're not creating these for 7.0 - //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 19, DataTypeId = 1038, PropertyEditorAlias = Constants.PropertyEditors.MarkdownEditorAlias, DbType = "Ntext" }); - //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 20, DataTypeId = 1039, PropertyEditorAlias = Constants.PropertyEditors.UltimatePickerAlias, DbType = "Ntext" }); - //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 23, DataTypeId = 1042, PropertyEditorAlias = Constants.PropertyEditors.MacroContainerAlias, DbType = "Ntext" }); - } - - private void CreateDataTypePreValueData() - { - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = 3, Alias = "", SortOrder = 0, DataTypeNodeId = -87, Value = ",code,undo,redo,cut,copy,mcepasteword,stylepicker,bold,italic,bullist,numlist,outdent,indent,mcelink,unlink,mceinsertanchor,mceimage,umbracomacro,mceinserttable,umbracoembed,mcecharmap,|1|1,2,3,|0|500,400|1049,|true|" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = 4, Alias = "group", SortOrder = 0, DataTypeNodeId = 1041, Value = "default" }); - - //defaults for the member list - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -1, Alias = "pageSize", SortOrder = 1, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "10" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -2, Alias = "orderBy", SortOrder = 2, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "username" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -3, Alias = "orderDirection", SortOrder = 3, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "asc" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -4, Alias = "includeProperties", SortOrder = 4, DataTypeNodeId = Constants.DataTypes.DefaultMembersListView, Value = "[{\"alias\":\"username\",\"isSystem\":1},{\"alias\":\"email\",\"isSystem\":1},{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1}]" }); - - //layouts for the list view - var cardLayout = "{\"name\": \"Grid\",\"path\": \"views/propertyeditors/listview/layouts/grid/grid.html\", \"icon\": \"icon-thumbnails-small\", \"isSystem\": 1, \"selected\": true}"; - var listLayout = "{\"name\": \"List\",\"path\": \"views/propertyeditors/listview/layouts/list/list.html\",\"icon\": \"icon-list\", \"isSystem\": 1,\"selected\": true}"; - - //defaults for the media list - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -5, Alias = "pageSize", SortOrder = 1, DataTypeNodeId = Constants.DataTypes.DefaultMediaListView, Value = "100" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -6, Alias = "orderBy", SortOrder = 2, DataTypeNodeId = Constants.DataTypes.DefaultMediaListView, Value = "updateDate" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -7, Alias = "orderDirection", SortOrder = 3, DataTypeNodeId = Constants.DataTypes.DefaultMediaListView, Value = "desc" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -8, Alias = "layouts", SortOrder = 4, DataTypeNodeId = Constants.DataTypes.DefaultMediaListView, Value = "[" + cardLayout + "," + listLayout + "]" }); - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = -9, Alias = "includeProperties", SortOrder = 5, DataTypeNodeId = Constants.DataTypes.DefaultMediaListView, Value = "[{\"alias\":\"updateDate\",\"header\":\"Last edited\",\"isSystem\":1},{\"alias\":\"owner\",\"header\":\"Updated by\",\"isSystem\":1}]" }); - - //default's for MultipleMediaPickerAlias picker - _database.Insert(Constants.DatabaseSchema.Tables.DataTypePreValue, "id", false, new DataTypePreValueDto { Id = 6, Alias = "multiPicker", SortOrder = 0, DataTypeNodeId = 1049, Value = "1" }); + //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { DataTypeId = 1038, PropertyEditorAlias = Constants.PropertyEditors.MarkdownEditorAlias, DbType = "Ntext" }); + //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { DataTypeId = 1039, PropertyEditorAlias = Constants.PropertyEditors.UltimatePickerAlias, DbType = "Ntext" }); + //_database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { DataTypeId = 1042, PropertyEditorAlias = Constants.PropertyEditors.MacroContainerAlias, DbType = "Ntext" }); } private void CreateRelationTypeData() diff --git a/src/Umbraco.Core/Migrations/MigrationBase.cs b/src/Umbraco.Core/Migrations/MigrationBase.cs index d2420fdd33..9fbee0ed92 100644 --- a/src/Umbraco.Core/Migrations/MigrationBase.cs +++ b/src/Umbraco.Core/Migrations/MigrationBase.cs @@ -16,7 +16,7 @@ namespace Umbraco.Core.Migrations /// /// Provides a base class to all migrations. /// - public abstract class MigrationBase : IMigration + public abstract partial class MigrationBase : IMigration { /// /// Initializes a new instance of the class. diff --git a/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs b/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs new file mode 100644 index 0000000000..9e0ca99b5c --- /dev/null +++ b/src/Umbraco.Core/Migrations/MigrationBase_Extra.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Linq; +using Umbraco.Core.Persistence.DatabaseModelDefinitions; + +namespace Umbraco.Core.Migrations +{ + /// + /// Provides a base class to all migrations. + /// + public abstract partial class MigrationBase + { + // provides extra methods for migrations + + protected void AddColumn(string tableName, string columnName) + { + AddColumn(tableName, columnName, out var sqls); + foreach (var sql in sqls) Database.Execute(sql); + } + + protected void AddColumn(string tableName, string columnName, out IEnumerable sqls) + { + //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, SqlSyntax.GetQuotedTableName(tableName), out sqls); + Database.Execute(string.Format(SqlSyntax.AddColumn, SqlSyntax.GetQuotedTableName(tableName), createSql)); + } + + protected void ReplaceColumn(string tableName, string currentName, string newName) + { + AddColumn(tableName, newName, out var sqls); + Database.Execute($"UPDATE {SqlSyntax.GetQuotedTableName(tableName)} SET {SqlSyntax.GetQuotedColumnName(newName)}={SqlSyntax.GetQuotedColumnName(currentName)}"); + foreach (var sql in sqls) Database.Execute(sql); + Delete.Column(currentName).FromTable(tableName).Do(); + } + + protected bool TableExists(string tableName) + { + var tables = SqlSyntax.GetTablesInSchema(Context.Database); + return tables.Any(x => x.InvariantEquals(tableName)); + } + + protected bool ColumnExists(string tableName, string columnName) + { + // that's ok even on MySql + var columns = SqlSyntax.GetColumnsInSchema(Context.Database).Distinct().ToArray(); + return columns.Any(x => x.TableName.InvariantEquals(tableName) && x.ColumnName.InvariantEquals(columnName)); + } + + protected string ColumnType(string tableName, string columnName) + { + // that's ok even on MySql + var columns = SqlSyntax.GetColumnsInSchema(Context.Database).Distinct().ToArray(); + var column = columns.FirstOrDefault(x => x.TableName.InvariantEquals(tableName) && x.ColumnName.InvariantEquals(columnName)); + return column?.DataType; + } + } +} diff --git a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs index 80fec80937..8fdd00a203 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/UmbracoPlan.cs @@ -67,7 +67,7 @@ namespace Umbraco.Core.Migrations.Upgrade // // when installing, the source state is empty, and the target state should be the final state. - Add(string.Empty, "{E3388F73-89FA-45FE-A539-C7FACC8D63DD}"); + Add(string.Empty, "{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}"); // UPGRADE FROM 7 // @@ -83,7 +83,8 @@ 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("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}") + .Chain("{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}"); // 7.8.1 = same as 7.8.0 From("{init-7.8.1}") @@ -92,7 +93,7 @@ namespace Umbraco.Core.Migrations.Upgrade // 7.9.0 = requires its own chain From("{init-7.9.0}") // chain... - .Chain("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}"); + .Chain("{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}"); // UPGRADE 8 // @@ -151,6 +152,7 @@ namespace Umbraco.Core.Migrations.Upgrade // 8.0.0 Chain("{6550C7E8-77B7-4DE3-9B58-E31C81CB9504}"); Chain("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}"); + Chain("{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}"); } } } 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 new file mode 100644 index 0000000000..aaa4929ec6 --- /dev/null +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/RefactorDataType.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using NPoco; +using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.DatabaseModelDefinitions; +using Umbraco.Core.Persistence.Dtos; + +namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0 +{ + public class RefactorDataType : MigrationBase + { + public RefactorDataType(IMigrationContext context) + : base(context) + { } + + public override void Migrate() + { + // drop all keys and indexes + Delete.KeysAndIndexes("cmsDataType").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(); + + // recreate all keys and indexes + Create.KeysAndIndexes().Do(); + + var sql = Sql() + .Select() + .AndSelect() + .From() + .InnerJoin().On((left, right) => left.NodeId == right.NodeId) + .OrderBy(x => x.NodeId) + .AndBy(x => x.SortOrder); + + var dtos = Database.Fetch(sql).GroupBy(x => x.NodeId); + + foreach (var group in dtos) + { + var dataType = Database.Fetch(Sql() + .Select() + .From() + .Where(x => x.NodeId == group.Key)).First(); + + var aliases = group.Select(x => x.Alias).Distinct().ToArray(); + if (aliases.Length == 1 && string.IsNullOrWhiteSpace(aliases[0])) + { + // array-based prevalues + var values = new Dictionary { ["values"] = group.OrderBy(x => x.SortOrder).Select(x => x.Value).ToArray() }; + dataType.Configuration = JsonConvert.SerializeObject(values); + } + else + { + // fixme deal with null or empty aliases + // fixme deal with duplicate aliases + // in these cases, fallback to array? + + // dictionary-base prevalues + var values = group.ToDictionary(x => x.Alias, x => x.Value); + dataType.Configuration = JsonConvert.SerializeObject(values); + } + + Database.Update(dataType); + } + + // drop preValues table + Delete.Table("cmsDataTypePreValues"); + } + + [TableName("cmsDataTypePreValues")] + [ExplicitColumns] + public class PreValueDto + { + [Column("datatypeNodeId")] + public int NodeId { get; set; } + + [Column("alias")] + public string Alias { get; set; } + + [Column("sortorder")] + public int SortOrder { get; set; } + + [Column("value")] + public string Value { get; set; } + } + } +} diff --git a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/VariantsMigration.cs b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/VariantsMigration.cs index 7d517bfad8..e8b06c4a31 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/VariantsMigration.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/VariantsMigration.cs @@ -329,51 +329,5 @@ WHERE v1.propertyTypeId=v2.propertyTypeId AND v1.languageId=v2.languageId AND v1 public const string TaskType = "cmsTaskType"; // ReSharper restore UnusedMember.Local } - - private void AddColumn(string tableName, string columnName) - { - AddColumn(tableName, columnName, out var sqls); - foreach (var sql in sqls) Database.Execute(sql); - } - - private void AddColumn(string tableName, string columnName, out IEnumerable sqls) - { - //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, SqlSyntax.GetQuotedTableName(tableName), out sqls); - Database.Execute(string.Format(SqlSyntax.AddColumn, SqlSyntax.GetQuotedTableName(tableName), createSql)); - } - - private void ReplaceColumn(string tableName, string currentName, string newName) - { - AddColumn(tableName, newName, out var sqls); - Database.Execute($"UPDATE {SqlSyntax.GetQuotedTableName(tableName)} SET {SqlSyntax.GetQuotedColumnName(newName)}={SqlSyntax.GetQuotedColumnName(currentName)}"); - foreach (var sql in sqls) Database.Execute(sql); - Delete.Column(currentName).FromTable(tableName).Do(); - } - - private bool TableExists(string tableName) - { - var tables = SqlSyntax.GetTablesInSchema(Context.Database); - return tables.Any(x => x.InvariantEquals(tableName)); - } - - private bool ColumnExists(string tableName, string columnName) - { - // that's ok even on MySql - var columns = SqlSyntax.GetColumnsInSchema(Context.Database).Distinct().ToArray(); - return columns.Any(x => x.TableName.InvariantEquals(tableName) && x.ColumnName.InvariantEquals(columnName)); - } - - private string ColumnType(string tableName, string columnName) - { - // that's ok even on MySql - var columns = SqlSyntax.GetColumnsInSchema(Context.Database).Distinct().ToArray(); - var column = columns.FirstOrDefault(x => x.TableName.InvariantEquals(tableName) && x.ColumnName.InvariantEquals(columnName)); - return column?.DataType; - } } } diff --git a/src/Umbraco.Core/Models/DataType.cs b/src/Umbraco.Core/Models/DataType.cs index 3914c74e3d..4601e1723e 100644 --- a/src/Umbraco.Core/Models/DataType.cs +++ b/src/Umbraco.Core/Models/DataType.cs @@ -1,9 +1,8 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Reflection; using System.Runtime.Serialization; using Umbraco.Core.Models.Entities; +using Umbraco.Core.PropertyEditors; namespace Umbraco.Core.Models { @@ -14,10 +13,14 @@ namespace Umbraco.Core.Models [DataContract(IsReference = true)] public class DataType : TreeEntityBase, IDataType { - private static readonly Lazy Ps = new Lazy(); + private static PropertySelectors _selectors; - private string _propertyEditorAlias; + private string _editorAlias; private DataTypeDatabaseType _databaseType; + private object _configuration; + private bool _hasConfiguration; + private string _configurationJson; + private PropertyEditor _editor; /// /// Initializes a new instance of the class. @@ -25,7 +28,7 @@ namespace Umbraco.Core.Models public DataType(int parentId, string propertyEditorAlias) { ParentId = parentId; - _propertyEditorAlias = propertyEditorAlias; + _editorAlias = propertyEditorAlias; } /// @@ -34,22 +37,25 @@ namespace Umbraco.Core.Models public DataType(string propertyEditorAlias) { ParentId = -1; - _propertyEditorAlias = propertyEditorAlias; + _editorAlias = propertyEditorAlias; } + private static PropertySelectors Selectors => _selectors ?? (_selectors = new PropertySelectors()); + // ReSharper disable once ClassNeverInstantiated.Local private class PropertySelectors { - public readonly PropertyInfo PropertyEditorAliasSelector = ExpressionHelper.GetPropertyInfo(x => x.EditorAlias); - public readonly PropertyInfo DatabaseTypeSelector = ExpressionHelper.GetPropertyInfo(x => x.DatabaseType); + public readonly PropertyInfo EditorAlias = ExpressionHelper.GetPropertyInfo(x => x.EditorAlias); + public readonly PropertyInfo DatabaseType = ExpressionHelper.GetPropertyInfo(x => x.DatabaseType); + public readonly PropertyInfo Configuration = ExpressionHelper.GetPropertyInfo(x => x.Configuration); } /// [DataMember] public string EditorAlias { - get => _propertyEditorAlias; - set => SetPropertyValueAndDetectChanges(value, ref _propertyEditorAlias, Ps.Value.PropertyEditorAliasSelector); + get => _editorAlias; + set => SetPropertyValueAndDetectChanges(value, ref _editorAlias, Selectors.EditorAlias); } /// @@ -57,11 +63,39 @@ namespace Umbraco.Core.Models public DataTypeDatabaseType DatabaseType { get => _databaseType; - set => SetPropertyValueAndDetectChanges(value, ref _databaseType, Ps.Value.DatabaseTypeSelector); + set => SetPropertyValueAndDetectChanges(value, ref _databaseType, Selectors.DatabaseType); } - // fixme - implement that one !! + /// [DataMember] - public object Configuration { get; set; } + public object Configuration + { + get + { + if (_hasConfiguration) return _configuration; + + _configuration = _editor.DeserializeConfiguration(_configurationJson); + _hasConfiguration = true; + _configurationJson = null; + return _configuration; + } + set + { + // fixme detect changes? if it's the same object? + SetPropertyValueAndDetectChanges(value, ref _configuration, Selectors.Configuration); + _hasConfiguration = true; + _configurationJson = null; + } + } + + /// // fixme on interface!? + public void SetConfiguration(string configurationJson, PropertyEditor editor) + { + _hasConfiguration = false; + _configuration = null; + _configurationJson = configurationJson; + _editor = editor; + OnPropertyChanged(Selectors.Configuration); + } } } diff --git a/src/Umbraco.Core/Models/PublishedContent/DataTypeConfigurationSource.cs b/src/Umbraco.Core/Models/PublishedContent/DataTypeConfigurationSource.cs index 45936de1bf..15d24fe76b 100644 --- a/src/Umbraco.Core/Models/PublishedContent/DataTypeConfigurationSource.cs +++ b/src/Umbraco.Core/Models/PublishedContent/DataTypeConfigurationSource.cs @@ -40,9 +40,13 @@ namespace Umbraco.Core.Models.PublishedContent // fixme - we need a more efficient dataTypeService way of getting these // fixme - would be nice not to pass editorAlias but annoying for tests? //var datatype = _dataTypeService.GetDataTypeDefinitionById(id); - var collection = _dataTypeService.GetPreValuesCollectionByDataTypeId(id); - var editor = _propertyEditors[editorAlias /*datatype.PropertyEditorAlias*/]; - return editor.MapDataTypeConfiguration(collection); + //var collection = _dataTypeService.GetPreValuesCollectionByDataTypeId(id); + var dataType = _dataTypeService.GetDataType(id); + return dataType.Configuration; + + // fixme - mapping done in dataTypeService? or should it be on-demand in DataType? + //var editor = _propertyEditors[editorAlias /*datatype.PropertyEditorAlias*/]; + //return editor.MapDataTypeConfiguration(dataType.Configuration); } } } diff --git a/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs b/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs index 1b308a0ca1..43438bfcf1 100644 --- a/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs +++ b/src/Umbraco.Core/Persistence/Constants-DatabaseSchema.cs @@ -21,8 +21,7 @@ namespace Umbraco.Core public const string ContentChildType = /*TableNamePrefix*/ "cms" + "ContentTypeAllowedContentType"; public const string DocumentType = /*TableNamePrefix*/ "cms" + "DocumentType"; // fixme dbfixmust rename corresponding DTO public const string ElementTypeTree = /*TableNamePrefix*/ "cms" + "ContentType2ContentType"; // fixme dbfixwhy can't we just use uNode for this? - public const string DataType = /*TableNamePrefix*/ "cms" + "DataType"; - public const string DataTypePreValue = /*TableNamePrefix*/ "cms" + "DataTypePreValues"; // fixme dbfixkill merge with uDataType + public const string DataType = TableNamePrefix + "DataType"; public const string Template = /*TableNamePrefix*/ "cms" + "Template"; public const string Content = TableNamePrefix + "Content"; diff --git a/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs b/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs index f9c94a8125..be86f2fbf8 100644 --- a/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/DataTypeDto.cs @@ -4,26 +4,25 @@ using Umbraco.Core.Persistence.DatabaseAnnotations; namespace Umbraco.Core.Persistence.Dtos { [TableName(Constants.DatabaseSchema.Tables.DataType)] - [PrimaryKey("pk")] + [PrimaryKey("nodeId", AutoIncrement = false)] [ExplicitColumns] internal class DataTypeDto { - [Column("pk")] - [PrimaryKeyColumn(IdentitySeed = 40)] - public int PrimaryKey { get; set; } - [Column("nodeId")] + [PrimaryKeyColumn(AutoIncrement = false)] [ForeignKey(typeof(NodeDto))] - [Index(IndexTypes.UniqueNonClustered)] - public int DataTypeId { get; set; } + public int NodeId { get; set; } [Column("propertyEditorAlias")] - public string EditorAlias { get; set; } + public string EditorAlias { get; set; } // fixme - length?! [Column("dbType")] [Length(50)] public string DbType { get; set; }//NOTE Is set to [varchar] (50) in Sql Server script + [Column("config")] + public string Configuration { get; set; } // fixme - length? + [ResultColumn] [Reference(ReferenceType.OneToOne, ColumnName = "DataTypeId")] public NodeDto NodeDto { get; set; } diff --git a/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs b/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs index 7fbc5cad5a..d01073ccc8 100644 --- a/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs +++ b/src/Umbraco.Core/Persistence/Dtos/DataTypePreValueDto.cs @@ -3,7 +3,7 @@ using Umbraco.Core.Persistence.DatabaseAnnotations; namespace Umbraco.Core.Persistence.Dtos { - [TableName(Constants.DatabaseSchema.Tables.DataTypePreValue)] + [TableName("cmsDataTypePreValues")] [PrimaryKey("id")] [ExplicitColumns] internal class DataTypePreValueDto diff --git a/src/Umbraco.Core/Persistence/Factories/DataTypeFactory.cs b/src/Umbraco.Core/Persistence/Factories/DataTypeFactory.cs index 7da0326a9b..55be349728 100644 --- a/src/Umbraco.Core/Persistence/Factories/DataTypeFactory.cs +++ b/src/Umbraco.Core/Persistence/Factories/DataTypeFactory.cs @@ -1,95 +1,78 @@ using System; using System.Globalization; +using Newtonsoft.Json; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Dtos; +using Umbraco.Core.PropertyEditors; namespace Umbraco.Core.Persistence.Factories { - internal class DataTypeFactory + internal static class DataTypeFactory { - private readonly Guid _nodeObjectTypeId; - private int _primaryKey; - - public DataTypeFactory(Guid nodeObjectTypeId) + public static IDataType BuildEntity(DataTypeDto dto, PropertyEditor editor) { - _nodeObjectTypeId = nodeObjectTypeId; - } - - #region Implementation of IEntityFactory - - public IDataType BuildEntity(DataTypeDto dto) - { - var dataTypeDefinition = new DataType(dto.EditorAlias); - + var dataType = new DataType(dto.EditorAlias); try { - dataTypeDefinition.DisableChangeTracking(); + dataType.DisableChangeTracking(); - dataTypeDefinition.CreateDate = dto.NodeDto.CreateDate; - dataTypeDefinition.DatabaseType = dto.DbType.EnumParse(true); - dataTypeDefinition.Id = dto.DataTypeId; - dataTypeDefinition.Key = dto.NodeDto.UniqueId; - dataTypeDefinition.Level = dto.NodeDto.Level; - dataTypeDefinition.UpdateDate = dto.NodeDto.CreateDate; - dataTypeDefinition.Name = dto.NodeDto.Text; - dataTypeDefinition.ParentId = dto.NodeDto.ParentId; - dataTypeDefinition.Path = dto.NodeDto.Path; - dataTypeDefinition.SortOrder = dto.NodeDto.SortOrder; - dataTypeDefinition.Trashed = dto.NodeDto.Trashed; - dataTypeDefinition.CreatorId = dto.NodeDto.UserId.Value; + dataType.CreateDate = dto.NodeDto.CreateDate; + dataType.DatabaseType = dto.DbType.EnumParse(true); + dataType.Id = dto.NodeId; + dataType.Key = dto.NodeDto.UniqueId; + dataType.Level = dto.NodeDto.Level; + dataType.UpdateDate = dto.NodeDto.CreateDate; + dataType.Name = dto.NodeDto.Text; + dataType.ParentId = dto.NodeDto.ParentId; + dataType.Path = dto.NodeDto.Path; + dataType.SortOrder = dto.NodeDto.SortOrder; + dataType.Trashed = dto.NodeDto.Trashed; + dataType.CreatorId = dto.NodeDto.UserId ?? 0; + + dataType.EditorAlias = editor.Alias; + dataType.SetConfiguration(dto.Configuration, editor); // reset dirty initial properties (U4-1946) - dataTypeDefinition.ResetDirtyProperties(false); - return dataTypeDefinition; + dataType.ResetDirtyProperties(false); + return dataType; } finally { - dataTypeDefinition.EnableChangeTracking(); + dataType.EnableChangeTracking(); } } - public DataTypeDto BuildDto(IDataType entity) + public static DataTypeDto BuildDto(IDataType entity) { var dataTypeDto = new DataTypeDto - { - EditorAlias = entity.EditorAlias, - DataTypeId = entity.Id, - DbType = entity.DatabaseType.ToString(), - NodeDto = BuildNodeDto(entity) - }; - - if (_primaryKey > 0) { - dataTypeDto.PrimaryKey = _primaryKey; - } + EditorAlias = entity.EditorAlias, + NodeId = entity.Id, + DbType = entity.DatabaseType.ToString(), + Configuration = JsonConvert.SerializeObject(entity.Configuration), + NodeDto = BuildNodeDto(entity) + }; return dataTypeDto; } - #endregion - - public void SetPrimaryKey(int primaryKey) - { - _primaryKey = primaryKey; - } - - private NodeDto BuildNodeDto(IDataType entity) + private static NodeDto BuildNodeDto(IDataType entity) { var nodeDto = new NodeDto - { - CreateDate = entity.CreateDate, - NodeId = entity.Id, - Level = short.Parse(entity.Level.ToString(CultureInfo.InvariantCulture)), - NodeObjectType = _nodeObjectTypeId, - ParentId = entity.ParentId, - Path = entity.Path, - SortOrder = entity.SortOrder, - Text = entity.Name, - Trashed = entity.Trashed, - UniqueId = entity.Key, - UserId = entity.CreatorId - }; + { + CreateDate = entity.CreateDate, + NodeId = entity.Id, + Level = Convert.ToInt16(entity.Level), + NodeObjectType = Constants.ObjectTypes.DataType, + ParentId = entity.ParentId, + Path = entity.Path, + SortOrder = entity.SortOrder, + Text = entity.Name, + Trashed = entity.Trashed, + UniqueId = entity.Key, + UserId = entity.CreatorId + }; return nodeDto; } diff --git a/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs index 5e1aed9ba0..afb419ebd6 100644 --- a/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/IDataTypeRepository.cs @@ -6,12 +6,6 @@ namespace Umbraco.Core.Persistence.Repositories { public interface IDataTypeRepository : IReadWriteQueryRepository { - - PreValueCollection GetPreValuesCollectionByDataTypeId(int dataTypeId); - string GetPreValueAsString(int preValueId); - - void AddOrUpdatePreValues(IDataType dataType, IDictionary values); - void AddOrUpdatePreValues(int dataTypeId, IDictionary values); IEnumerable> Move(IDataType toMove, EntityContainer container); } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index e538b23406..f9b0b2270c 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -100,7 +100,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .RightJoin() .On(left => left.Id, right => right.PropertyTypeGroupId) .InnerJoin() - .On(left => left.DataTypeId, right => right.DataTypeId); + .On(left => left.DataTypeId, right => right.NodeId); var translator = new SqlTranslator(sqlClause, query); // fixme v8 are we sorting only for 7.6 relators? @@ -472,7 +472,7 @@ AND umbracoNode.id <> @id", .LeftJoin() .On(left => left.Id, right => right.PropertyTypeGroupId) .LeftJoin() - .On(left => left.DataTypeId, right => right.DataTypeId) + .On(left => left.DataTypeId, right => right.NodeId) .Where(x => x.ContentTypeNodeId == id) .OrderBy(x => x.Id); @@ -491,7 +491,7 @@ AND umbracoNode.id <> @id", .SelectAll() .From() .InnerJoin() - .On(left => left.DataTypeId, right => right.DataTypeId) + .On(left => left.DataTypeId, right => right.NodeId) .Where(x => x.ContentTypeId == id); var dtos = Database.Fetch(sql); @@ -554,12 +554,12 @@ AND umbracoNode.id <> @id", .SelectAll() .From() .Where("propertyEditorAlias = @propertyEditorAlias", new { propertyEditorAlias = propertyType.PropertyEditorAlias }) - .OrderBy(typeDto => typeDto.DataTypeId); + .OrderBy(typeDto => typeDto.NodeId); var datatype = Database.FirstOrDefault(sql); //we cannot assign a data type if one was not found if (datatype != null) { - propertyType.DataTypeDefinitionId = datatype.DataTypeId; + propertyType.DataTypeDefinitionId = datatype.NodeId; } else { diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs index 2582ba3d12..9b00729572 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DataTypeRepository.cs @@ -13,6 +13,7 @@ using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Querying; +using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -23,24 +24,23 @@ namespace Umbraco.Core.Persistence.Repositories.Implement /// internal class DataTypeRepository : NPocoRepositoryBase, IDataTypeRepository { - private readonly DataTypePreValueRepository _preValRepository; + private readonly PropertyEditorCollection _editors; - public DataTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) + public DataTypeRepository(IScopeAccessor scopeAccessor, CacheHelper cache, PropertyEditorCollection editors, ILogger logger) : base(scopeAccessor, cache, logger) { - _preValRepository = new DataTypePreValueRepository(scopeAccessor, CacheHelper.NoCache, logger); + _editors = editors; } #region Overrides of RepositoryBase protected override IDataType PerformGet(int id) { - return GetMany(new[] { id }).FirstOrDefault(); + return GetMany(id).FirstOrDefault(); } protected override IEnumerable PerformGetAll(params int[] ids) { - var factory = new DataTypeFactory(NodeObjectTypeId); var dataTypeSql = GetBaseQuery(false); if (ids.Any()) @@ -53,20 +53,18 @@ namespace Umbraco.Core.Persistence.Repositories.Implement } var dtos = Database.Fetch(dataTypeSql); - return dtos.Select(factory.BuildEntity).ToArray(); + return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors[x.EditorAlias])).ToArray(); } protected override IEnumerable PerformGetByQuery(IQuery query) { - var factory = new DataTypeFactory(NodeObjectTypeId); - var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator(sqlClause, query); var sql = translator.Translate(); var dtos = Database.Fetch(sql); - return dtos.Select(factory.BuildEntity).ToArray(); + return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors[x.EditorAlias])).ToArray(); } #endregion @@ -84,7 +82,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement sql .From() .InnerJoin() - .On(left => left.DataTypeId, right => right.NodeId) + .On(left => left.NodeId, right => right.NodeId) .Where(x => x.NodeObjectType == NodeObjectTypeId); return sql; } @@ -122,8 +120,7 @@ WHERE umbracoNode." + SqlSyntax.GetQuotedColumnName("text") + "= @name", new { n throw new DuplicateNameException("A data type with the name " + entity.Name + " already exists"); } - var factory = new DataTypeFactory(NodeObjectTypeId); - var dto = factory.BuildDto(entity); + var dto = DataTypeFactory.BuildDto(entity); //Logic for setting Path, Level and SortOrder var parent = Database.First("WHERE id = @ParentId", new { ParentId = entity.ParentId }); @@ -149,7 +146,7 @@ WHERE umbracoNode." + SqlSyntax.GetQuotedColumnName("text") + "= @name", new { n entity.SortOrder = sortOrder; entity.Level = level; - dto.DataTypeId = nodeDto.NodeId; + dto.NodeId = nodeDto.NodeId; Database.Insert(dto); entity.ResetDirtyProperties(); @@ -187,21 +184,13 @@ AND umbracoNode.id <> @id", entity.SortOrder = maxSortOrder + 1; } - var factory = new DataTypeFactory(NodeObjectTypeId); - //Look up DataTypeDefinition entry to get Primary for updating the DTO - var dataTypeDto = Database.SingleOrDefault("WHERE nodeId = @Id", new { Id = entity.Id }); - factory.SetPrimaryKey(dataTypeDto.PrimaryKey); - var dto = factory.BuildDto(entity); + var dto = DataTypeFactory.BuildDto(entity); //Updates the (base) node data - umbracoNode var nodeDto = dto.NodeDto; Database.Update(nodeDto); Database.Update(dto); - //NOTE: This is a special case, we need to clear the custom cache for pre-values here so they are not stale if devs - // are querying for them in the Saved event (before the distributed call cache is clearing it) - IsolatedCache.ClearCacheItem(GetPrefixedCacheKey(entity.Id)); - entity.ResetDirtyProperties(); } @@ -225,9 +214,6 @@ AND umbracoNode.id <> @id", Database.Delete("WHERE id = @Id", new { Id = dto.Id }); } - //Delete the pre-values - Database.Delete("WHERE datatypeNodeId = @Id", new { Id = entity.Id }); - //Delete Content specific data Database.Delete("WHERE nodeId = @Id", new { Id = entity.Id }); @@ -239,41 +225,6 @@ AND umbracoNode.id <> @id", #endregion - public PreValueCollection GetPreValuesCollectionByDataTypeId(int dataTypeId) - { - return GetCachedPreValueCollection(dataTypeId); - } - - public string GetPreValueAsString(int preValueId) - { - var collections = IsolatedCache.GetCacheItemsByKeySearch(CacheKeys.DataTypePreValuesCacheKey + "_"); - - var preValue = collections.SelectMany(x => x.FormatAsDictionary().Values).FirstOrDefault(x => x.Id == preValueId); - if (preValue != null) - return preValue.Value; - - var dto = Database.FirstOrDefault("WHERE id = @preValueId", new { preValueId }); - if (dto == null) - return string.Empty; - - var collection = GetCachedPreValueCollection(dto.DataTypeNodeId); - if (collection == null) - return string.Empty; - - preValue = collection.FormatAsDictionary().Values.FirstOrDefault(x => x.Id == preValueId); - return preValue == null ? string.Empty : preValue.Value; - } - - public void AddOrUpdatePreValues(int dataTypeId, IDictionary values) - { - var dtd = Get(dataTypeId); - if (dtd == null) - { - throw new InvalidOperationException("No data type found with id " + dataTypeId); - } - AddOrUpdatePreValues(dtd, values); - } - public IEnumerable> Move(IDataType toMove, EntityContainer container) { var parentId = -1; @@ -322,90 +273,6 @@ AND umbracoNode.id <> @id", return moveInfo; } - public void AddOrUpdatePreValues(IDataType dataType, IDictionary values) - { - var currentVals = new DataTypePreValueDto[] { }; - if (dataType.HasIdentity) - { - //first just get all pre-values for this data type so we can compare them to see if we need to insert or update or replace - var sql = Sql() - .SelectAll() - .From() - .Where(dto => dto.DataTypeNodeId == dataType.Id) - .OrderBy(dto => dto.SortOrder); - currentVals = Database.Fetch(sql).ToArray(); - } - - //already existing, need to be updated - var valueIds = values.Where(x => x.Value.Id > 0).Select(x => x.Value.Id).ToArray(); - var existingByIds = currentVals.Where(x => valueIds.Contains(x.Id)).ToArray(); - - //These ones need to be removed from the db, they no longer exist in the new values - var deleteById = currentVals.Where(x => valueIds.Contains(x.Id) == false); - - foreach (var d in deleteById) - { - _preValRepository.Delete(new PreValueEntity - { - Alias = d.Alias, - Id = d.Id, - Value = d.Value, - DataType = dataType, - SortOrder = d.SortOrder - }); - } - - var sortOrder = 1; - - foreach (var pre in values) - { - var existing = existingByIds.FirstOrDefault(valueDto => valueDto.Id == pre.Value.Id); - if (existing != null) - { - _preValRepository.Save(new PreValueEntity - { - //setting an id will update it - Id = existing.Id, - DataType = dataType, - //These are the new values to update - Alias = pre.Key, - SortOrder = sortOrder, - Value = pre.Value.Value - }); - } - else - { - _preValRepository.Save(new PreValueEntity - { - Alias = pre.Key, - SortOrder = sortOrder, - Value = pre.Value.Value, - DataType = dataType, - }); - } - - sortOrder++; - } - - } - - private static string GetPrefixedCacheKey(int dataTypeId) - { - return CacheKeys.DataTypePreValuesCacheKey + "_" + dataTypeId; - } - - private PreValueCollection GetCachedPreValueCollection(int dataTypeId) - { - var key = GetPrefixedCacheKey(dataTypeId); - return IsolatedCache.GetCacheItem(key, () => - { - var dtos = Database.Fetch("WHERE datatypeNodeId = @Id", new { Id = dataTypeId }); - var list = dtos.Select(x => new Tuple(new PreValue(x.Id, x.Value, x.SortOrder), x.Alias, x.SortOrder)).ToList(); - var collection = PreValueConverter.ConvertToPreValuesCollection(list); - return collection; - }, TimeSpan.FromMinutes(20), isSliding: true); - } - private string EnsureUniqueNodeName(string nodeName, int id = 0) { var template = SqlContext.Templates.Get("Umbraco.Core.DataTypeDefinitionRepository.EnsureUniqueNodeName", tsql => tsql @@ -418,154 +285,5 @@ AND umbracoNode.id <> @id", return SimilarNodeName.GetUniqueName(names, id, nodeName); } - - /// - /// Private class to handle pre-value crud based on units of work with transactions - /// - private class PreValueEntity : EntityBase - { - public string Value { get; set; } - public string Alias { get; set; } - public IDataType DataType { get; set; } - public int SortOrder { get; set; } - } - - /// - /// Private class to handle pre-value crud based on standard principles and units of work with transactions - /// - private class DataTypePreValueRepository : NPocoRepositoryBase - { - public DataTypePreValueRepository(IScopeAccessor scopeAccessor, CacheHelper cache, ILogger logger) - : base(scopeAccessor, cache, logger) - { } - - #region Not implemented (don't need to for the purposes of this repo) - protected override PreValueEntity PerformGet(int id) - { - throw new NotImplementedException(); - } - - protected override IEnumerable PerformGetAll(params int[] ids) - { - throw new NotImplementedException(); - } - - protected override IEnumerable PerformGetByQuery(IQuery query) - { - throw new NotImplementedException(); - } - - protected override Sql GetBaseQuery(bool isCount) - { - throw new NotImplementedException(); - } - - protected override string GetBaseWhereClause() - { - throw new NotImplementedException(); - } - - protected override IEnumerable GetDeleteClauses() - { - return Array.Empty(); - } - - protected override Guid NodeObjectTypeId - { - get { throw new NotImplementedException(); } - } - #endregion - - protected override void PersistDeletedItem(PreValueEntity entity) - { - Database.Execute("DELETE FROM cmsDataTypePreValues WHERE id=@Id", new { Id = entity.Id }); - - entity.DeleteDate = DateTime.Now; - } - - protected override void PersistNewItem(PreValueEntity entity) - { - if (entity.DataType.HasIdentity == false) - { - throw new InvalidOperationException("Cannot insert a pre value for a data type that has no identity"); - } - - //NOTE: We used to check that the Alias was unique for the given DataTypeNodeId prevalues list, BUT - // in reality there is no need to check the uniqueness of this alias because the only way that this code executes is - // based on an IDictionary dictionary being passed to this repository and a dictionary - // must have unique aliases by definition, so there is no need for this additional check - - var dto = new DataTypePreValueDto - { - DataTypeNodeId = entity.DataType.Id, - Value = entity.Value, - SortOrder = entity.SortOrder, - Alias = entity.Alias - }; - Database.Insert(dto); - } - - protected override void PersistUpdatedItem(PreValueEntity entity) - { - if (entity.DataType.HasIdentity == false) - { - throw new InvalidOperationException("Cannot update a pre value for a data type that has no identity"); - } - - //NOTE: We used to check that the Alias was unique for the given DataTypeNodeId prevalues list, BUT - // this causes issues when sorting the pre-values (http://issues.umbraco.org/issue/U4-5670) but in reality - // there is no need to check the uniqueness of this alias because the only way that this code executes is - // based on an IDictionary dictionary being passed to this repository and a dictionary - // must have unique aliases by definition, so there is no need for this additional check - - var dto = new DataTypePreValueDto - { - DataTypeNodeId = entity.DataType.Id, - Id = entity.Id, - Value = entity.Value, - SortOrder = entity.SortOrder, - Alias = entity.Alias - }; - Database.Update(dto); - } - - - } - - internal static class PreValueConverter - { - /// - /// Converts the tuple to a pre-value collection - /// - /// - /// - internal static PreValueCollection ConvertToPreValuesCollection(IEnumerable> list) - { - //now we need to determine if they are dictionary based, otherwise they have to be array based - var dictionary = new Dictionary(); - - //need to check all of the keys, if there's only one and it is empty then it's an array - var keys = list.Select(x => x.Item2).Distinct().ToArray(); - if (keys.Length == 1 && keys[0].IsNullOrWhiteSpace()) - { - return new PreValueCollection(list.OrderBy(x => x.Item3).Select(x => x.Item1)); - } - - foreach (var item in list - .OrderBy(x => x.Item3) //we'll order them first so we maintain the order index in the dictionary - .GroupBy(x => x.Item2)) //group by alias - { - if (item.Count() > 1) - { - //if there's more than 1 item per key, then it cannot be a dictionary, just return the array - return new PreValueCollection(list.OrderBy(x => x.Item3).Select(x => x.Item1)); - } - - dictionary.Add(item.Key, item.First().Item1); - } - - return new PreValueCollection(dictionary); - } - } } } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/EntityRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/EntityRepository.cs index ed12a3a4eb..857e059942 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/EntityRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/EntityRepository.cs @@ -370,7 +370,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .Select(r => r.Select(x => x.PropertyTypeDto, r1 => r1.Select(x => x.DataTypeDto))) .From() .InnerJoin().On((left, right) => left.PropertyTypeId == right.Id) - .InnerJoin().On((left, right) => left.DataTypeId == right.DataTypeId) + .InnerJoin().On((left, right) => left.DataTypeId == right.NodeId) .Where(x => x.VersionId == versionId); } @@ -380,7 +380,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .Select(r => r.Select(x => x.PropertyTypeDto, r1 => r1.Select(x => x.DataTypeDto))) .From() .InnerJoin().On((left, right) => left.PropertyTypeId == right.Id) - .InnerJoin().On((left, right) => left.DataTypeId == right.DataTypeId) + .InnerJoin().On((left, right) => left.DataTypeId == right.NodeId) .WhereIn(x => x.VersionId, versionIds) .OrderBy(x => x.VersionId); } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs index 9daf174f67..75990e12b3 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberRepository.cs @@ -161,7 +161,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .InnerJoin().On((left, right) => left.NodeId == right.NodeId) .LeftJoin().On(left => left.ContentTypeId, right => right.ContentTypeId) - .LeftJoin().On(left => left.DataTypeId, right => right.DataTypeId) + .LeftJoin().On(left => left.DataTypeId, right => right.NodeId) .LeftJoin().On(x => x .Where((left, right) => left.PropertyTypeId == right.Id) diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs index 0548365274..b2ee926a5b 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/MemberTypeRepository.cs @@ -155,7 +155,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .InnerJoin().On(left => left.NodeId, right => right.NodeId) .LeftJoin().On(left => left.ContentTypeId, right => right.NodeId) .LeftJoin().On(left => left.PropertyTypeId, right => right.Id) - .LeftJoin().On(left => left.DataTypeId, right => right.DataTypeId) + .LeftJoin().On(left => left.NodeId, right => right.DataTypeId) .LeftJoin().On(left => left.ContentTypeNodeId, right => right.NodeId) .Where(x => x.NodeObjectType == NodeObjectTypeId); @@ -170,7 +170,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement .InnerJoin().On(left => left.NodeId, right => right.NodeId) .LeftJoin().On(left => left.ContentTypeId, right => right.NodeId) .LeftJoin().On(left => left.PropertyTypeId, right => right.Id) - .LeftJoin().On(left => left.DataTypeId, right => right.DataTypeId) + .LeftJoin().On(left => left.NodeId, right => right.DataTypeId) .LeftJoin().On(left => left.ContentTypeNodeId, right => right.NodeId) .Where(x => x.NodeObjectType == NodeObjectTypeId); return sql; diff --git a/src/Umbraco.Core/PropertyEditors/DecimalValidator.cs b/src/Umbraco.Core/PropertyEditors/DecimalValidator.cs index 4b8b6213db..58a2bf0dfb 100644 --- a/src/Umbraco.Core/PropertyEditors/DecimalValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/DecimalValidator.cs @@ -10,21 +10,21 @@ namespace Umbraco.Core.PropertyEditors [ValueValidator("Decimal")] internal sealed class DecimalValidator : ManifestValueValidator, IPropertyValidator { - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + /// + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { - if (value != null && value.ToString() != string.Empty) - { - var result = value.TryConvertTo(); - if (result.Success == false) - { - yield return new ValidationResult("The value " + value + " is not a valid decimal", new[] { "value" }); - } - } + if (value == null || value.ToString() == string.Empty) + yield break; + + var result = value.TryConvertTo(); + if (result.Success == false) + yield return new ValidationResult("The value " + value + " is not a valid decimal", new[] { "value" }); } - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + /// + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { - return Validate(value, "", preValues, editor); + return Validate(value, "", dataTypeConfiguration, editor); } } } diff --git a/src/Umbraco.Core/PropertyEditors/DelimitedManifestValueValidator.cs b/src/Umbraco.Core/PropertyEditors/DelimitedManifestValueValidator.cs index 0ea3cf6bce..4954b495d8 100644 --- a/src/Umbraco.Core/PropertyEditors/DelimitedManifestValueValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/DelimitedManifestValueValidator.cs @@ -14,24 +14,17 @@ namespace Umbraco.Core.PropertyEditors [ValueValidator("Delimited")] internal sealed class DelimitedManifestValueValidator : ManifestValueValidator { - /// - /// Performs the validation - /// - /// - /// Can be a json formatted string containing properties: 'delimiter' and 'pattern' - /// The current pre-values stored for the data type - /// - /// - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + /// + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { //TODO: localize these! if (value != null) { var delimiter = ","; Regex regex = null; - if (config.IsNullOrWhiteSpace() == false) + if (validatorConfiguration.IsNullOrWhiteSpace() == false) { - var json = JsonConvert.DeserializeObject(config); + var json = JsonConvert.DeserializeObject(validatorConfiguration); if (json["delimiter"] != null) { delimiter = json["delimiter"].ToString(); diff --git a/src/Umbraco.Core/PropertyEditors/EmailValidator.cs b/src/Umbraco.Core/PropertyEditors/EmailValidator.cs index d83d9fae76..3041585187 100644 --- a/src/Umbraco.Core/PropertyEditors/EmailValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/EmailValidator.cs @@ -10,7 +10,8 @@ namespace Umbraco.Core.PropertyEditors [ValueValidator("Email")] internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator { - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + /// + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { var asString = value.ToString(); @@ -23,9 +24,10 @@ namespace Umbraco.Core.PropertyEditors } } - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + /// + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { - return this.Validate(value, null, preValues, editor); + return this.Validate(value, null, dataTypeConfiguration, editor); } } } diff --git a/src/Umbraco.Core/PropertyEditors/IPropertyValidator.cs b/src/Umbraco.Core/PropertyEditors/IPropertyValidator.cs index 3cbb3485b0..e523424044 100644 --- a/src/Umbraco.Core/PropertyEditors/IPropertyValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/IPropertyValidator.cs @@ -5,24 +5,19 @@ using Umbraco.Core.Models; namespace Umbraco.Core.PropertyEditors { /// - /// An interface defining a validator + /// Defines a property validator. /// public interface IPropertyValidator { /// - /// Validates the object with the resolved ValueValidator found for this type + /// Validates. /// - /// - /// Depending on what is being validated, this value can be a json structure (JObject, JArray, etc...) representing an editor's model, it could be a single - /// string representing an editor's model, this class structure is also used to validate pre-values and in that case this value - /// could be a json structure or a single value representing a pre-value field. - /// - /// - /// When validating a property editor value (not a pre-value), this is the current pre-values stored for the data type. - /// When validating a pre-value field this will be null. - /// - /// The property editor instance that we are validating for - /// - IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor); + /// The value to validate. Can be a json structure (JObject, JArray, etc...), could be a single string, representing an editor's model. + /// The data type configuration. + /// The property editor. + /// Validation results. + /// If a validation result does not have a field name, then it applies to the entire property + /// type being validated. Otherwise, it matches a field. + IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor); } } diff --git a/src/Umbraco.Core/PropertyEditors/IntegerValidator.cs b/src/Umbraco.Core/PropertyEditors/IntegerValidator.cs index 826b008e3c..b8d94f09e1 100644 --- a/src/Umbraco.Core/PropertyEditors/IntegerValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/IntegerValidator.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.PropertyEditors [ValueValidator("Integer")] internal sealed class IntegerValidator : ManifestValueValidator, IPropertyValidator { - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { if (value != null && value.ToString() != string.Empty) { @@ -22,9 +22,9 @@ namespace Umbraco.Core.PropertyEditors } } - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { - return Validate(value, "", preValues, editor); + return Validate(value, "", dataTypeConfiguration, editor); } } } diff --git a/src/Umbraco.Core/PropertyEditors/ManifestPropertyValidator.cs b/src/Umbraco.Core/PropertyEditors/ManifestPropertyValidator.cs index 9fccbd101d..9a4dd31157 100644 --- a/src/Umbraco.Core/PropertyEditors/ManifestPropertyValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/ManifestPropertyValidator.cs @@ -54,13 +54,9 @@ namespace Umbraco.Core.PropertyEditors /// /// Validates the object with the resolved ValueValidator found for this type /// - /// - /// The current pre-values stored for the data type - /// The property editor instance that we are validating for - /// - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { - return ValidatorInstance.Validate(value, Config, preValues, editor); + return ValidatorInstance.Validate(value, Config, dataTypeConfiguration, editor); } } } diff --git a/src/Umbraco.Core/PropertyEditors/ManifestValueValidator.cs b/src/Umbraco.Core/PropertyEditors/ManifestValueValidator.cs index a9c25bf029..754f254b69 100644 --- a/src/Umbraco.Core/PropertyEditors/ManifestValueValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/ManifestValueValidator.cs @@ -6,41 +6,30 @@ using Umbraco.Core.Models; namespace Umbraco.Core.PropertyEditors { /// - /// A validator used to validate a value based on a validator name defined in a package manifest + /// A validator used to validate a value based on a validator name defined in a package manifest. /// public abstract class ManifestValueValidator { protected ManifestValueValidator() { - var att = this.GetType().GetCustomAttribute(false); + var att = GetType().GetCustomAttribute(false); if (att == null) - { - throw new InvalidOperationException("The class " + GetType() + " is not attributed with the " + typeof(ValueValidatorAttribute) + " attribute"); - } + throw new InvalidOperationException($"Class {GetType()} is not attributed with the {typeof(ValueValidatorAttribute)} attribute."); TypeName = att.TypeName; } - public string TypeName { get; private set; } + public string TypeName { get; } /// - /// Performs the validation against the value + /// Validates. /// - /// - /// Depending on what is being validated, this value can be a json structure (JObject, JArray, etc...) representing an editor's model, it could be a single - /// string representing an editor's model. - /// - /// - /// An object that is used to configure the validator. An example could be a regex - /// expression if the validator was a regex validator. This is defined in the manifest along with - /// the definition of the validator. - /// - /// The current pre-values stored for the data type - /// The property editor instance that is being validated - /// - /// Returns a list of validation results. If a result does not have a field name applied to it then then we assume that - /// the validation message applies to the entire property type being validated. If there is a field name applied to a - /// validation result we will try to match that field name up with a field name on the item itself. - /// - public abstract IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor); + /// The value to validate. Can be a json structure (JObject, JArray, etc...), could be a single string, representing an editor's model. + /// The validator configuration, defined in the manifest. + /// The data type configuration. + /// The property editor. + /// Validation results. + /// If a validation result does not have a field name, then it applies to the entire property + /// type being validated. Otherwise, it matches a field. + public abstract IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor); } } diff --git a/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs b/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs index ceb9a82924..01c654553a 100644 --- a/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/PreValueEditor.cs @@ -26,52 +26,50 @@ namespace Umbraco.Core.PropertyEditors var fields = new List(); //the ctor checks if we have PreValueFieldAttributes applied and if so we construct our fields from them - var props = TypeHelper.CachedDiscoverableProperties(GetType()) - .Where(x => x.Name != "Fields"); + var props = TypeHelper.CachedDiscoverableProperties(GetType()).Where(x => x.Name != "Fields"); foreach (var p in props) { var att = p.GetCustomAttributes(typeof (PreValueFieldAttribute), false).OfType().SingleOrDefault(); - if (att != null) + if (att == null) continue; + + if (att.PreValueFieldType != null) { - if (att.PreValueFieldType != null) + //try to create it + try { - //try to create it - try - { - var instance = (PreValueField) Activator.CreateInstance(att.PreValueFieldType); - //overwrite values if they are assigned - if (!att.Key.IsNullOrWhiteSpace()) - { - instance.Key = att.Key; - } - //if the key is still empty then assign it to be the property name - if (instance.Key.IsNullOrWhiteSpace()) - { - instance.Key = p.Name; - } + // instanciate and add custom field + var instance = (PreValueField) Activator.CreateInstance(att.PreValueFieldType); + fields.Add(instance); - if (!att.Name.IsNullOrWhiteSpace()) - instance.Name = att.Name; - if (!att.View.IsNullOrWhiteSpace()) - instance.View = att.View; - if (!att.Description.IsNullOrWhiteSpace()) - instance.Description = att.Description; - if (att.HideLabel) - instance.HideLabel = att.HideLabel; + // overwrite values if they are assigned + if (!att.Key.IsNullOrWhiteSpace()) + instance.Key = att.Key; - //add the custom field - fields.Add(instance); - } - catch (Exception ex) - { - Current.Logger.Warn(ex, "Could not create an instance of " + att.PreValueFieldType); - } + // if the key is still empty then assign it to be the property name + if (instance.Key.IsNullOrWhiteSpace()) + instance.Key = p.Name; + + if (!att.Name.IsNullOrWhiteSpace()) + instance.Name = att.Name; + + if (!att.View.IsNullOrWhiteSpace()) + instance.View = att.View; + + if (!att.Description.IsNullOrWhiteSpace()) + instance.Description = att.Description; + + if (att.HideLabel) + instance.HideLabel = att.HideLabel; } - else + catch (Exception ex) { - fields.Add(MapAttributeToField(att, p)); + Current.Logger.Warn(ex, "Could not create an instance of " + att.PreValueFieldType); } } + else + { + fields.Add(MapAttributeToField(att, p)); + } } Fields = fields; @@ -117,7 +115,7 @@ namespace Umbraco.Core.PropertyEditors public virtual IDictionary ConvertEditorToDb(IDictionary editorValue, PreValueCollection currentValue) { //convert to a string based value to be saved in the db - return editorValue.ToDictionary(x => x.Key, x => new PreValue(x.Value == null ? null : x.Value.ToString())); + return editorValue.ToDictionary(x => x.Key, x => new PreValue(x.Value?.ToString())); } /// diff --git a/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs b/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs index 2ee0775750..14508e6aa4 100644 --- a/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/PropertyEditor.cs @@ -187,28 +187,11 @@ namespace Umbraco.Core.PropertyEditors } /// - /// Maps a preValues collection to a strongly typed object. + /// Maps configuration to a strongly typed object. /// - /// The preValues collection. - /// A strongly typed object. - /// - /// Each property editor can declare a DataTypeConfiguration inner class that represents - /// its preValues in a nice strongly typed way, and override this method to convert the preValues - /// collection. - /// Otherwise, by default, this method will convert to a Dictionary{string, string}. - /// fixme - is this temp? - /// - public virtual object MapDataTypeConfiguration(PreValueCollection preValues) + public virtual object DeserializeConfiguration(string json) { - var asDictionary = preValues.IsDictionaryBased - ? preValues.PreValuesAsDictionary - : preValues.FormatAsDictionary(); - - var configuration = new Dictionary(); - foreach (var kvp in asDictionary) - configuration[kvp.Key] = kvp.Value.Value; - - return configuration; + return JsonConvert.DeserializeObject>(json); } } } diff --git a/src/Umbraco.Core/PropertyEditors/RegexValidator.cs b/src/Umbraco.Core/PropertyEditors/RegexValidator.cs index 4cac9f1370..c35cb00344 100644 --- a/src/Umbraco.Core/PropertyEditors/RegexValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/RegexValidator.cs @@ -27,18 +27,17 @@ namespace Umbraco.Core.PropertyEditors /// public RegexValidator(string regex) { - if (regex == null) throw new ArgumentNullException("regex"); - _regex = regex; + _regex = regex ?? throw new ArgumentNullException(nameof(regex)); } - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { //TODO: localize these! - if (config.IsNullOrWhiteSpace() == false && value != null) + if (validatorConfiguration.IsNullOrWhiteSpace() == false && value != null) { var asString = value.ToString(); - var regex = new Regex(config); + var regex = new Regex(validatorConfiguration); if (regex.IsMatch(asString) == false) { @@ -55,13 +54,13 @@ namespace Umbraco.Core.PropertyEditors /// /// /// - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { if (_regex == null) { throw new InvalidOperationException("This validator is not configured as a " + typeof(IPropertyValidator)); } - return Validate(value, _regex, preValues, editor); + return Validate(value, _regex, dataTypeConfiguration, editor); } } } diff --git a/src/Umbraco.Core/PropertyEditors/RequiredManifestValueValidator.cs b/src/Umbraco.Core/PropertyEditors/RequiredManifestValueValidator.cs index e421bf7cac..1f7829c8a1 100644 --- a/src/Umbraco.Core/PropertyEditors/RequiredManifestValueValidator.cs +++ b/src/Umbraco.Core/PropertyEditors/RequiredManifestValueValidator.cs @@ -10,7 +10,7 @@ namespace Umbraco.Core.PropertyEditors [ValueValidator("Required")] internal sealed class RequiredManifestValueValidator : ManifestValueValidator { - public override IEnumerable Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) + public override IEnumerable Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor) { //TODO: localize these! diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs index 66d46f0e13..3bbd268de8 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs @@ -67,9 +67,13 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters // GetPreValuesCollectionByDataTypeId is cached at repository level; // still, the collection is deep-cloned so this is kinda expensive, // better to cache here + trigger refresh in DataTypeCacheRefresher + // fixme wtf this should NOT be expensive! return Storages.GetOrAdd(dataTypeId, id => { + var dataType = _dataTypeService.GetDataType(id); + var configuration = dataType.Configuration as SliderPropertyEditor.Configuration; // fixme - why is the converter in Core if the editor is in Web? + return configuration.IsRange; var preValue = _dataTypeService.GetPreValuesCollectionByDataTypeId(id) .PreValuesAsDictionary .FirstOrDefault(x => string.Equals(x.Key, "enableRange", StringComparison.InvariantCultureIgnoreCase)) diff --git a/src/Umbraco.Core/Services/EntityXmlSerializer.cs b/src/Umbraco.Core/Services/EntityXmlSerializer.cs index a152fa29e3..7c0de0b1eb 100644 --- a/src/Umbraco.Core/Services/EntityXmlSerializer.cs +++ b/src/Umbraco.Core/Services/EntityXmlSerializer.cs @@ -263,7 +263,7 @@ namespace Umbraco.Core.Services var genericProperties = new XElement("GenericProperties"); // actually, all of them foreach (var propertyType in mediaType.PropertyTypes) { - var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); + var definition = dataTypeService.GetDataType(propertyType.DataTypeDefinitionId); var propertyGroup = propertyType.PropertyGroupId == null // true generic property ? null @@ -374,7 +374,7 @@ namespace Umbraco.Core.Services var genericProperties = new XElement("GenericProperties"); // actually, all of them foreach (var propertyType in contentType.PropertyTypes) { - var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); + var definition = dataTypeService.GetDataType(propertyType.DataTypeDefinitionId); var propertyGroup = propertyType.PropertyGroupId == null // true generic property ? null diff --git a/src/Umbraco.Core/Services/IDataTypeService.cs b/src/Umbraco.Core/Services/IDataTypeService.cs index 6f3f41b817..fef7065571 100644 --- a/src/Umbraco.Core/Services/IDataTypeService.cs +++ b/src/Umbraco.Core/Services/IDataTypeService.cs @@ -24,28 +24,28 @@ namespace Umbraco.Core.Services /// /// Name of the /// - IDataType GetDataTypeDefinitionByName(string name); + IDataType GetDataType(string name); /// /// Gets a by its Id /// /// Id of the /// - IDataType GetDataTypeDefinitionById(int id); + IDataType GetDataType(int id); /// /// Gets a by its unique guid Id /// /// Unique guid Id of the DataType /// - IDataType GetDataTypeDefinitionById(Guid id); + IDataType GetDataType(Guid id); /// /// Gets all objects or those with the ids passed in /// /// Optional array of Ids /// An enumerable list of objects - IEnumerable GetAllDataTypeDefinitions(params int[] ids); + IEnumerable GetAll(params int[] ids); /// /// Saves an @@ -85,60 +85,8 @@ namespace Umbraco.Core.Services /// /// Alias of the property editor /// Collection of objects with a matching contorl id - IEnumerable GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias); - - /// - /// Gets all values for an - /// - /// Id of the to retrieve prevalues from - /// An enumerable list of string values - IEnumerable GetPreValuesByDataTypeId(int id); - - /// - /// Gets a pre-value collection by data type id - /// - /// - /// - PreValueCollection GetPreValuesCollectionByDataTypeId(int id); - - /// - /// Saves a list of PreValues for a given DataTypeDefinition - /// - /// Id of the DataTypeDefinition to save PreValues for - /// List of string values to save - [Obsolete("This should no longer be used, use the alternative SavePreValues or SaveDataTypeAndPreValues methods instead. This will only insert pre-values without keys")] - void SavePreValues(int dataTypeId, IEnumerable values); - - /// - /// Saves a list of PreValues for a given DataTypeDefinition - /// - /// Id of the DataTypeDefinition to save PreValues for - /// List of key/value pairs to save - void SavePreValues(int dataTypeId, IDictionary values); - - /// - /// Saves a list of PreValues for a given DataTypeDefinition - /// - /// The DataTypeDefinition to save PreValues for - /// List of key/value pairs to save - void SavePreValues(IDataType dataType, IDictionary values); - - /// - /// Saves the data type and it's prevalues - /// - /// - /// - /// - void SaveDataTypeAndPreValues(IDataType dataType, IDictionary values, int userId = 0); - - /// - /// Gets a specific PreValue by its Id - /// - /// Id of the PreValue to retrieve the value from - /// PreValue as a string - string GetPreValueAsString(int id); + IEnumerable GetByEditorAlias(string propertyEditorAlias); Attempt> Move(IDataType toMove, int parentId); - } } diff --git a/src/Umbraco.Core/Services/Implement/DataTypeService.cs b/src/Umbraco.Core/Services/Implement/DataTypeService.cs index 82e2548966..8fdd5a1ba0 100644 --- a/src/Umbraco.Core/Services/Implement/DataTypeService.cs +++ b/src/Umbraco.Core/Services/Implement/DataTypeService.cs @@ -223,7 +223,7 @@ namespace Umbraco.Core.Services.Implement /// /// Name of the /// - public IDataType GetDataTypeDefinitionByName(string name) + public IDataType GetDataType(string name) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { @@ -236,7 +236,7 @@ namespace Umbraco.Core.Services.Implement /// /// Id of the /// - public IDataType GetDataTypeDefinitionById(int id) + public IDataType GetDataType(int id) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { @@ -249,7 +249,7 @@ namespace Umbraco.Core.Services.Implement /// /// Unique guid Id of the DataType /// - public IDataType GetDataTypeDefinitionById(Guid id) + public IDataType GetDataType(Guid id) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { @@ -263,7 +263,7 @@ namespace Umbraco.Core.Services.Implement /// /// Alias of the property editor /// Collection of objects with a matching contorl id - public IEnumerable GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias) + public IEnumerable GetByEditorAlias(string propertyEditorAlias) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { @@ -277,7 +277,7 @@ namespace Umbraco.Core.Services.Implement /// /// Optional array of Ids /// An enumerable list of objects - public IEnumerable GetAllDataTypeDefinitions(params int[] ids) + public IEnumerable GetAll(params int[] ids) { using (var scope = ScopeProvider.CreateScope(autoComplete: true)) { @@ -285,48 +285,6 @@ namespace Umbraco.Core.Services.Implement } } - /// - /// Gets all prevalues for an - /// - /// Id of the to retrieve prevalues from - /// An enumerable list of string values - public IEnumerable GetPreValuesByDataTypeId(int id) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - var collection = _dataTypeRepository.GetPreValuesCollectionByDataTypeId(id); - //now convert the collection to a string list - return collection.FormatAsDictionary() - .Select(x => x.Value.Value) - .ToList(); - } - } - - /// - /// Returns the PreValueCollection for the specified data type - /// - /// - /// - public PreValueCollection GetPreValuesCollectionByDataTypeId(int id) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _dataTypeRepository.GetPreValuesCollectionByDataTypeId(id); - } - } - - /// - /// Gets a specific PreValue by its Id - /// - /// Id of the PreValue to retrieve the value from - /// PreValue as a string - public string GetPreValueAsString(int id) - { - using (var scope = ScopeProvider.CreateScope(autoComplete: true)) - { - return _dataTypeRepository.GetPreValueAsString(id); - } - } public Attempt> Move(IDataType toMove, int parentId) { @@ -447,107 +405,6 @@ namespace Umbraco.Core.Services.Implement } } - /// - /// Saves a list of PreValues for a given DataTypeDefinition - /// - /// Id of the DataTypeDefinition to save PreValues for - /// List of string values to save - [Obsolete("This should no longer be used, use the alternative SavePreValues or SaveDataTypeAndPreValues methods instead. This will only insert pre-values without keys")] - public void SavePreValues(int dataTypeId, IEnumerable values) - { - //TODO: Should we raise an event here since we are really saving values for the data type? - - using (var scope = ScopeProvider.CreateScope()) - { - var sortOrderObj = scope.Database.ExecuteScalar( - "SELECT max(sortorder) FROM cmsDataTypePreValues WHERE datatypeNodeId = @DataTypeId", new { DataTypeId = dataTypeId }); - - if (sortOrderObj == null || int.TryParse(sortOrderObj.ToString(), out int sortOrder) == false) - sortOrder = 1; - - foreach (var value in values) - { - var dto = new DataTypePreValueDto { DataTypeNodeId = dataTypeId, Value = value, SortOrder = sortOrder }; - scope.Database.Insert(dto); - sortOrder++; - } - - scope.Complete(); - } - } - - /// - /// Saves/updates the pre-values - /// - /// - /// - /// - /// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors - /// like 'dropdown list publishing keys' - /// - public void SavePreValues(int dataTypeId, IDictionary values) - { - var dtd = GetDataTypeDefinitionById(dataTypeId); - if (dtd == null) - throw new InvalidOperationException("No data type found for id " + dataTypeId); - - SavePreValues(dtd, values); - } - - /// - /// Saves/updates the pre-values - /// - /// - /// - /// - /// We need to actually look up each pre-value and maintain it's id if possible - this is because of silly property editors - /// like 'dropdown list publishing keys' - /// - public void SavePreValues(IDataType dataType, IDictionary values) - { - //TODO: Should we raise an event here since we are really saving values for the data type? - - using (var scope = ScopeProvider.CreateScope()) - { - _dataTypeRepository.AddOrUpdatePreValues(dataType, values); - scope.Complete(); - } - } - - /// - /// This will save a data type and it's pre-values in one transaction - /// - /// - /// - /// - public void SaveDataTypeAndPreValues(IDataType dataType, IDictionary values, int userId = 0) - { - using (var scope = ScopeProvider.CreateScope()) - { - var saveEventArgs = new SaveEventArgs(dataType); - if (scope.Events.DispatchCancelable(Saving, this, saveEventArgs)) - { - scope.Complete(); - return; - } - - // if preValues contain the data type, override the data type definition accordingly - if (values != null && values.ContainsKey(Constants.PropertyEditors.PreValueKeys.DataValueType)) - dataType.DatabaseType = PropertyValueEditor.GetDatabaseType(values[Constants.PropertyEditors.PreValueKeys.DataValueType].Value); - - dataType.CreatorId = userId; - - _dataTypeRepository.Save(dataType); // definition - _dataTypeRepository.AddOrUpdatePreValues(dataType, values); //prevalues - - saveEventArgs.CanCancel = false; - scope.Events.Dispatch(Saved, this, saveEventArgs); - Audit(AuditType.Save, "Save DataTypeDefinition performed by user", userId, dataType.Id); - - scope.Complete(); - } - } - /// /// Deletes an /// diff --git a/src/Umbraco.Core/Services/Implement/EntityService.cs b/src/Umbraco.Core/Services/Implement/EntityService.cs index e41cd17f72..09eab551ae 100644 --- a/src/Umbraco.Core/Services/Implement/EntityService.cs +++ b/src/Umbraco.Core/Services/Implement/EntityService.cs @@ -35,7 +35,7 @@ namespace Umbraco.Core.Services.Implement _objectTypes = new Dictionary, Func)> { - { typeof (IDataType).FullName, (UmbracoObjectTypes.DataType, dataTypeService.GetDataTypeDefinitionById, dataTypeService.GetDataTypeDefinitionById) }, + { typeof (IDataType).FullName, (UmbracoObjectTypes.DataType, dataTypeService.GetDataType, dataTypeService.GetDataType) }, { typeof (IContent).FullName, (UmbracoObjectTypes.Document, contentService.GetById, contentService.GetById) }, { typeof (IContentType).FullName, (UmbracoObjectTypes.DocumentType, contentTypeService.Get, contentTypeService.Get) }, { typeof (IMedia).FullName, (UmbracoObjectTypes.Media, mediaService.GetById, mediaService.GetById) }, diff --git a/src/Umbraco.Core/Services/Implement/PackagingService.cs b/src/Umbraco.Core/Services/Implement/PackagingService.cs index 376a654958..5263f3197e 100644 --- a/src/Umbraco.Core/Services/Implement/PackagingService.cs +++ b/src/Umbraco.Core/Services/Implement/PackagingService.cs @@ -684,7 +684,7 @@ namespace Umbraco.Core.Services.Implement { var dataTypeDefinitionId = new Guid(property.Element("Definition").Value);//Unique Id for a DataTypeDefinition - var dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(dataTypeDefinitionId); + var dataTypeDefinition = _dataTypeService.GetDataType(dataTypeDefinitionId); //If no DataTypeDefinition with the guid from the xml wasn't found OR the ControlId on the DataTypeDefinition didn't match the DataType Id //We look up a DataTypeDefinition that matches @@ -698,7 +698,7 @@ namespace Umbraco.Core.Services.Implement if (dataTypeDefinition == null) { - var dataTypeDefinitions = _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(propertyEditorAlias); + var dataTypeDefinitions = _dataTypeService.GetByEditorAlias(propertyEditorAlias); if (dataTypeDefinitions != null && dataTypeDefinitions.Any()) { dataTypeDefinition = dataTypeDefinitions.FirstOrDefault(); @@ -706,7 +706,7 @@ namespace Umbraco.Core.Services.Implement } else if (dataTypeDefinition.EditorAlias != propertyEditorAlias) { - var dataTypeDefinitions = _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(propertyEditorAlias); + var dataTypeDefinitions = _dataTypeService.GetByEditorAlias(propertyEditorAlias); if (dataTypeDefinitions != null && dataTypeDefinitions.Any()) { dataTypeDefinition = dataTypeDefinitions.FirstOrDefault(); @@ -724,7 +724,7 @@ namespace Umbraco.Core.Services.Implement property.Element("Type").Value.Trim())); //convert to a label! - dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(Constants.PropertyEditors.NoEditAlias).FirstOrDefault(); + dataTypeDefinition = _dataTypeService.GetByEditorAlias(Constants.PropertyEditors.NoEditAlias).FirstOrDefault(); //if for some odd reason this isn't there then ignore if (dataTypeDefinition == null) continue; } @@ -884,7 +884,7 @@ namespace Umbraco.Core.Services.Implement if (importedFolders.ContainsKey(dataTypeDefinitionName)) parentId = importedFolders[dataTypeDefinitionName]; - var definition = _dataTypeService.GetDataTypeDefinitionById(dataTypeDefinitionId); + var definition = _dataTypeService.GetDataType(dataTypeDefinitionId); //If the datatypedefinition doesn't already exist we create a new new according to the one in the package xml if (definition == null) { diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 942facddfd..1f34df8be6 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -313,6 +313,8 @@ + + diff --git a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs index 4318457811..5b1c83951a 100644 --- a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(Mock.Of( definition => definition.Id == 555 @@ -149,7 +149,7 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(Mock.Of( definition => definition.Id == 555 @@ -206,7 +206,7 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(Mock.Of( definition => definition.Id == 555 @@ -280,7 +280,7 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(Mock.Of( definition => definition.Id == 555 @@ -307,7 +307,7 @@ namespace Umbraco.Tests.Models.Mapping // setup the mocks to return the data we want to test against... - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(Mock.Of( definition => definition.Id == 555 @@ -516,7 +516,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new PropertyGroupBasic @@ -585,7 +585,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void PropertyGroupBasic_To_PropertyGroup() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new PropertyGroupBasic @@ -651,7 +651,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void MemberPropertyTypeBasic_To_PropertyType() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new MemberPropertyTypeBasic() @@ -685,7 +685,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void PropertyTypeBasic_To_PropertyType() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new PropertyTypeBasic() @@ -907,7 +907,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void MemberPropertyTypeBasic_To_MemberPropertyTypeDisplay() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new MemberPropertyTypeBasic() @@ -945,7 +945,7 @@ namespace Umbraco.Tests.Models.Mapping [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { - _dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny())) + _dataTypeService.Setup(x => x.GetDataType(It.IsAny())) .Returns(new DataType("test")); var basic = new PropertyTypeBasic() diff --git a/src/Umbraco.Tests/Models/Mapping/ContentWebModelMappingTests.cs b/src/Umbraco.Tests/Models/Mapping/ContentWebModelMappingTests.cs index 51ffd26e07..11f6b684b9 100644 --- a/src/Umbraco.Tests/Models/Mapping/ContentWebModelMappingTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/ContentWebModelMappingTests.cs @@ -224,7 +224,7 @@ namespace Umbraco.Tests.Models.Mapping Assert.AreEqual(p.PropertyType.ValidationRegExp, pDto.ValidationRegExp); Assert.AreEqual(p.PropertyType.Description, pDto.Description); Assert.AreEqual(p.PropertyType.Name, pDto.Label); - Assert.AreEqual(Current.Services.DataTypeService.GetDataTypeDefinitionById(p.PropertyType.DataTypeDefinitionId), pDto.DataType); + Assert.AreEqual(Current.Services.DataTypeService.GetDataType(p.PropertyType.DataTypeDefinitionId), pDto.DataType); Assert.AreEqual(Current.PropertyEditors[p.PropertyType.PropertyEditorAlias], pDto.PropertyEditor); } diff --git a/src/Umbraco.Tests/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs b/src/Umbraco.Tests/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs index e5e91edf5b..59f30c92ed 100644 --- a/src/Umbraco.Tests/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests/Persistence/Querying/ContentTypeRepositorySqlClausesTest.cs @@ -102,7 +102,7 @@ namespace Umbraco.Tests.Persistence.Querying .RightJoin() .On(left => left.Id, right => right.PropertyTypeGroupId) .InnerJoin() - .On(left => left.DataTypeId, right => right.DataTypeId); + .On(left => left.DataTypeId, right => right.NodeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); @@ -149,7 +149,7 @@ namespace Umbraco.Tests.Persistence.Querying .RightJoin() .On(left => left.Id, right => right.PropertyTypeGroupId) .InnerJoin() - .On(left => left.DataTypeId, right => right.DataTypeId) + .On(left => left.DataTypeId, right => right.NodeId) .Where(x => x.ContentTypeId == 1050); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); diff --git a/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs b/src/Umbraco.Tests/Persistence/Querying/ContentTypeSqlMappingTests.cs index 0cb0b5aa2a..795b2e6f7e 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, DataTypeId = 55555, EditorAlias = Constants.PropertyEditors.TextboxAlias, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = 44444, NodeId = 55555, EditorAlias = Constants.PropertyEditors.TextboxAlias, 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/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs b/src/Umbraco.Tests/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs index 953b333cf5..6b468c403e 100644 --- a/src/Umbraco.Tests/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs +++ b/src/Umbraco.Tests/Persistence/Querying/DataTypeDefinitionRepositorySqlClausesTest.cs @@ -27,7 +27,7 @@ namespace Umbraco.Tests.Persistence.Querying sql.SelectAll() .From() .InnerJoin() - .On(left => left.DataTypeId, right => right.NodeId) + .On(left => left.NodeId, right => right.NodeId) .Where(x => x.NodeObjectType == NodeObjectTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); diff --git a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs index b6940ac756..a625cc14d1 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/MemberRepositoryTest.cs @@ -339,7 +339,7 @@ namespace Umbraco.Tests.Persistence.Repositories .InnerJoin().On(left => left.NodeId, right => right.NodeId) .InnerJoin().On(left => left.NodeId, right => right.NodeId) .LeftJoin().On(left => left.ContentTypeId, right => right.ContentTypeId) - .LeftJoin().On(left => left.DataTypeId, right => right.DataTypeId) + .LeftJoin().On(left => left.NodeId, right => right.DataTypeId) .LeftJoin().On(left => left.PropertyTypeId, right => right.Id) .Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + ".versionId = uContentVersion.id") .Where(x => x.NodeObjectType == NodeObjectTypeId); @@ -357,7 +357,7 @@ namespace Umbraco.Tests.Persistence.Repositories .InnerJoin().On(left => left.NodeId, right => right.NodeId) .InnerJoin().On(left => left.NodeId, right => right.NodeId) .LeftJoin().On(left => left.ContentTypeId, right => right.ContentTypeId) - .LeftJoin().On(left => left.DataTypeId, right => right.DataTypeId) + .LeftJoin().On(left => left.NodeId, right => right.DataTypeId) .LeftJoin().On(left => left.PropertyTypeId, right => right.Id) .Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + ".versionId = uContentVersion.id") .Where(x => x.NodeObjectType == NodeObjectTypeId); diff --git a/src/Umbraco.Tests/Services/CachedDataTypeServiceTests.cs b/src/Umbraco.Tests/Services/CachedDataTypeServiceTests.cs index 63146f5b07..220a4a449b 100644 --- a/src/Umbraco.Tests/Services/CachedDataTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/CachedDataTypeServiceTests.cs @@ -24,9 +24,9 @@ namespace Umbraco.Tests.Services dataTypeService.Save(dataType); //Get all the first time (no cache) - var all = dataTypeService.GetAllDataTypeDefinitions(); + var all = dataTypeService.GetAll(); //Get all a second time (with cache) - all = dataTypeService.GetAllDataTypeDefinitions(); + all = dataTypeService.GetAll(); Assert.Pass(); } diff --git a/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs b/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs index 09591903ad..dbfc5cd0bb 100644 --- a/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentTypeServiceTests.cs @@ -470,7 +470,7 @@ namespace Umbraco.Tests.Services // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; - var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); + var dtdYesNo = ServiceContext.DataTypeService.GetDataType(-49); var ctBase = new ContentType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(dtdYesNo, Constants.Conventions.Content.NaviHide) { diff --git a/src/Umbraco.Tests/Services/DataTypeServiceTests.cs b/src/Umbraco.Tests/Services/DataTypeServiceTests.cs index 29560f59cc..cfb00fa9e2 100644 --- a/src/Umbraco.Tests/Services/DataTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/DataTypeServiceTests.cs @@ -31,7 +31,7 @@ namespace Umbraco.Tests.Services Assert.That(dataType, Is.Not.Null); Assert.That(dataType.HasIdentity, Is.True); - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); Assert.That(dataType, Is.Not.Null); } @@ -41,14 +41,14 @@ namespace Umbraco.Tests.Services // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = "Umbraco.Textbox"; - var dataTypeDefinitions = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(textfieldId); + var dataTypeDefinitions = dataTypeService.GetByEditorAlias(textfieldId); // Act var definition = dataTypeDefinitions.First(); var definitionId = definition.Id; dataTypeService.Delete(definition); - var deletedDefinition = dataTypeService.GetDataTypeDefinitionById(definitionId); + var deletedDefinition = dataTypeService.GetDataType(definitionId); // Assert Assert.That(deletedDefinition, Is.Null); @@ -75,7 +75,7 @@ namespace Umbraco.Tests.Services {"preVal2", new PreValue("World")} }); //re-get - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); // Assert @@ -104,7 +104,7 @@ namespace Umbraco.Tests.Services {"preVal2", new PreValue("World")} }); //re-get - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); // Assert @@ -133,7 +133,7 @@ namespace Umbraco.Tests.Services {"preVal2", new PreValue("World")} }); //re-get - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); //update them (ensure Ids are there!) @@ -170,7 +170,7 @@ namespace Umbraco.Tests.Services {"preVal2", new PreValue("World")} }); //re-get - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); //update them (ensure Ids are there!) @@ -202,7 +202,7 @@ namespace Umbraco.Tests.Services dataTypeService.SavePreValues(dataType.Id, new[] {"preVal1", "preVal2"}); //re-get - dataType = dataTypeService.GetDataTypeDefinitionById(dataType.Id); + dataType = dataTypeService.GetDataType(dataType.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); // Assert diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index 76e19eb452..ae684814ba 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -117,7 +117,7 @@ namespace Umbraco.Web.Editors Constants.Trees.MemberTypes, Constants.Trees.Members)] public ContentPropertyDisplay GetPropertyTypeScaffold(int id) { - var dataTypeDiff = Services.DataTypeService.GetDataTypeDefinitionById(id); + var dataTypeDiff = Services.DataTypeService.GetDataType(id); if (dataTypeDiff == null) { diff --git a/src/Umbraco.Web/Editors/DataTypeController.cs b/src/Umbraco.Web/Editors/DataTypeController.cs index b7d1c1bbb9..5290dd98d5 100644 --- a/src/Umbraco.Web/Editors/DataTypeController.cs +++ b/src/Umbraco.Web/Editors/DataTypeController.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.Editors /// public DataTypeDisplay GetByName(string name) { - var dataType = Services.DataTypeService.GetDataTypeDefinitionByName(name); + var dataType = Services.DataTypeService.GetDataType(name); return dataType == null ? null : Mapper.Map(dataType); } @@ -51,7 +51,7 @@ namespace Umbraco.Web.Editors /// public DataTypeDisplay GetById(int id) { - var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id); + var dataType = Services.DataTypeService.GetDataType(id); if (dataType == null) { throw new HttpResponseException(HttpStatusCode.NotFound); @@ -68,7 +68,7 @@ namespace Umbraco.Web.Editors [HttpPost] public HttpResponseMessage DeleteById(int id) { - var foundType = Services.DataTypeService.GetDataTypeDefinitionById(id); + var foundType = Services.DataTypeService.GetDataType(id); if (foundType == null) { throw new HttpResponseException(HttpStatusCode.NotFound); @@ -92,7 +92,7 @@ namespace Umbraco.Web.Editors /// a DataTypeDisplay public DataTypeDisplay GetCustomListView(string contentTypeAlias) { - var dt = Services.DataTypeService.GetDataTypeDefinitionByName(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); + var dt = Services.DataTypeService.GetDataType(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); if (dt == null) { throw new HttpResponseException(HttpStatusCode.NotFound); @@ -108,7 +108,7 @@ namespace Umbraco.Web.Editors /// public DataTypeDisplay PostCreateCustomListView(string contentTypeAlias) { - var dt = Services.DataTypeService.GetDataTypeDefinitionByName(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); + var dt = Services.DataTypeService.GetDataType(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); //if it doesnt exist yet, we will create it. if (dt == null) @@ -142,7 +142,7 @@ namespace Umbraco.Web.Editors } //we have a data type associated - var dataType = Services.DataTypeService.GetDataTypeDefinitionById(dataTypeId); + var dataType = Services.DataTypeService.GetDataType(dataTypeId); if (dataType == null) { throw new HttpResponseException(HttpStatusCode.NotFound); @@ -234,7 +234,7 @@ namespace Umbraco.Web.Editors /// public HttpResponseMessage PostMove(MoveOrCopy move) { - var toMove = Services.DataTypeService.GetDataTypeDefinitionById(move.Id); + var toMove = Services.DataTypeService.GetDataType(move.Id); if (toMove == null) { return Request.CreateResponse(HttpStatusCode.NotFound); @@ -288,7 +288,7 @@ namespace Umbraco.Web.Editors public IEnumerable GetAll() { return Services.DataTypeService - .GetAllDataTypeDefinitions() + .GetAll() .Select(Mapper.Map).Where(x => x.IsSystemDataType == false); } @@ -305,7 +305,7 @@ namespace Umbraco.Web.Editors public IDictionary> GetGroupedDataTypes() { var dataTypes = Services.DataTypeService - .GetAllDataTypeDefinitions() + .GetAll() .Select(Mapper.Map) .ToArray(); diff --git a/src/Umbraco.Web/Editors/DataTypeValidateAttribute.cs b/src/Umbraco.Web/Editors/DataTypeValidateAttribute.cs index 30abbf0ca7..918780f6aa 100644 --- a/src/Umbraco.Web/Editors/DataTypeValidateAttribute.cs +++ b/src/Umbraco.Web/Editors/DataTypeValidateAttribute.cs @@ -62,7 +62,7 @@ namespace Umbraco.Web.Editors switch (dataType.Action) { case ContentSaveAction.Save: - persisted = DataTypeService.GetDataTypeDefinitionById(Convert.ToInt32(dataType.Id)); + persisted = DataTypeService.GetDataType(Convert.ToInt32(dataType.Id)); if (persisted == null) { var message = string.Format("Data type with id: {0} was not found", dataType.Id); diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 897d9085e8..6466017394 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -173,7 +173,7 @@ namespace Umbraco.Web.Editors { int nId; if (int.TryParse(item, out nId) == false) continue; - var dtd = Services.DataTypeService.GetDataTypeDefinitionById(nId); + var dtd = Services.DataTypeService.GetDataType(nId); if (dtd != null) { removedDataTypes.Add(dtd); diff --git a/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs b/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs index 7540e9a955..18285b70a7 100644 --- a/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs +++ b/src/Umbraco.Web/Migrations/EnsureListViewDataTypeIsCreated.cs @@ -54,9 +54,9 @@ 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)))); - scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -26, DataTypeId = Constants.DataTypes.DefaultContentListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); - scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -27, DataTypeId = Constants.DataTypes.DefaultMediaListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); - scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -28, DataTypeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -26, NodeId = Constants.DataTypes.DefaultContentListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -27, NodeId = Constants.DataTypes.DefaultMediaListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); + scope.Database.Insert(Constants.DatabaseSchema.Tables.DataType, "pk", false, new DataTypeDto { PrimaryKey = -28, NodeId = Constants.DataTypes.DefaultMembersListView, EditorAlias = Constants.PropertyEditors.ListViewAlias, DbType = "Nvarchar" }); } finally { diff --git a/src/Umbraco.Web/Models/Mapping/ContentPropertyDtoConverter.cs b/src/Umbraco.Web/Models/Mapping/ContentPropertyDtoConverter.cs index 8192bd1a37..5a598eecbf 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentPropertyDtoConverter.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentPropertyDtoConverter.cs @@ -27,7 +27,7 @@ namespace Umbraco.Web.Models.Mapping propertyDto.Label = originalProperty.PropertyType.Name; //TODO: We should be able to look both of these up at the same time! - propertyDto.DataType = dataTypeService.GetDataTypeDefinitionById(originalProperty.PropertyType.DataTypeDefinitionId); + propertyDto.DataType = dataTypeService.GetDataType(originalProperty.PropertyType.DataTypeDefinitionId); propertyDto.PreValues = dataTypeService.GetPreValuesCollectionByDataTypeId(originalProperty.PropertyType.DataTypeDefinitionId); return propertyDto; diff --git a/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs index b7b72437ff..42ef50a32f 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs @@ -127,7 +127,7 @@ namespace Umbraco.Web.Models.Mapping if (string.IsNullOrEmpty(source.Name) == false) { var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Name; - if (_dataTypeService.GetDataTypeDefinitionByName(name) != null) + if (_dataTypeService.GetDataType(name) != null) dest.ListViewEditorName = name; } }); @@ -152,7 +152,7 @@ namespace Umbraco.Web.Models.Mapping if (string.IsNullOrEmpty(source.Alias) == false) { var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Alias; - if (_dataTypeService.GetDataTypeDefinitionByName(name) != null) + if (_dataTypeService.GetDataType(name) != null) dest.ListViewEditorName = name; } @@ -172,7 +172,7 @@ namespace Umbraco.Web.Models.Mapping .ConstructUsing(propertyTypeBasic => { - var dataType = _dataTypeService.GetDataTypeDefinitionById(propertyTypeBasic.DataTypeId); + var dataType = _dataTypeService.GetDataType(propertyTypeBasic.DataTypeId); if (dataType == null) throw new NullReferenceException("No data type found with id " + propertyTypeBasic.DataTypeId); return new PropertyType(dataType, propertyTypeBasic.Alias); }) diff --git a/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs b/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs index 0663d7d983..4c18040daa 100644 --- a/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/TabsAndPropertiesResolver.cs @@ -140,8 +140,8 @@ namespace Umbraco.Web.Models.Mapping } //first try to get the custom one if there is one - var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName) - ?? dataTypeService.GetDataTypeDefinitionById(dtdId); + var dt = dataTypeService.GetDataType(customDtdName) + ?? dataTypeService.GetDataType(dtdId); if (dt == null) { diff --git a/src/Umbraco.Web/PropertyEditors/DateTimeValidator.cs b/src/Umbraco.Web/PropertyEditors/DateTimeValidator.cs index b841727faf..106457885a 100644 --- a/src/Umbraco.Web/PropertyEditors/DateTimeValidator.cs +++ b/src/Umbraco.Web/PropertyEditors/DateTimeValidator.cs @@ -12,7 +12,7 @@ namespace Umbraco.Web.PropertyEditors /// internal class DateTimeValidator : IPropertyValidator { - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { //don't validate if empty if (value == null || value.ToString().IsNullOrWhiteSpace()) diff --git a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs index 1226f2d0c8..758bf956f8 100644 --- a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs @@ -90,7 +90,7 @@ namespace Umbraco.Web.PropertyEditors #region DataType Configuration - public class DataTypeConfiguration + public class Configuration { public NestedContentType[] ContentTypes { get; set; } public int? MinItems { get; set; } @@ -110,20 +110,23 @@ namespace Umbraco.Web.PropertyEditors } } - public override object MapDataTypeConfiguration(PreValueCollection preValues) + public override object DeserializeConfiguration(string json) { - var d = preValues.PreValuesAsDictionary; - return new DataTypeConfiguration - { - 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" - }; + 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 diff --git a/src/Umbraco.Web/PropertyEditors/SliderPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/SliderPropertyEditor.cs index e71165cec3..24ea1906b6 100644 --- a/src/Umbraco.Web/PropertyEditors/SliderPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/SliderPropertyEditor.cs @@ -21,7 +21,6 @@ namespace Umbraco.Web.PropertyEditors internal class SliderPreValueEditor : PreValueEditor { - [PreValueField("enableRange", "Enable range", "boolean")] public string Range { get; set; } diff --git a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs index 7f430dda55..9134147d4a 100644 --- a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs +++ b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs @@ -17,7 +17,7 @@ namespace Umbraco.Web.PropertyEditors { internal class UploadFileTypeValidator : IPropertyValidator { - public IEnumerable Validate(object value, PreValueCollection preValues, PropertyEditor editor) + public IEnumerable Validate(object value, object dataTypeConfiguration, PropertyEditor editor) { //now check the file type diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerLegacyValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerLegacyValueConverter.cs index 6ce3385f2e..4cd0094725 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerLegacyValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerLegacyValueConverter.cs @@ -70,7 +70,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters if (nodeIds.Length > 0) { - var error = $"Data type \"{_services.DataTypeService.GetDataTypeDefinitionById(propertyType.DataType.Id).Name}\" is not set to allow multiple items but appears to contain multiple items, check the setting and save the data type again"; + var error = $"Data type \"{_services.DataTypeService.GetDataType(propertyType.DataType.Id).Name}\" is not set to allow multiple items but appears to contain multiple items, check the setting and save the data type again"; _logger.Warn(error); throw new Exception(error); diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentManyValueConverter.cs index 6e882ddc16..afc57a7341 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.GetConfiguration().ContentTypes; + var contentTypes = propertyType.DataType.GetConfiguration().ContentTypes; return contentTypes.Length > 1 ? typeof (IEnumerable) : typeof (IEnumerable<>).MakeGenericType(ModelType.For(contentTypes[0].Alias)); @@ -62,7 +62,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters if (objects.Count == 0) return Enumerable.Empty(); - var contentTypes = propertyType.DataType.GetConfiguration().ContentTypes; + var contentTypes = propertyType.DataType.GetConfiguration().ContentTypes; var elements = contentTypes.Length > 1 ? new List() : PublishedModelFactory.CreateModelList(contentTypes[0].Alias); diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/NestedContentSingleValueConverter.cs index 8d74bb0fef..16fd697054 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.GetConfiguration().ContentTypes; + var contentTypes = propertyType.DataType.GetConfiguration().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 b1eb59a164..fb28e534a0 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.GetConfiguration(); + var config = publishedProperty.DataType.GetConfiguration(); return config.MinItems == 1 && config.MaxItems == 1; } diff --git a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/InstalledPackage.cs b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/InstalledPackage.cs index 1c7e833cb5..a358c69389 100644 --- a/src/Umbraco.Web/_Legacy/Packager/PackageInstance/InstalledPackage.cs +++ b/src/Umbraco.Web/_Legacy/Packager/PackageInstance/InstalledPackage.cs @@ -145,7 +145,7 @@ namespace umbraco.cms.businesslogic.packager { var macros = TryGetIntegerIds(Data.Macros).Select(macroService.GetById).ToList(); var templates = TryGetIntegerIds(Data.Templates).Select(fileService.GetTemplate).ToList(); var contentTypes = TryGetIntegerIds(Data.Documenttypes).Select(contentTypeService.Get).ToList(); // fixme - media types? - var dataTypes = TryGetIntegerIds(Data.DataTypes).Select(dataTypeService.GetDataTypeDefinitionById).ToList(); + var dataTypes = TryGetIntegerIds(Data.DataTypes).Select(dataTypeService.GetDataType).ToList(); var dictionaryItems = TryGetIntegerIds(Data.DictionaryItems).Select(localizationService.GetDictionaryItemById).ToList(); var languages = TryGetIntegerIds(Data.Languages).Select(localizationService.GetLanguageById).ToList();