DataType refactoring

This commit is contained in:
Stephan
2018-01-15 17:32:45 +01:00
parent 2f7f22961b
commit e30d8f79ef
62 changed files with 516 additions and 926 deletions
@@ -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()
+1 -1
View File
@@ -16,7 +16,7 @@ namespace Umbraco.Core.Migrations
/// <summary>
/// Provides a base class to all migrations.
/// </summary>
public abstract class MigrationBase : IMigration
public abstract partial class MigrationBase : IMigration
{
/// <summary>
/// Initializes a new instance of the <see cref="MigrationBase"/> class.
@@ -0,0 +1,60 @@
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Core.Migrations
{
/// <summary>
/// Provides a base class to all migrations.
/// </summary>
public abstract partial class MigrationBase
{
// provides extra methods for migrations
protected void AddColumn<T>(string tableName, string columnName)
{
AddColumn<T>(tableName, columnName, out var sqls);
foreach (var sql in sqls) Database.Execute(sql);
}
protected void AddColumn<T>(string tableName, string columnName, out IEnumerable<string> 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<T>(string tableName, string currentName, string newName)
{
AddColumn<T>(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;
}
}
}
@@ -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<AddContentNuTable>("{CBFF58A2-7B50-4F75-8E98-249920DB0F37}")
.Chain<RefactorXmlColumns>("{3D18920C-E84D-405C-A06A-B7CEE52FE5DD}")
.Chain<VariantsMigration>("{FB0A5429-587E-4BD0-8A67-20F0E7E62FF7}")
.Chain<DropMigrationsTable>("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}");
.Chain<DropMigrationsTable>("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}")
.Chain<RefactorDataType>("{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<VariantsMigration>("{6550C7E8-77B7-4DE3-9B58-E31C81CB9504}");
Chain<DropMigrationsTable>("{E3388F73-89FA-45FE-A539-C7FACC8D63DD}");
Chain<RefactorDataType>("{82C4BA1D-7720-46B1-BBD7-07F3F73800E6}");
}
}
}
@@ -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<DataTypeDto>("cmsDataType", "config");
// rename the table
Rename.Table("cmsDataType").To(Constants.DatabaseSchema.Tables.Document).Do();
// recreate all keys and indexes
Create.KeysAndIndexes<DataTypeDto>().Do();
var sql = Sql()
.Select<DataTypeDto>()
.AndSelect<PreValueDto>()
.From<DataTypeDto>()
.InnerJoin<PreValueDto>().On<DataTypeDto, PreValueDto>((left, right) => left.NodeId == right.NodeId)
.OrderBy<DataTypeDto>(x => x.NodeId)
.AndBy<PreValueDto>(x => x.SortOrder);
var dtos = Database.Fetch<PreValueDto>(sql).GroupBy(x => x.NodeId);
foreach (var group in dtos)
{
var dataType = Database.Fetch<DataTypeDto>(Sql()
.Select<DataTypeDto>()
.From<DataTypeDto>()
.Where<DataTypeDto>(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<string, object> { ["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; }
}
}
}
@@ -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<T>(string tableName, string columnName)
{
AddColumn<T>(tableName, columnName, out var sqls);
foreach (var sql in sqls) Database.Execute(sql);
}
private void AddColumn<T>(string tableName, string columnName, out IEnumerable<string> 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<T>(string tableName, string currentName, string newName)
{
AddColumn<T>(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;
}
}
}
+47 -13
View File
@@ -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<PropertySelectors> Ps = new Lazy<PropertySelectors>();
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;
/// <summary>
/// Initializes a new instance of the <see cref="DataType"/> class.
@@ -25,7 +28,7 @@ namespace Umbraco.Core.Models
public DataType(int parentId, string propertyEditorAlias)
{
ParentId = parentId;
_propertyEditorAlias = propertyEditorAlias;
_editorAlias = propertyEditorAlias;
}
/// <summary>
@@ -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<DataType, string>(x => x.EditorAlias);
public readonly PropertyInfo DatabaseTypeSelector = ExpressionHelper.GetPropertyInfo<DataType, DataTypeDatabaseType>(x => x.DatabaseType);
public readonly PropertyInfo EditorAlias = ExpressionHelper.GetPropertyInfo<DataType, string>(x => x.EditorAlias);
public readonly PropertyInfo DatabaseType = ExpressionHelper.GetPropertyInfo<DataType, DataTypeDatabaseType>(x => x.DatabaseType);
public readonly PropertyInfo Configuration = ExpressionHelper.GetPropertyInfo<DataType, object>(x => x.Configuration);
}
/// <inheritdoc />
[DataMember]
public string EditorAlias
{
get => _propertyEditorAlias;
set => SetPropertyValueAndDetectChanges(value, ref _propertyEditorAlias, Ps.Value.PropertyEditorAliasSelector);
get => _editorAlias;
set => SetPropertyValueAndDetectChanges(value, ref _editorAlias, Selectors.EditorAlias);
}
/// <inheritdoc />
@@ -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 !!
/// <inheritdoc />
[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;
}
}
/// <inheritdoc /> // fixme on interface!?
public void SetConfiguration(string configurationJson, PropertyEditor editor)
{
_hasConfiguration = false;
_configuration = null;
_configurationJson = configurationJson;
_editor = editor;
OnPropertyChanged(Selectors.Configuration);
}
}
}
@@ -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);
}
}
}
@@ -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";
@@ -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; }
@@ -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
@@ -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<DataTypeDefinition,DataTypeDto>
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<DataTypeDatabaseType>(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<DataTypeDatabaseType>(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;
}
@@ -6,12 +6,6 @@ namespace Umbraco.Core.Persistence.Repositories
{
public interface IDataTypeRepository : IReadWriteQueryRepository<int, IDataType>
{
PreValueCollection GetPreValuesCollectionByDataTypeId(int dataTypeId);
string GetPreValueAsString(int preValueId);
void AddOrUpdatePreValues(IDataType dataType, IDictionary<string, PreValue> values);
void AddOrUpdatePreValues(int dataTypeId, IDictionary<string, PreValue> values);
IEnumerable<MoveEventInfo<IDataType>> Move(IDataType toMove, EntityContainer container);
}
}
@@ -100,7 +100,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.RightJoin<PropertyTypeDto>()
.On<PropertyTypeGroupDto, PropertyTypeDto>(left => left.Id, right => right.PropertyTypeGroupId)
.InnerJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId);
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId);
var translator = new SqlTranslator<PropertyType>(sqlClause, query);
// fixme v8 are we sorting only for 7.6 relators?
@@ -472,7 +472,7 @@ AND umbracoNode.id <> @id",
.LeftJoin<PropertyTypeDto>()
.On<PropertyTypeGroupDto, PropertyTypeDto>(left => left.Id, right => right.PropertyTypeGroupId)
.LeftJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId)
.Where<PropertyTypeGroupDto>(x => x.ContentTypeNodeId == id)
.OrderBy<PropertyTypeGroupDto>(x => x.Id);
@@ -491,7 +491,7 @@ AND umbracoNode.id <> @id",
.SelectAll()
.From<PropertyTypeDto>()
.InnerJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId)
.Where<PropertyTypeDto>(x => x.ContentTypeId == id);
var dtos = Database.Fetch<PropertyTypeDto>(sql);
@@ -554,12 +554,12 @@ AND umbracoNode.id <> @id",
.SelectAll()
.From<DataTypeDto>()
.Where("propertyEditorAlias = @propertyEditorAlias", new { propertyEditorAlias = propertyType.PropertyEditorAlias })
.OrderBy<DataTypeDto>(typeDto => typeDto.DataTypeId);
.OrderBy<DataTypeDto>(typeDto => typeDto.NodeId);
var datatype = Database.FirstOrDefault<DataTypeDto>(sql);
//we cannot assign a data type if one was not found
if (datatype != null)
{
propertyType.DataTypeDefinitionId = datatype.DataTypeId;
propertyType.DataTypeDefinitionId = datatype.NodeId;
}
else
{
@@ -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
/// </summary>
internal class DataTypeRepository : NPocoRepositoryBase<int, IDataType>, 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<int,DataTypeDefinition>
protected override IDataType PerformGet(int id)
{
return GetMany(new[] { id }).FirstOrDefault();
return GetMany(id).FirstOrDefault();
}
protected override IEnumerable<IDataType> 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<DataTypeDto>(dataTypeSql);
return dtos.Select(factory.BuildEntity).ToArray();
return dtos.Select(x => DataTypeFactory.BuildEntity(x, _editors[x.EditorAlias])).ToArray();
}
protected override IEnumerable<IDataType> PerformGetByQuery(IQuery<IDataType> query)
{
var factory = new DataTypeFactory(NodeObjectTypeId);
var sqlClause = GetBaseQuery(false);
var translator = new SqlTranslator<IDataType>(sqlClause, query);
var sql = translator.Translate();
var dtos = Database.Fetch<DataTypeDto>(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<DataTypeDto>()
.InnerJoin<NodeDto>()
.On<DataTypeDto, NodeDto>(left => left.DataTypeId, right => right.NodeId)
.On<DataTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(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<NodeDto>("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<DataTypeDto>("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<PropertyTypeDto>("WHERE id = @Id", new { Id = dto.Id });
}
//Delete the pre-values
Database.Delete<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new { Id = entity.Id });
//Delete Content specific data
Database.Delete<DataTypeDto>("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<PreValueCollection>(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<DataTypePreValueDto>("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<string, PreValue> values)
{
var dtd = Get(dataTypeId);
if (dtd == null)
{
throw new InvalidOperationException("No data type found with id " + dataTypeId);
}
AddOrUpdatePreValues(dtd, values);
}
public IEnumerable<MoveEventInfo<IDataType>> Move(IDataType toMove, EntityContainer container)
{
var parentId = -1;
@@ -322,90 +273,6 @@ AND umbracoNode.id <> @id",
return moveInfo;
}
public void AddOrUpdatePreValues(IDataType dataType, IDictionary<string, PreValue> 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<DataTypePreValueDto>()
.Where<DataTypePreValueDto>(dto => dto.DataTypeNodeId == dataType.Id)
.OrderBy<DataTypePreValueDto>(dto => dto.SortOrder);
currentVals = Database.Fetch<DataTypePreValueDto>(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<PreValueCollection>(key, () =>
{
var dtos = Database.Fetch<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new { Id = dataTypeId });
var list = dtos.Select(x => new Tuple<PreValue, string, int>(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);
}
/// <summary>
/// Private class to handle pre-value crud based on units of work with transactions
/// </summary>
private class PreValueEntity : EntityBase
{
public string Value { get; set; }
public string Alias { get; set; }
public IDataType DataType { get; set; }
public int SortOrder { get; set; }
}
/// <summary>
/// Private class to handle pre-value crud based on standard principles and units of work with transactions
/// </summary>
private class DataTypePreValueRepository : NPocoRepositoryBase<int, PreValueEntity>
{
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<PreValueEntity> PerformGetAll(params int[] ids)
{
throw new NotImplementedException();
}
protected override IEnumerable<PreValueEntity> PerformGetByQuery(IQuery<PreValueEntity> query)
{
throw new NotImplementedException();
}
protected override Sql<ISqlContext> GetBaseQuery(bool isCount)
{
throw new NotImplementedException();
}
protected override string GetBaseWhereClause()
{
throw new NotImplementedException();
}
protected override IEnumerable<string> GetDeleteClauses()
{
return Array.Empty<string>();
}
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<string, PreValue> 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<string, PreValue> 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
{
/// <summary>
/// Converts the tuple to a pre-value collection
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal static PreValueCollection ConvertToPreValuesCollection(IEnumerable<Tuple<PreValue, string, int>> list)
{
//now we need to determine if they are dictionary based, otherwise they have to be array based
var dictionary = new Dictionary<string, PreValue>();
//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);
}
}
}
}
@@ -370,7 +370,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.Select<PropertyDataDto>(r => r.Select(x => x.PropertyTypeDto, r1 => r1.Select(x => x.DataTypeDto)))
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>().On<PropertyDataDto, PropertyTypeDto>((left, right) => left.PropertyTypeId == right.Id)
.InnerJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>((left, right) => left.DataTypeId == right.DataTypeId)
.InnerJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>((left, right) => left.DataTypeId == right.NodeId)
.Where<PropertyDataDto>(x => x.VersionId == versionId);
}
@@ -380,7 +380,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.Select<PropertyDataDto>(r => r.Select(x => x.PropertyTypeDto, r1 => r1.Select(x => x.DataTypeDto)))
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>().On<PropertyDataDto, PropertyTypeDto>((left, right) => left.PropertyTypeId == right.Id)
.InnerJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>((left, right) => left.DataTypeId == right.DataTypeId)
.InnerJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>((left, right) => left.DataTypeId == right.NodeId)
.WhereIn<PropertyDataDto>(x => x.VersionId, versionIds)
.OrderBy<PropertyDataDto>(x => x.VersionId);
}
@@ -161,7 +161,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.InnerJoin<MemberDto>().On<ContentDto, MemberDto>((left, right) => left.NodeId == right.NodeId)
.LeftJoin<PropertyTypeDto>().On<ContentDto, PropertyTypeDto>(left => left.ContentTypeId, right => right.ContentTypeId)
.LeftJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.LeftJoin<DataTypeDto>().On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId)
.LeftJoin<PropertyDataDto>().On(x => x
.Where<PropertyDataDto, PropertyTypeDto>((left, right) => left.PropertyTypeId == right.Id)
@@ -155,7 +155,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.InnerJoin<ContentTypeDto>().On<ContentTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, NodeDto>(left => left.ContentTypeId, right => right.NodeId)
.LeftJoin<MemberTypeDto>().On<MemberTypeDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId)
.LeftJoin<PropertyTypeGroupDto>().On<PropertyTypeGroupDto, NodeDto>(left => left.ContentTypeNodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
@@ -170,7 +170,7 @@ namespace Umbraco.Core.Persistence.Repositories.Implement
.InnerJoin<ContentTypeDto>().On<ContentTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, NodeDto>(left => left.ContentTypeId, right => right.NodeId)
.LeftJoin<MemberTypeDto>().On<MemberTypeDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId)
.LeftJoin<PropertyTypeGroupDto>().On<PropertyTypeGroupDto, NodeDto>(left => left.ContentTypeNodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
return sql;
@@ -10,21 +10,21 @@ namespace Umbraco.Core.PropertyEditors
[ValueValidator("Decimal")]
internal sealed class DecimalValidator : ManifestValueValidator, IPropertyValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
/// <inheritdoc />
public override IEnumerable<ValidationResult> Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor)
{
if (value != null && value.ToString() != string.Empty)
{
var result = value.TryConvertTo<decimal>();
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<decimal>();
if (result.Success == false)
yield return new ValidationResult("The value " + value + " is not a valid decimal", new[] { "value" });
}
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
/// <inheritdoc />
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
return Validate(value, "", preValues, editor);
return Validate(value, "", dataTypeConfiguration, editor);
}
}
}
@@ -14,24 +14,17 @@ namespace Umbraco.Core.PropertyEditors
[ValueValidator("Delimited")]
internal sealed class DelimitedManifestValueValidator : ManifestValueValidator
{
/// <summary>
/// Performs the validation
/// </summary>
/// <param name="value"></param>
/// <param name="config">Can be a json formatted string containing properties: 'delimiter' and 'pattern'</param>
/// <param name="preValues">The current pre-values stored for the data type</param>
/// <param name="editor"></param>
/// <returns></returns>
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
/// <inheritdoc />
public override IEnumerable<ValidationResult> 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<JObject>(config);
var json = JsonConvert.DeserializeObject<JObject>(validatorConfiguration);
if (json["delimiter"] != null)
{
delimiter = json["delimiter"].ToString();
@@ -10,7 +10,8 @@ namespace Umbraco.Core.PropertyEditors
[ValueValidator("Email")]
internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
/// <inheritdoc />
public override IEnumerable<ValidationResult> Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor)
{
var asString = value.ToString();
@@ -23,9 +24,10 @@ namespace Umbraco.Core.PropertyEditors
}
}
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
/// <inheritdoc />
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
return this.Validate(value, null, preValues, editor);
return this.Validate(value, null, dataTypeConfiguration, editor);
}
}
}
@@ -5,24 +5,19 @@ using Umbraco.Core.Models;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// An interface defining a validator
/// Defines a property validator.
/// </summary>
public interface IPropertyValidator
{
/// <summary>
/// Validates the object with the resolved ValueValidator found for this type
/// Validates.
/// </summary>
/// <param name="value">
/// 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.
/// </param>
/// <param name="preValues">
/// 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.
/// </param>
/// <param name="editor">The property editor instance that we are validating for</param>
/// <returns></returns>
IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor);
/// <param name="value">The value to validate. Can be a json structure (JObject, JArray, etc...), could be a single string, representing an editor's model.</param>
/// <param name="dataTypeConfiguration">The data type configuration.</param>
/// <param name="editor">The property editor.</param>
/// <returns>Validation results.</returns>
/// <remarks>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.</remarks>
IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor);
}
}
@@ -10,7 +10,7 @@ namespace Umbraco.Core.PropertyEditors
[ValueValidator("Integer")]
internal sealed class IntegerValidator : ManifestValueValidator, IPropertyValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
public override IEnumerable<ValidationResult> 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<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
return Validate(value, "", preValues, editor);
return Validate(value, "", dataTypeConfiguration, editor);
}
}
}
@@ -54,13 +54,9 @@ namespace Umbraco.Core.PropertyEditors
/// <summary>
/// Validates the object with the resolved ValueValidator found for this type
/// </summary>
/// <param name="value"></param>
/// <param name="preValues">The current pre-values stored for the data type</param>
/// <param name="editor">The property editor instance that we are validating for</param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
return ValidatorInstance.Validate(value, Config, preValues, editor);
return ValidatorInstance.Validate(value, Config, dataTypeConfiguration, editor);
}
}
}
@@ -6,41 +6,30 @@ using Umbraco.Core.Models;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// 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.
/// </summary>
public abstract class ManifestValueValidator
{
protected ManifestValueValidator()
{
var att = this.GetType().GetCustomAttribute<ValueValidatorAttribute>(false);
var att = GetType().GetCustomAttribute<ValueValidatorAttribute>(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; }
/// <summary>
/// Performs the validation against the value
/// Validates.
/// </summary>
/// <param name="value">
/// 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.
/// </param>
/// <param name="config">
/// 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.
/// </param>
/// <param name="preValues">The current pre-values stored for the data type</param>
/// <param name="editor">The property editor instance that is being validated</param>
/// <returns>
/// 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.
/// </returns>
public abstract IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor);
/// <param name="value">The value to validate. Can be a json structure (JObject, JArray, etc...), could be a single string, representing an editor's model.</param>
/// <param name="validatorConfiguration">The validator configuration, defined in the manifest.</param>
/// <param name="dataTypeConfiguration">The data type configuration.</param>
/// <param name="editor">The property editor.</param>
/// <returns>Validation results.</returns>
/// <remarks>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.</remarks>
public abstract IEnumerable<ValidationResult> Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor);
}
}
@@ -26,52 +26,50 @@ namespace Umbraco.Core.PropertyEditors
var fields = new List<PreValueField>();
//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<PreValueFieldAttribute>().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<PreValueEditor>(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<PreValueEditor>(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<string, PreValue> ConvertEditorToDb(IDictionary<string, object> 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()));
}
/// <summary>
@@ -187,28 +187,11 @@ namespace Umbraco.Core.PropertyEditors
}
/// <summary>
/// Maps a preValues collection to a strongly typed object.
/// Maps configuration to a strongly typed object.
/// </summary>
/// <param name="preValues">The preValues collection.</param>
/// <returns>A strongly typed object.</returns>
/// <remarks>
/// <para>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.</para>
/// <para>Otherwise, by default, this method will convert to a Dictionary{string, string}.</para>
/// <para>fixme - is this temp?</para>
/// </remarks>
public virtual object MapDataTypeConfiguration(PreValueCollection preValues)
public virtual object DeserializeConfiguration(string json)
{
var asDictionary = preValues.IsDictionaryBased
? preValues.PreValuesAsDictionary
: preValues.FormatAsDictionary();
var configuration = new Dictionary<string, string>();
foreach (var kvp in asDictionary)
configuration[kvp.Key] = kvp.Value.Value;
return configuration;
return JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
}
}
@@ -27,18 +27,17 @@ namespace Umbraco.Core.PropertyEditors
/// <param name="regex"></param>
public RegexValidator(string regex)
{
if (regex == null) throw new ArgumentNullException("regex");
_regex = regex;
_regex = regex ?? throw new ArgumentNullException(nameof(regex));
}
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
public override IEnumerable<ValidationResult> 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
/// <param name="preValues"></param>
/// <param name="editor"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
public IEnumerable<ValidationResult> 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);
}
}
}
@@ -10,7 +10,7 @@ namespace Umbraco.Core.PropertyEditors
[ValueValidator("Required")]
internal sealed class RequiredManifestValueValidator : ManifestValueValidator
{
public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor)
public override IEnumerable<ValidationResult> Validate(object value, string validatorConfiguration, object dataTypeConfiguration, PropertyEditor editor)
{
//TODO: localize these!
@@ -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))
@@ -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
+5 -57
View File
@@ -24,28 +24,28 @@ namespace Umbraco.Core.Services
/// </summary>
/// <param name="name">Name of the <see cref="IDataType"/></param>
/// <returns><see cref="IDataType"/></returns>
IDataType GetDataTypeDefinitionByName(string name);
IDataType GetDataType(string name);
/// <summary>
/// Gets a <see cref="IDataType"/> by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IDataType"/></param>
/// <returns><see cref="IDataType"/></returns>
IDataType GetDataTypeDefinitionById(int id);
IDataType GetDataType(int id);
/// <summary>
/// Gets a <see cref="IDataType"/> by its unique guid Id
/// </summary>
/// <param name="id">Unique guid Id of the DataType</param>
/// <returns><see cref="IDataType"/></returns>
IDataType GetDataTypeDefinitionById(Guid id);
IDataType GetDataType(Guid id);
/// <summary>
/// Gets all <see cref="IDataType"/> objects or those with the ids passed in
/// </summary>
/// <param name="ids">Optional array of Ids</param>
/// <returns>An enumerable list of <see cref="IDataType"/> objects</returns>
IEnumerable<IDataType> GetAllDataTypeDefinitions(params int[] ids);
IEnumerable<IDataType> GetAll(params int[] ids);
/// <summary>
/// Saves an <see cref="IDataType"/>
@@ -85,60 +85,8 @@ namespace Umbraco.Core.Services
/// </summary>
/// <param name="propertyEditorAlias">Alias of the property editor</param>
/// <returns>Collection of <see cref="IDataType"/> objects with a matching contorl id</returns>
IEnumerable<IDataType> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias);
/// <summary>
/// Gets all values for an <see cref="IDataType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IDataType"/> to retrieve prevalues from</param>
/// <returns>An enumerable list of string values</returns>
IEnumerable<string> GetPreValuesByDataTypeId(int id);
/// <summary>
/// Gets a pre-value collection by data type id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
PreValueCollection GetPreValuesCollectionByDataTypeId(int id);
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of string values to save</param>
[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<string> values);
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of key/value pairs to save</param>
void SavePreValues(int dataTypeId, IDictionary<string, PreValue> values);
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataType">The DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of key/value pairs to save</param>
void SavePreValues(IDataType dataType, IDictionary<string, PreValue> values);
/// <summary>
/// Saves the data type and it's prevalues
/// </summary>
/// <param name="dataType"></param>
/// <param name="values"></param>
/// <param name="userId"></param>
void SaveDataTypeAndPreValues(IDataType dataType, IDictionary<string, PreValue> values, int userId = 0);
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
string GetPreValueAsString(int id);
IEnumerable<IDataType> GetByEditorAlias(string propertyEditorAlias);
Attempt<OperationResult<MoveOperationStatusType>> Move(IDataType toMove, int parentId);
}
}
@@ -223,7 +223,7 @@ namespace Umbraco.Core.Services.Implement
/// </summary>
/// <param name="name">Name of the <see cref="IDataType"/></param>
/// <returns><see cref="IDataType"/></returns>
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
/// </summary>
/// <param name="id">Id of the <see cref="IDataType"/></param>
/// <returns><see cref="IDataType"/></returns>
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
/// </summary>
/// <param name="id">Unique guid Id of the DataType</param>
/// <returns><see cref="IDataType"/></returns>
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
/// </summary>
/// <param name="propertyEditorAlias">Alias of the property editor</param>
/// <returns>Collection of <see cref="IDataType"/> objects with a matching contorl id</returns>
public IEnumerable<IDataType> GetDataTypeDefinitionByPropertyEditorAlias(string propertyEditorAlias)
public IEnumerable<IDataType> GetByEditorAlias(string propertyEditorAlias)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -277,7 +277,7 @@ namespace Umbraco.Core.Services.Implement
/// </summary>
/// <param name="ids">Optional array of Ids</param>
/// <returns>An enumerable list of <see cref="IDataType"/> objects</returns>
public IEnumerable<IDataType> GetAllDataTypeDefinitions(params int[] ids)
public IEnumerable<IDataType> GetAll(params int[] ids)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
@@ -285,48 +285,6 @@ namespace Umbraco.Core.Services.Implement
}
}
/// <summary>
/// Gets all prevalues for an <see cref="IDataType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IDataType"/> to retrieve prevalues from</param>
/// <returns>An enumerable list of string values</returns>
public IEnumerable<string> 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();
}
}
/// <summary>
/// Returns the PreValueCollection for the specified data type
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public PreValueCollection GetPreValuesCollectionByDataTypeId(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _dataTypeRepository.GetPreValuesCollectionByDataTypeId(id);
}
}
/// <summary>
/// Gets a specific PreValue by its Id
/// </summary>
/// <param name="id">Id of the PreValue to retrieve the value from</param>
/// <returns>PreValue as a string</returns>
public string GetPreValueAsString(int id)
{
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _dataTypeRepository.GetPreValueAsString(id);
}
}
public Attempt<OperationResult<MoveOperationStatusType>> Move(IDataType toMove, int parentId)
{
@@ -447,107 +405,6 @@ namespace Umbraco.Core.Services.Implement
}
}
/// <summary>
/// Saves a list of PreValues for a given DataTypeDefinition
/// </summary>
/// <param name="dataTypeId">Id of the DataTypeDefinition to save PreValues for</param>
/// <param name="values">List of string values to save</param>
[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<string> 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<object>(
"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();
}
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataTypeId"></param>
/// <param name="values"></param>
/// <remarks>
/// 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'
/// </remarks>
public void SavePreValues(int dataTypeId, IDictionary<string, PreValue> values)
{
var dtd = GetDataTypeDefinitionById(dataTypeId);
if (dtd == null)
throw new InvalidOperationException("No data type found for id " + dataTypeId);
SavePreValues(dtd, values);
}
/// <summary>
/// Saves/updates the pre-values
/// </summary>
/// <param name="dataType"></param>
/// <param name="values"></param>
/// <remarks>
/// 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'
/// </remarks>
public void SavePreValues(IDataType dataType, IDictionary<string, PreValue> 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();
}
}
/// <summary>
/// This will save a data type and it's pre-values in one transaction
/// </summary>
/// <param name="dataType"></param>
/// <param name="values"></param>
/// <param name="userId"></param>
public void SaveDataTypeAndPreValues(IDataType dataType, IDictionary<string, PreValue> values, int userId = 0)
{
using (var scope = ScopeProvider.CreateScope())
{
var saveEventArgs = new SaveEventArgs<IDataType>(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();
}
}
/// <summary>
/// Deletes an <see cref="IDataType"/>
/// </summary>
@@ -35,7 +35,7 @@ namespace Umbraco.Core.Services.Implement
_objectTypes = new Dictionary<string, (UmbracoObjectTypes, Func<int, IUmbracoEntity>, Func<Guid, IUmbracoEntity>)>
{
{ 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) },
@@ -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)
{
+2
View File
@@ -313,6 +313,8 @@
<Compile Include="Constants-Web.cs" />
<Compile Include="Constants.cs" />
<Compile Include="KeyValuePairExtensions.cs" />
<Compile Include="Migrations\MigrationBase_Extra.cs" />
<Compile Include="Migrations\Upgrade\V_8_0_0\RefactorDataType.cs" />
<Compile Include="Models\ContentTypeBaseExtensions.cs" />
<Compile Include="Models\Editors\ContentPropertyFile.cs" />
<Compile Include="Models\Entities\BeingDirty.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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(Mock.Of<IDataType>(
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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType("test"));
var basic = new PropertyGroupBasic<MemberPropertyTypeBasic>
@@ -585,7 +585,7 @@ namespace Umbraco.Tests.Models.Mapping
[Test]
public void PropertyGroupBasic_To_PropertyGroup()
{
_dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType("test"));
var basic = new PropertyGroupBasic<PropertyTypeBasic>
@@ -651,7 +651,7 @@ namespace Umbraco.Tests.Models.Mapping
[Test]
public void MemberPropertyTypeBasic_To_PropertyType()
{
_dataTypeService.Setup(x => x.GetDataTypeDefinitionById(It.IsAny<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.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<int>()))
_dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>()))
.Returns(new DataType("test"));
var basic = new PropertyTypeBasic()
@@ -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);
}
@@ -102,7 +102,7 @@ namespace Umbraco.Tests.Persistence.Querying
.RightJoin<PropertyTypeDto>()
.On<PropertyTypeGroupDto, PropertyTypeDto>(left => left.Id, right => right.PropertyTypeGroupId)
.InnerJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId);
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId);
Assert.That(sql.SQL, Is.EqualTo(expected.SQL));
@@ -149,7 +149,7 @@ namespace Umbraco.Tests.Persistence.Querying
.RightJoin<PropertyTypeDto>()
.On<PropertyTypeGroupDto, PropertyTypeDto>(left => left.Id, right => right.PropertyTypeGroupId)
.InnerJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId)
.Where<PropertyTypeDto>(x => x.ContentTypeId == 1050);
Assert.That(sql.SQL, Is.EqualTo(expected.SQL));
@@ -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"))));
@@ -27,7 +27,7 @@ namespace Umbraco.Tests.Persistence.Querying
sql.SelectAll()
.From<DataTypeDto>()
.InnerJoin<NodeDto>()
.On<DataTypeDto, NodeDto>(left => left.DataTypeId, right => right.NodeId)
.On<DataTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
Assert.That(sql.SQL, Is.EqualTo(expected.SQL));
@@ -339,7 +339,7 @@ namespace Umbraco.Tests.Persistence.Repositories
.InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId)
.LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId)
.LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id)
.Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + ".versionId = uContentVersion.id")
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
@@ -357,7 +357,7 @@ namespace Umbraco.Tests.Persistence.Repositories
.InnerJoin<ContentVersionDto>().On<ContentVersionDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<MemberDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId)
.LeftJoin<PropertyTypeDto>().On<PropertyTypeDto, ContentDto>(left => left.ContentTypeId, right => right.ContentTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.DataTypeId, right => right.DataTypeId)
.LeftJoin<DataTypeDto>().On<DataTypeDto, PropertyTypeDto>(left => left.NodeId, right => right.DataTypeId)
.LeftJoin<PropertyDataDto>().On<PropertyDataDto, PropertyTypeDto>(left => left.PropertyTypeId, right => right.Id)
.Append("AND " + Constants.DatabaseSchema.Tables.PropertyData + ".versionId = uContentVersion.id")
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
@@ -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();
}
@@ -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)
{
@@ -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
@@ -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)
{
@@ -40,7 +40,7 @@ namespace Umbraco.Web.Editors
/// <returns></returns>
public DataTypeDisplay GetByName(string name)
{
var dataType = Services.DataTypeService.GetDataTypeDefinitionByName(name);
var dataType = Services.DataTypeService.GetDataType(name);
return dataType == null ? null : Mapper.Map<IDataType, DataTypeDisplay>(dataType);
}
@@ -51,7 +51,7 @@ namespace Umbraco.Web.Editors
/// <returns></returns>
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
/// <returns>a DataTypeDisplay</returns>
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
/// <returns></returns>
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
/// <returns></returns>
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<DataTypeBasic> GetAll()
{
return Services.DataTypeService
.GetAllDataTypeDefinitions()
.GetAll()
.Select(Mapper.Map<IDataType, DataTypeBasic>).Where(x => x.IsSystemDataType == false);
}
@@ -305,7 +305,7 @@ namespace Umbraco.Web.Editors
public IDictionary<string, IEnumerable<DataTypeBasic>> GetGroupedDataTypes()
{
var dataTypes = Services.DataTypeService
.GetAllDataTypeDefinitions()
.GetAll()
.Select(Mapper.Map<IDataType, DataTypeBasic>)
.ToArray();
@@ -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);
@@ -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);
@@ -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
{
@@ -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;
@@ -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);
})
@@ -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)
{
@@ -12,7 +12,7 @@ namespace Umbraco.Web.PropertyEditors
/// </summary>
internal class DateTimeValidator : IPropertyValidator
{
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
//don't validate if empty
if (value == null || value.ToString().IsNullOrWhiteSpace())
@@ -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<DataTypeConfiguration.NestedContentType[]>(preValue.Value)
: Array.Empty<DataTypeConfiguration.NestedContentType>(),
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<Configuration>(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<Configuration.NestedContentType[]>(preValue.Value)
// : Array.Empty<Configuration.NestedContentType>(),
// 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
@@ -21,7 +21,6 @@ namespace Umbraco.Web.PropertyEditors
internal class SliderPreValueEditor : PreValueEditor
{
[PreValueField("enableRange", "Enable range", "boolean")]
public string Range { get; set; }
@@ -17,7 +17,7 @@ namespace Umbraco.Web.PropertyEditors
{
internal class UploadFileTypeValidator : IPropertyValidator
{
public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
public IEnumerable<ValidationResult> Validate(object value, object dataTypeConfiguration, PropertyEditor editor)
{
//now check the file type
@@ -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<MediaPickerLegacyValueConverter>(error);
throw new Exception(error);
@@ -34,7 +34,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// <inheritdoc />
public override Type GetPropertyValueType(PublishedPropertyType propertyType)
{
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.DataTypeConfiguration>().ContentTypes;
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.Configuration>().ContentTypes;
return contentTypes.Length > 1
? typeof (IEnumerable<IPublishedElement>)
: typeof (IEnumerable<>).MakeGenericType(ModelType.For(contentTypes[0].Alias));
@@ -62,7 +62,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
if (objects.Count == 0)
return Enumerable.Empty<IPublishedElement>();
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.DataTypeConfiguration>().ContentTypes;
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.Configuration>().ContentTypes;
var elements = contentTypes.Length > 1
? new List<IPublishedElement>()
: PublishedModelFactory.CreateModelList(contentTypes[0].Alias);
@@ -33,7 +33,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
/// <inheritdoc />
public override Type GetPropertyValueType(PublishedPropertyType propertyType)
{
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.DataTypeConfiguration>().ContentTypes;
var contentTypes = propertyType.DataType.GetConfiguration<NestedContentPropertyEditor.Configuration>().ContentTypes;
return contentTypes.Length > 1
? typeof(IPublishedElement)
: ModelType.For(contentTypes[0].Alias);
@@ -30,7 +30,7 @@ namespace Umbraco.Web.PropertyEditors.ValueConverters
if (!IsNested(publishedProperty))
return false;
var config = publishedProperty.DataType.GetConfiguration<NestedContentPropertyEditor.DataTypeConfiguration>();
var config = publishedProperty.DataType.GetConfiguration<NestedContentPropertyEditor.Configuration>();
return config.MinItems == 1 && config.MaxItems == 1;
}
@@ -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();