From dca3b745428560ca221738fd486be4f556b3654f Mon Sep 17 00:00:00 2001 From: Stephan Date: Wed, 20 Sep 2017 20:06:46 +0200 Subject: [PATCH] Refactor and fix tests --- .../PublishedContent/PublishedPropertyBase.cs | 11 +- src/Umbraco.Core/Models/Rdbms/UserGroupDto.cs | 2 +- .../Mappers/MapperCollectionBuilder.cs | 2 +- .../Persistence/Mappers/UserTypeMapper.cs | 49 +- .../Persistence/NPocoSqlExtensions.cs | 211 ++++++- .../Persistence/Querying/Query.cs | 4 +- .../Repositories/PermissionRepository.cs | 2 +- .../Repositories/UserGroupRepository.cs | 70 +-- .../Repositories/UserRepository.cs | 4 +- src/Umbraco.Tests/App.config | 4 +- .../Cache/CacheRefresherComponentTests.cs | 7 +- .../UmbracoServiceMembershipProviderTests.cs | 18 +- .../Migrations/Upgrades/BaseUpgradeTest.cs | 7 +- src/Umbraco.Tests/Misc/LibraryTests.cs | 4 +- .../Models/Mapping/AutoMapperTests.cs | 13 +- .../Mapping/ContentTypeModelMappingTests.cs | 4 +- .../Persistence/NPocoExpressionsTests.cs | 36 -- .../NPocoBulkInsertTests.cs} | 15 +- .../NPocoTests/NPocoExpressionsTests.cs | 69 +++ .../NPocoTests/NPocoFetchTests.cs} | 134 ++--- .../NPocoTests/NPocoSqlCacheTests.cs | 89 +++ .../{Querying => NPocoTests}/NPocoSqlTests.cs | 546 +++++++++--------- .../{ => NPocoTests}/PetaPocoCachesTest.cs | 2 +- .../Persistence/Querying/QueryBuilderTests.cs | 6 +- .../Repositories/UserGroupRepositoryTest.cs | 14 +- .../Plugins/PluginManagerTests.cs | 10 +- src/Umbraco.Tests/Plugins/TypeFinderTests.cs | 2 +- .../PublishedContentExtensionTests.cs | 5 +- .../PublishedContentTestBase.cs | 9 +- .../Services/ContentServiceTests.cs | 36 +- .../Services/MemberServiceTests.cs | 7 +- .../Services/UserServiceTests.cs | 3 +- src/Umbraco.Tests/StringNewlineExtensions.cs | 16 +- .../TestHelpers/BaseUsingSqlCeSyntax.cs | 6 +- .../TestControllerActivatorBase.cs | 3 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 13 + src/Umbraco.Tests/Umbraco.Tests.csproj | 11 +- .../Web/Controllers/UsersControllerTests.cs | 6 +- .../DI/WebMappingProfilesCompositionRoot.cs | 28 +- ...ileProfile.cs => CodeFileMapperProfile.cs} | 4 +- ...tentProfile.cs => ContentMapperProfile.cs} | 4 +- ...ile.cs => ContentPropertyMapperProfile.cs} | 4 +- ...Profile.cs => ContentTypeMapperProfile.cs} | 4 +- .../Models/Mapping/CreatorResolver.cs | 1 - ...rdProfile.cs => DashboardMapperProfile.cs} | 4 +- ...ypeProfile.cs => DataTypeMapperProfile.cs} | 4 +- ...ntityProfile.cs => EntityMapperProfile.cs} | 4 +- ...{MacroProfile.cs => MacroMapperProfile.cs} | 6 +- ...{MediaProfile.cs => MediaMapperProfile.cs} | 4 +- ...emberProfile.cs => MemberMapperProfile.cs} | 4 +- .../Models/Mapping/OwnerResolver.cs | 1 - ...ionProfile.cs => RelationMapperProfile.cs} | 4 +- ...tionProfile.cs => SectionMapperProfile.cs} | 10 +- .../{TabProfile.cs => TagMapperProfile.cs} | 4 +- ...ateProfile.cs => TemplateMapperProfile.cs} | 4 +- .../{UserProfile.cs => UserMapperProfile.cs} | 4 +- .../NestedContentPropertyEditor.cs | 9 +- .../Providers/MembersMembershipProvider.cs | 38 +- src/Umbraco.Web/Umbraco.Web.csproj | 30 +- src/Umbraco.Web/WebRuntimeComponent.cs | 2 +- .../Actions/ActionCollectionBuilder.cs | 16 +- 61 files changed, 924 insertions(+), 719 deletions(-) delete mode 100644 src/Umbraco.Tests/Persistence/NPocoExpressionsTests.cs rename src/Umbraco.Tests/Persistence/{NPocoExtensionsTest.cs => NPocoTests/NPocoBulkInsertTests.cs} (93%) create mode 100644 src/Umbraco.Tests/Persistence/NPocoTests/NPocoExpressionsTests.cs rename src/Umbraco.Tests/{NuGet/NPocoTests.cs => Persistence/NPocoTests/NPocoFetchTests.cs} (76%) create mode 100644 src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlCacheTests.cs rename src/Umbraco.Tests/Persistence/{Querying => NPocoTests}/NPocoSqlTests.cs (96%) rename src/Umbraco.Tests/Persistence/{ => NPocoTests}/PetaPocoCachesTest.cs (99%) rename src/Umbraco.Web/Models/Mapping/{CodeFileProfile.cs => CodeFileMapperProfile.cs} (96%) rename src/Umbraco.Web/Models/Mapping/{ContentProfile.cs => ContentMapperProfile.cs} (98%) rename src/Umbraco.Web/Models/Mapping/{ContentPropertyProfile.cs => ContentPropertyMapperProfile.cs} (92%) rename src/Umbraco.Web/Models/Mapping/{ContentTypeProfile.cs => ContentTypeMapperProfile.cs} (98%) rename src/Umbraco.Web/Models/Mapping/{DashboardProfile.cs => DashboardMapperProfile.cs} (88%) rename src/Umbraco.Web/Models/Mapping/{DataTypeProfile.cs => DataTypeMapperProfile.cs} (98%) rename src/Umbraco.Web/Models/Mapping/{EntityProfile.cs => EntityMapperProfile.cs} (99%) rename src/Umbraco.Web/Models/Mapping/{MacroProfile.cs => MacroMapperProfile.cs} (89%) rename src/Umbraco.Web/Models/Mapping/{MediaProfile.cs => MediaMapperProfile.cs} (97%) rename src/Umbraco.Web/Models/Mapping/{MemberProfile.cs => MemberMapperProfile.cs} (98%) rename src/Umbraco.Web/Models/Mapping/{RelationProfile.cs => RelationMapperProfile.cs} (83%) rename src/Umbraco.Web/Models/Mapping/{SectionProfile.cs => SectionMapperProfile.cs} (59%) rename src/Umbraco.Web/Models/Mapping/{TabProfile.cs => TagMapperProfile.cs} (67%) rename src/Umbraco.Web/Models/Mapping/{TemplateProfile.cs => TemplateMapperProfile.cs} (90%) rename src/Umbraco.Web/Models/Mapping/{UserProfile.cs => UserMapperProfile.cs} (99%) diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyBase.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyBase.cs index 2e00a89385..fbb95ec434 100644 --- a/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyBase.cs +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedPropertyBase.cs @@ -14,11 +14,11 @@ namespace Umbraco.Core.Models.PublishedContent PropertyType = propertyType ?? throw new ArgumentNullException(nameof(propertyType)); ReferenceCacheLevel = referenceCacheLevel; - ValidateCacheLevel(ReferenceCacheLevel); - ValidateCacheLevel(PropertyType.CacheLevel); + ValidateCacheLevel(ReferenceCacheLevel, true); + ValidateCacheLevel(PropertyType.CacheLevel, false); } - private static void ValidateCacheLevel(PropertyCacheLevel cacheLevel) + private static void ValidateCacheLevel(PropertyCacheLevel cacheLevel, bool validateUnknown) { switch (cacheLevel) { @@ -26,9 +26,12 @@ namespace Umbraco.Core.Models.PublishedContent case PropertyCacheLevel.Snapshot: case PropertyCacheLevel.Facade: case PropertyCacheLevel.None: + break; + case PropertyCacheLevel.Unknown: + if (!validateUnknown) goto default; break; default: - throw new Exception("Invalid cache level."); + throw new Exception($"Invalid cache level \"{cacheLevel}\"."); } } diff --git a/src/Umbraco.Core/Models/Rdbms/UserGroupDto.cs b/src/Umbraco.Core/Models/Rdbms/UserGroupDto.cs index 8b7c693518..fde641ecc6 100644 --- a/src/Umbraco.Core/Models/Rdbms/UserGroupDto.cs +++ b/src/Umbraco.Core/Models/Rdbms/UserGroupDto.cs @@ -60,7 +60,7 @@ namespace Umbraco.Core.Models.Rdbms public int? StartMediaId { get; set; } [ResultColumn] - [Reference(ReferenceType.Many, ReferenceMemberName = "id")] + [Reference(ReferenceType.Many, ReferenceMemberName = "UserGroupId")] public List UserGroup2AppDtos { get; set; } /// diff --git a/src/Umbraco.Core/Persistence/Mappers/MapperCollectionBuilder.cs b/src/Umbraco.Core/Persistence/Mappers/MapperCollectionBuilder.cs index 76bcb58115..530250bbf0 100644 --- a/src/Umbraco.Core/Persistence/Mappers/MapperCollectionBuilder.cs +++ b/src/Umbraco.Core/Persistence/Mappers/MapperCollectionBuilder.cs @@ -54,7 +54,7 @@ namespace Umbraco.Core.Persistence.Mappers Add(); Add(); Add(); - Add(); + Add(); return this; } } diff --git a/src/Umbraco.Core/Persistence/Mappers/UserTypeMapper.cs b/src/Umbraco.Core/Persistence/Mappers/UserTypeMapper.cs index 332964aff7..eab01769b7 100644 --- a/src/Umbraco.Core/Persistence/Mappers/UserTypeMapper.cs +++ b/src/Umbraco.Core/Persistence/Mappers/UserTypeMapper.cs @@ -1,27 +1,28 @@ -using System.Collections.Concurrent; -using Umbraco.Core.Models.Membership; -using Umbraco.Core.Models.Rdbms; +//using System.Collections.Concurrent; +//using Umbraco.Core.Models.Membership; +//using Umbraco.Core.Models.Rdbms; -namespace Umbraco.Core.Persistence.Mappers -{ - /// - /// Represents a to DTO mapper used to translate the properties of the public api - /// implementation to that of the database's DTO as sql: [tableName].[columnName]. - /// - [MapperFor(typeof(IUserType))] - [MapperFor(typeof(UserType))] - public sealed class UserTypeMapper : BaseMapper - { - private static readonly ConcurrentDictionary PropertyInfoCacheInstance = new ConcurrentDictionary(); +//namespace Umbraco.Core.Persistence.Mappers +//{ +// /// +// /// Represents a to DTO mapper used to translate the properties of the public api +// /// implementation to that of the database's DTO as sql: [tableName].[columnName]. +// /// +// [MapperFor(typeof(IUserType))] +// [MapperFor(typeof(UserType))] +// public sealed class UserTypeMapper : BaseMapper +// { +// private static readonly ConcurrentDictionary PropertyInfoCacheInstance = new ConcurrentDictionary(); - internal override ConcurrentDictionary PropertyInfoCache => PropertyInfoCacheInstance; +// internal override ConcurrentDictionary PropertyInfoCache => PropertyInfoCacheInstance; - protected override void BuildMap() - { - CacheMap(src => src.Id, dto => dto.Id); - CacheMap(src => src.Alias, dto => dto.Alias); - CacheMap(src => src.Name, dto => dto.Name); - CacheMap(src => src.Permissions, dto => dto.DefaultPermissions); - } - } -} +// protected override void BuildMap() +// { +// CacheMap(src => src.Id, dto => dto.Id); +// CacheMap(src => src.Alias, dto => dto.Alias); +// CacheMap(src => src.Name, dto => dto.Name); +// CacheMap(src => src.Permissions, dto => dto.DefaultPermissions); +// } +// } +//} +// fixme remoev this file \ No newline at end of file diff --git a/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs b/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs index a44838dbda..e9766edc72 100644 --- a/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs +++ b/src/Umbraco.Core/Persistence/NPocoSqlExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; @@ -182,31 +183,74 @@ namespace Umbraco.Core.Persistence return sql; } + /// + /// Creates a SELECT Sql statement. + /// + /// The type of the DTO to select. + /// The origin sql. + /// An optional reference Sql expression. + /// The Sql statement. + /// + /// Use to select referenced DTOs. + /// public static Sql Select(this Sql sql, Func refexpr = null) { - var pd = sql.SqlContext.PocoDataFactory.ForType(typeof (T)); - - var tableName = pd.TableInfo.TableName; - var columns = pd.QueryColumns.Select(x => GetColumn(sql.SqlContext.DatabaseType, - tableName, - x.Value.ColumnName, - string.IsNullOrEmpty(x.Value.ColumnAlias) ? x.Value.MemberInfoKey : x.Value.ColumnAlias)); - - sql.Select(columns); + sql.Select(sql.GetColumns()); if (refexpr == null) return sql; refexpr(new RefSql(sql, null)); return sql; } + public static Sql Zelect(this Sql sql, Func, RefSql> refexpr = null) + { + sql.Select(sql.GetColumns()); + + if (refexpr == null) return sql; + refexpr(new RefSql(sql, null)); + return sql; + } + /// - /// + /// Creates a SELECT Sql statement. /// - /// - /// - /// - /// The name of the DTO reference. - /// The name of the table alias. + /// The type of the DTO to select. + /// The origin sql. + /// A selection Sql expression. + /// A reference Sql expression. + /// The Sql statement. + /// + /// Use to complement the selection.. + /// Use to select referenced DTOs. + /// + public static Sql Select(this Sql sql, Func, Sql> sqlexpr, Func refexpr) + { + sql.Select(sql.GetColumns()); + + sql = sqlexpr(sql); + + refexpr(new RefSql(sql, null)); + return sql; + } + + public static Sql Zelect(this Sql sql, Func, Sql> sqlexpr, Func, RefSql> refexpr) + { + sql.Select(sql.GetColumns()); + + sql = sqlexpr(sql); + + refexpr(new RefSql(sql, null)); + return sql; + } + + /// + /// Complements a SELECT Sql statement with a referenced DTO. + /// + /// The type of the DTO to select. + /// The origin sql. + /// An optional, nested, reference Sql expression. + /// The optional name of the DTO reference. + /// The optional name of the table alias. /// /// /// Select<Foo>() produces: [foo].[value] AS [Foo_Value] @@ -217,15 +261,8 @@ namespace Umbraco.Core.Persistence { if (referenceName == null) referenceName = typeof (T).Name; if (refSql.Prefix != null) referenceName = refSql.Prefix + PocoData.Separator + referenceName; - var pd = refSql.Sql.SqlContext.PocoDataFactory.ForType(typeof (T)); - - var tableName = tableAlias ?? pd.TableInfo.TableName; - var columns = pd.QueryColumns.Select(x => GetColumn(refSql.Sql.SqlContext.DatabaseType, - tableName, - x.Value.ColumnName, - string.IsNullOrEmpty(x.Value.ColumnAlias) ? x.Value.MemberInfoKey : x.Value.ColumnAlias, - referenceName)); + var columns = refSql.Sql.GetColumns(referenceName); refSql.Sql.Append(", " + string.Join(", ", columns)); if (refexpr == null) return refSql; @@ -233,13 +270,27 @@ namespace Umbraco.Core.Persistence return refSql; } - public static Sql Select(this Sql sql, params Expression>[] columns) + /// + /// Creates a SELECT Sql statement. + /// + /// The type of the DTO to select. + /// The origin sql. + /// Expressions indicating the columns to select. + /// The Sql statement. + /// + /// If is empty, all columns are selected. + /// + public static Sql Select(this Sql sql, params Expression>[] columnExpressions) { - var fieldNames = columns.Select(x => GetFieldName(x, sql.SqlContext.SqlSyntax)).ToArray(); - sql.Select(fieldNames); + var columns = columnExpressions.Length == 0 + ? sql.GetColumns() + : columnExpressions.Select(x => GetFieldName(x, sql.SqlContext.SqlSyntax)).ToArray(); + + sql.Select(columns); return sql; } + // fixme - obsolete public class RefSql { public RefSql(Sql sql, string prefix) @@ -252,6 +303,106 @@ namespace Umbraco.Core.Persistence public string Prefix { get; } } + public class RefSql + { + public RefSql(Sql sql, string prefix) + { + Sql = sql; + Prefix = prefix; + } + + public Sql Sql { get; } + public string Prefix { get; } + + public RefSql Select(Func, RefSql> refexpr = null) + => Select(null, null, refexpr); + + //fixme rename duplicate "ref expr" + + public RefSql Select(Expression> referenceExpression, Func, RefSql> refexpr = null) + => Select(referenceExpression, null, refexpr); + + public RefSql Select(Expression>> referenceExpression, Func, RefSql> refexpr = null) + => Select(referenceExpression, null, refexpr); + + public RefSql Select(Expression> referenceExpression, string tableAlias, Func, RefSql> refexpr = null) + { + string referenceName = null; + if (referenceExpression != null) + { + var property = ExpressionHelper.FindProperty(referenceExpression) as PropertyInfo; + if (property == null) + throw new InvalidOperationException("Could not get property specified in expression."); + referenceName = property.Name; + } + if (referenceName == null) referenceName = typeof(TDto).Name; + if (Prefix != null) referenceName = Prefix + PocoData.Separator + referenceName; + + var columns = Sql.GetColumns(referenceName); + Sql.Append(", " + string.Join(", ", columns)); + + if (refexpr == null) return this; + refexpr(new RefSql(Sql, referenceName)); + return this; + } + + // fixme - also handle the case... when it's not a List but a single one + // fixme - DRY + public RefSql Select(Expression>> referenceExpression, string tableAlias, Func, RefSql> refexpr = null) + { + string referenceName = null; + if (referenceExpression != null) + { + var property = ExpressionHelper.FindProperty(referenceExpression) as PropertyInfo; + if (property == null) + throw new InvalidOperationException("Could not get property specified in expression."); + referenceName = property.Name; + } + if (referenceName == null) referenceName = typeof(TDto).Name; + if (Prefix != null) referenceName = Prefix + PocoData.Separator + referenceName; + + var columns = Sql.GetColumns(referenceName); + Sql.Append(", " + string.Join(", ", columns)); + + if (refexpr == null) return this; + refexpr(new RefSql(Sql, referenceName)); + return this; + } + } + + /// + /// Gets the column names of a DTO. + /// + /// The type of the DTO. + /// The origin sql. + /// Expressions indicating the columns to select. + /// The comma-separated list of columns. + /// + /// If is empty, all columns are selected. + /// + public static string Columns(this Sql sql, params Expression>[] columnExpressions) + { + var columns = columnExpressions.Length == 0 + ? sql.GetColumns() + : columnExpressions.Select(x => GetFieldName(x, sql.SqlContext.SqlSyntax)).ToArray(); + + return string.Join(", ", columns); + } + + #endregion + + #region Utilities + + private static object[] GetColumns(this Sql sql, string referenceName = null) + { + var pd = sql.SqlContext.PocoDataFactory.ForType(typeof (TDto)); + var tableName = pd.TableInfo.TableName; + return pd.QueryColumns.Select(x => (object) GetColumn(sql.SqlContext.DatabaseType, + tableName, x.Value.ColumnName, + string.IsNullOrEmpty(x.Value.ColumnAlias) ? x.Value.MemberInfoKey : x.Value.ColumnAlias, + referenceName)).ToArray(); + } + private static string GetColumn(DatabaseType dbType, string tableName, string columnName, string columnAlias, string referenceName = null) { tableName = dbType.EscapeTableName(tableName); @@ -260,10 +411,6 @@ namespace Umbraco.Core.Persistence return tableName + "." + columnName + " AS " + columnAlias; } - #endregion - - #region Helpers - private static string GetTableName(this Type type) { // todo: returning string.Empty for now @@ -279,12 +426,12 @@ namespace Umbraco.Core.Persistence return string.IsNullOrWhiteSpace(attr?.Name) ? column.Name : attr.Name; } - private static string GetFieldName(Expression> fieldSelector, ISqlSyntaxProvider sqlSyntax) + private static string GetFieldName(Expression> fieldSelector, ISqlSyntaxProvider sqlSyntax) { var field = ExpressionHelper.FindProperty(fieldSelector) as PropertyInfo; var fieldName = field.GetColumnName(); - var type = typeof(T); + var type = typeof (TDto); var tableName = type.GetTableName(); return sqlSyntax.GetQuotedTableName(tableName) + "." + sqlSyntax.GetQuotedColumnName(fieldName); diff --git a/src/Umbraco.Core/Persistence/Querying/Query.cs b/src/Umbraco.Core/Persistence/Querying/Query.cs index d9282525d0..dd84d283f6 100644 --- a/src/Umbraco.Core/Persistence/Querying/Query.cs +++ b/src/Umbraco.Core/Persistence/Querying/Query.cs @@ -2,8 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; -using Umbraco.Core.Persistence.Mappers; -using Umbraco.Core.Persistence.SqlSyntax; using System.Text; using NPoco; @@ -15,7 +13,7 @@ namespace Umbraco.Core.Persistence.Querying /// public class Query : IQuery { - private readonly SqlContext _sqlContext; + private readonly SqlContext _sqlContext; private readonly List> _wheres = new List>(); public Query(SqlContext sqlContext) diff --git a/src/Umbraco.Core/Persistence/Repositories/PermissionRepository.cs b/src/Umbraco.Core/Persistence/Repositories/PermissionRepository.cs index fb6da888ef..e2732f04b1 100644 --- a/src/Umbraco.Core/Persistence/Repositories/PermissionRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/PermissionRepository.cs @@ -203,7 +203,7 @@ namespace Umbraco.Core.Persistence.Repositories { nodeId = entity.Id, permission = permission.ToString(CultureInfo.InvariantCulture), - groupIdsA + groupIds = groupIdsA }); var actions = groupIdsA.Select(id => new UserGroup2NodePermissionDto diff --git a/src/Umbraco.Core/Persistence/Repositories/UserGroupRepository.cs b/src/Umbraco.Core/Persistence/Repositories/UserGroupRepository.cs index c5926d8db0..8a3715a8e5 100644 --- a/src/Umbraco.Core/Persistence/Repositories/UserGroupRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/UserGroupRepository.cs @@ -79,7 +79,7 @@ namespace Umbraco.Core.Persistence.Repositories sql.Where($"umbracoUserGroup.id IN ({innerSql.SQL})"); AppendGroupBy(sql); - return ConvertFromDtos(Database.Fetch(sql)); + return Database.Fetch(sql).Select(UserGroupFactory.BuildEntity); } public void AddOrUpdateGroupWithUsers(IUserGroup userGroup, int[] userIds) @@ -186,14 +186,18 @@ namespace Umbraco.Core.Persistence.Repositories var sql = GetBaseQuery(QueryType.Many); if (ids.Any()) - sql.WhereIn(x => x.Id, ids); + sql.WhereIn(x => x.Id, ids); else sql.Where(x => x.Id >= 0); AppendGroupBy(sql); - var dtos = Database.Fetch(sql); - return ConvertFromDtos(dtos); + // fixme - required so that Fetch can assemble references + sql.OrderBy(x => x.Id); + + Console.WriteLine(sql.SQL); + var dtos = Database.FetchOneToMany(x => x.UserGroup2AppDtos, sql); // fixme one-to-many! + return dtos.Select(UserGroupFactory.BuildEntity); } protected override IEnumerable PerformGetByQuery(IQuery query) @@ -204,7 +208,7 @@ namespace Umbraco.Core.Persistence.Repositories AppendGroupBy(sql); var dtos = Database.Fetch(sql); - return ConvertFromDtos(dtos); + return dtos.Select(UserGroupFactory.BuildEntity); } #endregion @@ -225,14 +229,15 @@ namespace Umbraco.Core.Persistence.Repositories break; case QueryType.Ids: sql - .Select("umbracoUserGroup.id"); + .Select(x => x.Id); addFrom = true; break; case QueryType.Single: case QueryType.Many: sql - .Select(r => r.Select()) - .Append(", COUNT(umbracoUser2UserGroup.UserId)"); // vs COUNT(umbracoUser.Id) - removes a JOIN + .Zelect( + s => s.Append($", COUNT({sql.Columns(x => x.UserId)}) AS {SqlSyntax.GetQuotedColumnName("UserCount")}"), + r => r.Select(x => x.UserGroup2AppDtos)); addFrom = true; break; default: @@ -245,9 +250,7 @@ namespace Umbraco.Core.Persistence.Repositories .LeftJoin() .On(left => left.Id, right => right.UserGroupId) .LeftJoin() - .On(left => left.UserGroupId, right => right.Id) - /*.LeftJoin() - .On(left => left.Id, right => right.UserId)*/; + .On(left => left.UserGroupId, right => right.Id); return sql; } @@ -255,42 +258,14 @@ namespace Umbraco.Core.Persistence.Repositories protected override Sql GetBaseQuery(bool isCount) { return GetBaseQuery(isCount ? QueryType.Count : QueryType.Many); - -// var sql = Sql(); - -// if (isCount) -// { -// sql.Select("COUNT(*)").From(); -// } -// else -// { -// return GetBaseQuery(@"umbracoUserGroup.createDate, umbracoUserGroup.icon, umbracoUserGroup.id, umbracoUserGroup.startContentId, -//umbracoUserGroup.startMediaId, umbracoUserGroup.updateDate, umbracoUserGroup.userGroupAlias, umbracoUserGroup.userGroupDefaultPermissions, -//umbracoUserGroup.userGroupName, COUNT(umbracoUser.id) AS UserCount, umbracoUserGroup2App.app, umbracoUserGroup2App.userGroupId"); -// } -// return sql; } - //protected Sql GetBaseQuery(string columns) - //{ - // var sql = Sql() - // .Select(columns) - // .From() - // .LeftJoin() - // .On(left => left.Id, right => right.UserGroupId) - // .LeftJoin() - // .On(left => left.UserGroupId, right => right.Id) - // .LeftJoin() - // .On(left => left.Id, right => right.UserId); - - // return sql; - //} - - private static void AppendGroupBy(Sql sql) + private static void AppendGroupBy(Sql sql) { - sql.GroupBy(@"umbracoUserGroup.createDate, umbracoUserGroup.icon, umbracoUserGroup.id, umbracoUserGroup.startContentId, -umbracoUserGroup.startMediaId, umbracoUserGroup.updateDate, umbracoUserGroup.userGroupAlias, umbracoUserGroup.userGroupDefaultPermissions, -umbracoUserGroup.userGroupName, umbracoUserGroup2App.app, umbracoUserGroup2App.userGroupId"); + sql.GroupBy(sql.Columns(x => x.CreateDate, x => x.Icon, x => x.Id, x => x.StartContentId, x => x.StartMediaId, + x => x.UpdateDate, x => x.Alias, x => x.DefaultPermissions, x => x.Name) + + ", " + + sql.Columns(x => x.AppAlias, x => x.UserGroupId)); } protected override string GetBaseWhereClause() @@ -317,7 +292,7 @@ umbracoUserGroup.userGroupName, umbracoUserGroup2App.app, umbracoUserGroup2App.u ((UserGroup) entity).AddingEntity(); var userGroupDto = UserGroupFactory.BuildDto(entity); - + var id = Convert.ToInt32(Database.Insert(userGroupDto)); entity.Id = id; @@ -356,11 +331,6 @@ umbracoUserGroup.userGroupName, umbracoUserGroup2App.app, umbracoUserGroup2App.u #endregion - private static IEnumerable ConvertFromDtos(IEnumerable dtos) - { - return dtos.Select(UserGroupFactory.BuildEntity); - } - /// /// used to persist a user group with associated users at once /// diff --git a/src/Umbraco.Core/Persistence/Repositories/UserRepository.cs b/src/Umbraco.Core/Persistence/Repositories/UserRepository.cs index 97ea564129..3c85db63c5 100644 --- a/src/Umbraco.Core/Persistence/Repositories/UserRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/UserRepository.cs @@ -213,7 +213,7 @@ ORDER BY colName"; .WhereIn(x => x.UserId, userIds); var users2groups = Database.Fetch(sql); - var groupIds = users2groups.Select(x => x.UserGroupId).ToList(); + var groupIds = users2groups.Select(x => x.UserGroupId).ToList(); // get groups @@ -257,7 +257,7 @@ ORDER BY colName"; } // map start nodes - + foreach (var startNode in startNodes) { var dto = xUsers == null ? dtos[0] : xUsers[startNode.UserId]; diff --git a/src/Umbraco.Tests/App.config b/src/Umbraco.Tests/App.config index 362eed160c..0cd869810f 100644 --- a/src/Umbraco.Tests/App.config +++ b/src/Umbraco.Tests/App.config @@ -94,8 +94,8 @@ - - + + diff --git a/src/Umbraco.Tests/Cache/CacheRefresherComponentTests.cs b/src/Umbraco.Tests/Cache/CacheRefresherComponentTests.cs index 20d0fe979c..e7175d744f 100644 --- a/src/Umbraco.Tests/Cache/CacheRefresherComponentTests.cs +++ b/src/Umbraco.Tests/Cache/CacheRefresherComponentTests.cs @@ -89,9 +89,12 @@ namespace Umbraco.Tests.Cache new EventDefinition(null, serviceContext.MediaService, new RecycleBinEventArgs(Guid.NewGuid(), new Dictionary>(), true)), new EventDefinition>(null, serviceContext.ContentService, new SaveEventArgs(Enumerable.Empty()), "Saved"), - new EventDefinition>(null, serviceContext.ContentService, new SaveEventArgs(Enumerable.Empty()), "SavedBlueprint"), new EventDefinition>(null, serviceContext.ContentService, new DeleteEventArgs(Enumerable.Empty()), "Deleted"), - new EventDefinition>(null, serviceContext.ContentService, new DeleteEventArgs(Enumerable.Empty()), "DeletedBlueprint"), + + // not managed + //new EventDefinition>(null, serviceContext.ContentService, new SaveEventArgs(Enumerable.Empty()), "SavedBlueprint"), + //new EventDefinition>(null, serviceContext.ContentService, new DeleteEventArgs(Enumerable.Empty()), "DeletedBlueprint"), + new EventDefinition>(null, serviceContext.ContentService, new CopyEventArgs(null, null, -1)), new EventDefinition>(null, serviceContext.ContentService, new MoveEventArgs(new MoveEventInfo(null, "", -1)), "Trashed"), new EventDefinition(null, serviceContext.ContentService, new RecycleBinEventArgs(Guid.NewGuid(), new Dictionary>(), true)), diff --git a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs index 9dd3047f1d..bdfe1004fc 100644 --- a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs +++ b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs @@ -5,14 +5,24 @@ using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Services; +using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; +using Umbraco.Tests.Testing; using Umbraco.Web.Security.Providers; namespace Umbraco.Tests.Membership { [TestFixture, RequiresSTA] - public class UmbracoServiceMembershipProviderTests + [UmbracoTest(Database = UmbracoTestOptions.Database.None, WithApplication = true)] + public class UmbracoServiceMembershipProviderTests : UmbracoTestBase { + //[SetUp] + //public void SetUp() + //{ + // SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings()); + // var container = new ServiceContainer + //} + [Test] public void Sets_Default_Member_Type_From_Service_On_Init() { @@ -84,7 +94,7 @@ namespace Umbraco.Tests.Membership membershipServiceMock.Setup(service => service.Exists("test")).Returns(false); membershipServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); membershipServiceMock.Setup( - service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m, bool isApproved) => { createdMember = new Member("test", e, u, p, memberType, isApproved); @@ -116,7 +126,7 @@ namespace Umbraco.Tests.Membership membershipServiceMock.Setup(service => service.Exists("test")).Returns(false); membershipServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); membershipServiceMock.Setup( - service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m, bool isApproved) => { createdMember = new Member("test", e, u, p, memberType, isApproved); @@ -150,7 +160,7 @@ namespace Umbraco.Tests.Membership membershipServiceMock.Setup(service => service.Exists("test")).Returns(false); membershipServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); membershipServiceMock.Setup( - service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m, bool isApproved) => { createdMember = new Member("test", e, u, p, memberType, isApproved); diff --git a/src/Umbraco.Tests/Migrations/Upgrades/BaseUpgradeTest.cs b/src/Umbraco.Tests/Migrations/Upgrades/BaseUpgradeTest.cs index a3ee01dc3d..f2d5504dfb 100644 --- a/src/Umbraco.Tests/Migrations/Upgrades/BaseUpgradeTest.cs +++ b/src/Umbraco.Tests/Migrations/Upgrades/BaseUpgradeTest.cs @@ -30,7 +30,8 @@ namespace Umbraco.Tests.Migrations.Upgrades DatabaseSpecificSetUp(); } - [Test] + [Test] + [NUnit.Framework.Ignore("remove in v8")] // fixme remove in v8 public virtual void Can_Upgrade_From_470_To_600() { var configuredVersion = new SemVersion(4, 7, 0); @@ -60,7 +61,7 @@ namespace Umbraco.Tests.Migrations.Upgrades configuredVersion, targetVersion, Constants.System.UmbracoMigrationName - //pass in explicit migrations + //pass in explicit migrations // fixme - all gone in v8 - migrations need to be refactored anyways //new Core.Persistence.Migrations.Upgrades.TargetVersionFourNineZero.RemoveUmbracoAppConstraints(context), //new DeleteAppTables(context), @@ -73,7 +74,7 @@ namespace Umbraco.Tests.Migrations.Upgrades //new UpdateCmsContentTypeAllowedContentTypeTable(context), //new UpdateCmsContentTypeTable(context), //new UpdateCmsContentVersionTable(context), - //new UpdateCmsPropertyTypeGroupTable(context) + //new UpdateCmsPropertyTypeGroupTable(context) ); var upgraded = migrationRunner.Execute(context /*, true*/); diff --git a/src/Umbraco.Tests/Misc/LibraryTests.cs b/src/Umbraco.Tests/Misc/LibraryTests.cs index 24bd494ee6..f75b8ae519 100644 --- a/src/Umbraco.Tests/Misc/LibraryTests.cs +++ b/src/Umbraco.Tests/Misc/LibraryTests.cs @@ -10,6 +10,7 @@ using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.PublishedCache.XmlPublishedCache; +using LightInject; namespace Umbraco.Tests.Misc { @@ -52,7 +53,8 @@ namespace Umbraco.Tests.Misc base.Compose(); // required so we can access property.Value - Container.RegisterCollectionBuilder(); + if (Container.TryGetInstance() == null) + Container.RegisterCollectionBuilder(); } [Test] diff --git a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs index 501d0c73c9..63e06ffa0c 100644 --- a/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/AutoMapperTests.cs @@ -45,21 +45,23 @@ namespace Umbraco.Tests.Models.Mapping // validate each profile (better granularity for error reports) + Console.WriteLine("Validate each profile:"); foreach (var profile in profiles) { try { config.AssertConfigurationIsValid(profile.GetType().FullName); - Console.WriteLine("OK " + profile.GetType().FullName); + //Console.WriteLine("OK " + profile.GetType().FullName); } - catch + catch (Exception e) { Console.WriteLine("KO " + profile.GetType().FullName); + Console.WriteLine(e); } } Console.WriteLine(); - + Console.WriteLine("Validate each profile and throw:"); foreach (var profile in profiles) { try @@ -74,10 +76,9 @@ namespace Umbraco.Tests.Models.Mapping } // validate the global config + Console.WriteLine(); + Console.WriteLine("Validate global config:"); config.AssertConfigurationIsValid(); - - // validate the static config (should be the same) - Mapper.AssertConfigurationIsValid(); } } } diff --git a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs index 78922603ce..59c209266c 100644 --- a/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs +++ b/src/Umbraco.Tests/Models/Mapping/ContentTypeModelMappingTests.cs @@ -59,9 +59,9 @@ namespace Umbraco.Tests.Models.Mapping Mapper.Initialize(configuration => { //initialize our content type mapper - var profile1 = new ContentTypeProfile(_editorsMock.Object, _dataTypeService.Object, _fileService.Object, _contentTypeService.Object, Mock.Of()); + var profile1 = new ContentTypeMapperProfile(_editorsMock.Object, _dataTypeService.Object, _fileService.Object, _contentTypeService.Object, Mock.Of()); configuration.AddProfile(profile1); - var profile2 = new EntityProfile(); + var profile2 = new EntityMapperProfile(); configuration.AddProfile(profile2); }); } diff --git a/src/Umbraco.Tests/Persistence/NPocoExpressionsTests.cs b/src/Umbraco.Tests/Persistence/NPocoExpressionsTests.cs deleted file mode 100644 index ef8c2ea84c..0000000000 --- a/src/Umbraco.Tests/Persistence/NPocoExpressionsTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using NPoco; -using NUnit.Framework; -using Umbraco.Core.Models.Rdbms; -using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.SqlSyntax; -using Umbraco.Tests.TestHelpers; - -namespace Umbraco.Tests.Persistence -{ - [TestFixture] - public class NPocoExpressionsTests : BaseUsingSqlCeSyntax - { - [Test] - public void WhereInValueFieldTest() - { - var sql = new Sql(SqlContext) - .Select("*") - .From() - .WhereIn(x => x.NodeId, new[] { 1, 2, 3 }); - Assert.AreEqual("SELECT *\nFROM [umbracoNode]\nWHERE ([umbracoNode].[id] IN (@0,@1,@2))", sql.SQL); - } - - [Test] - public void WhereInObjectFieldTest() - { - // this test used to fail because x => x.Text was evaluated as a lambda - // and returned "[umbracoNode].[text] = @0"... had to fix WhereIn. - - var sql = new Sql(SqlContext) - .Select("*") - .From() - .WhereIn(x => x.Text, new[] { "a", "b", "c" }); - Assert.AreEqual("SELECT *\nFROM [umbracoNode]\nWHERE ([umbracoNode].[text] IN (@0,@1,@2))", sql.SQL); - } - } -} diff --git a/src/Umbraco.Tests/Persistence/NPocoExtensionsTest.cs b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoBulkInsertTests.cs similarity index 93% rename from src/Umbraco.Tests/Persistence/NPocoExtensionsTest.cs rename to src/Umbraco.Tests/Persistence/NPocoTests/NPocoBulkInsertTests.cs index 7085fc2ef4..2a2d9ce42e 100644 --- a/src/Umbraco.Tests/Persistence/NPocoExtensionsTest.cs +++ b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoBulkInsertTests.cs @@ -3,23 +3,20 @@ using System.Collections.Generic; using System.Data; using System.Linq; using System.Text.RegularExpressions; -using NPoco; using NUnit.Framework; -using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; -using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.Testing; -namespace Umbraco.Tests.Persistence +namespace Umbraco.Tests.Persistence.NPocoTests { // fixme.npoco - is this still appropriate? // [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class NPocoExtensionsTest : TestWithDatabaseBase + public class NPocoBulkInsertTests : TestWithDatabaseBase { [Test] public void Can_Bulk_Insert_One_By_One() @@ -38,7 +35,7 @@ namespace Umbraco.Tests.Persistence } // Act - using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) + using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { using (var scope = ScopeProvider.CreateScope()) { @@ -71,7 +68,7 @@ namespace Umbraco.Tests.Persistence } // Act - using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) + using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { using (var scope = ScopeProvider.CreateScope()) { @@ -154,7 +151,7 @@ namespace Umbraco.Tests.Persistence } // Act - using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) + using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { using (var scope = ScopeProvider.CreateScope()) { @@ -187,7 +184,7 @@ namespace Umbraco.Tests.Persistence } // Act - using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) + using (ProfilingLogger.TraceDuration("starting insert", "finished insert")) { using (var scope = ScopeProvider.CreateScope()) { diff --git a/src/Umbraco.Tests/Persistence/NPocoTests/NPocoExpressionsTests.cs b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoExpressionsTests.cs new file mode 100644 index 0000000000..d80f5ed900 --- /dev/null +++ b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoExpressionsTests.cs @@ -0,0 +1,69 @@ +using System; +using NPoco; +using NUnit.Framework; +using Umbraco.Core.Models.Rdbms; +using Umbraco.Core.Persistence; +using Umbraco.Tests.TestHelpers; + +namespace Umbraco.Tests.Persistence.NPocoTests +{ + [TestFixture] + public class NPocoExpressionsTests : BaseUsingSqlCeSyntax + { + [Test] + public void WhereInValueFieldTest() + { + var sql = new Sql(SqlContext) + .Select("*") + .From() + .WhereIn(x => x.NodeId, new[] { 1, 2, 3 }); + Assert.AreEqual("SELECT *\nFROM [umbracoNode]\nWHERE ([umbracoNode].[id] IN (@0,@1,@2))", sql.SQL); + } + + [Test] + public void WhereInObjectFieldTest() + { + // this test used to fail because x => x.Text was evaluated as a lambda + // and returned "[umbracoNode].[text] = @0"... had to fix WhereIn. + + var sql = new Sql(SqlContext) + .Select("*") + .From() + .WhereIn(x => x.Text, new[] { "a", "b", "c" }); + Assert.AreEqual("SELECT *\nFROM [umbracoNode]\nWHERE ([umbracoNode].[text] IN (@0,@1,@2))", sql.SQL); + } + + [Test] + public void SelectDtoTest() + { + var sql = Sql() + .Select() + .From(); + Assert.AreEqual("SELECT [umbracoNode].[id] AS [NodeId], [umbracoNode].[trashed] AS [Trashed], [umbracoNode].[parentID] AS [ParentId], [umbracoNode].[nodeUser] AS [UserId], [umbracoNode].[level] AS [Level], [umbracoNode].[path] AS [Path], [umbracoNode].[sortOrder] AS [SortOrder], [umbracoNode].[uniqueID] AS [UniqueId], [umbracoNode].[text] AS [Text], [umbracoNode].[nodeObjectType] AS [NodeObjectType], [umbracoNode].[createDate] AS [CreateDate] FROM [umbracoNode]", sql.SQL.NoCrLf()); + } + + [Test] + public void SelectDtoFieldTest() + { + var sql = Sql() + .Select(x => x.NodeId) + .From(); + Assert.AreEqual("SELECT [umbracoNode].[id] FROM [umbracoNode]", sql.SQL.NoCrLf()); + + sql = Sql() + .Select(x => x.NodeId, x => x.UniqueId) + .From(); + Assert.AreEqual("SELECT [umbracoNode].[id], [umbracoNode].[uniqueID] FROM [umbracoNode]", sql.SQL.NoCrLf()); + } + + [Test] + public void SelectDtoRefTest() + { + var sql = Sql() + .Select(r => r.Select()) + .From(); + Console.WriteLine(sql.SQL); + Assert.AreEqual("SELECT [umbracoNode].[id] AS [NodeId], [umbracoNode].[trashed] AS [Trashed], [umbracoNode].[parentID] AS [ParentId], [umbracoNode].[nodeUser] AS [UserId], [umbracoNode].[level] AS [Level], [umbracoNode].[path] AS [Path], [umbracoNode].[sortOrder] AS [SortOrder], [umbracoNode].[uniqueID] AS [UniqueId], [umbracoNode].[text] AS [Text], [umbracoNode].[nodeObjectType] AS [NodeObjectType], [umbracoNode].[createDate] AS [CreateDate] , [cmsContent].[pk] AS [ContentDto__PrimaryKey], [cmsContent].[nodeId] AS [ContentDto__NodeId], [cmsContent].[contentType] AS [ContentDto__ContentTypeId] FROM [umbracoNode]", sql.SQL.NoCrLf()); + } + } +} diff --git a/src/Umbraco.Tests/NuGet/NPocoTests.cs b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoFetchTests.cs similarity index 76% rename from src/Umbraco.Tests/NuGet/NPocoTests.cs rename to src/Umbraco.Tests/Persistence/NPocoTests/NPocoFetchTests.cs index 6c88dc3e70..da7cac21fb 100644 --- a/src/Umbraco.Tests/NuGet/NPocoTests.cs +++ b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoFetchTests.cs @@ -1,32 +1,33 @@ using System; using System.Collections.Generic; using System.Linq; +using LightInject; using NPoco; using NUnit.Framework; -using Umbraco.Core.Scoping; -using Umbraco.Tests.Testing; -using LightInject; using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.SqlSyntax; +using Umbraco.Core.Scoping; +using Umbraco.Tests.TestHelpers; +using Umbraco.Tests.Testing; -namespace Umbraco.Tests.NuGet +namespace Umbraco.Tests.Persistence.NPocoTests { [TestFixture] - [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] - public class NPocoTests : UmbracoTestBase + [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest, WithApplication = true)] + public class NPocoFetchTests : TestWithDatabaseBase { - public override void SetUp() + protected override void Initialize() { - base.SetUp(); + base.Initialize(); using (var scope = ScopeProvider.CreateScope()) { InsertData(scope.Database); + scope.Complete(); } } - private IScopeProvider ScopeProvider => Container.GetInstance(); - - private void InsertData(IDatabase database) + private static void InsertData(IDatabase database) { database.Execute(@" CREATE TABLE zbThing1 ( @@ -50,7 +51,7 @@ namespace Umbraco.Tests.NuGet CREATE TABLE zbThing2 ( id int PRIMARY KEY NOT NULL, name NVARCHAR(255) NULL, - thingId int NULL, + thingId int NULL );"); database.Insert(new Thing2Dto @@ -153,7 +154,8 @@ namespace Umbraco.Tests.NuGet using (var scope = ScopeProvider.CreateScope()) { var dtos = scope.Database.Fetch(@" - SELECT zbThing2.id, zbThing2.name, zbThing2.thingId, zbThing1.id Thing__id, zbThing1.name Thing__name + SELECT zbThing2.id, zbThing2.name, zbThing2.thingId, + zbThing1.id Thing__id, zbThing1.name Thing__name FROM zbThing2 JOIN zbThing1 ON zbThing2.thingId=zbThing1.id"); Assert.AreEqual(3, dtos.Count); @@ -174,7 +176,8 @@ namespace Umbraco.Tests.NuGet using (var scope = ScopeProvider.CreateScope()) { var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" - SELECT zbThing1.id, zbThing1.name, zbThing2.id, zbThing2.name, zbThing2.thingId + SELECT zbThing1.id AS Id, zbThing1.name AS Name, + zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId FROM zbThing1 JOIN zbThing2 ON zbThing1.id=zbThing2.thingId WHERE zbThing1.id=1"); @@ -203,11 +206,24 @@ namespace Umbraco.Tests.NuGet using (var scope = ScopeProvider.CreateScope()) { - var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, @" - SELECT zbThing1.id, zbThing1.name, zbThing2.id, zbThing2.name, zbThing2.thingId - FROM zbThing1 - JOIN zbThing2 ON zbThing1.id=zbThing2.thingId - ORDER BY zbThing1.id"); + // this is the raw SQL, but it's better to use expressions and no magic strings! + //var sql = @" + // SELECT zbThing1.id AS Id, zbThing1.name AS Name, + // zbThing2.id AS Things__Id, zbThing2.name AS Things__Name, zbThing2.thingId AS Things__ThingId + // FROM zbThing1 + // JOIN zbThing2 ON zbThing1.id=zbThing2.thingId + // ORDER BY zbThing1.id"; + + var sql = scope.DatabaseContext.Sql() + .Zelect(r => r.Select(x => x.Things)) // select Thing3Dto, and Thing2Dto for Things + .From() + .InnerJoin().On(left => left.Id, right => right.ThingId) + .OrderBy(x => x.Id); + + // one-to-many on Things, using Id as the 'one' key - not needed since it's PK + //var dtos = scope.Database.FetchOneToMany(x => x.Things, x => x.Id, sql); + var dtos = scope.Database.FetchOneToMany(x => x.Things, sql); + Assert.AreEqual(2, dtos.Count); var dto1 = dtos.FirstOrDefault(x => x.Id == 1); Assert.IsNotNull(dto1); @@ -307,86 +323,6 @@ namespace Umbraco.Tests.NuGet } } - [Test] - public void TestSqlTemplates() - { - using (var scope = ScopeProvider.CreateScope()) - { - // this can be used for queries that we know we'll use a *lot* and - // want to cache as a (static) template for ever, and ever - note - // that using a MemoryCache would allow us to set a size limit, or - // something equivalent, to reduce risk of memory explosion - var sql = SqlTemplate.Get("xxx", () => new Sql() - .Select("*") - .From("zbThing1") - .Where("id=@id", new { id = "id" })).WithNamed(new { id = 1 }); - - WriteSql(sql); - var dto = scope.Database.Fetch(sql).FirstOrDefault(); - Assert.IsNotNull(dto); - Assert.AreEqual("one", dto.Name); - - var sql2 = SqlTemplate.Get("xxx", () => throw new InvalidOperationException("Should be cached.")).With(1); - - WriteSql(sql2); - dto = scope.Database.Fetch(sql2).FirstOrDefault(); - Assert.IsNotNull(dto); - Assert.AreEqual("one", dto.Name); - - var sql3 = SqlTemplate.Get("xxx", () => throw new InvalidOperationException("Should be cached.")).WithNamed(new { id = 1 }); - - WriteSql(sql3); - dto = scope.Database.Fetch(sql3).FirstOrDefault(); - Assert.IsNotNull(dto); - Assert.AreEqual("one", dto.Name); - } - } - - public class SqlTemplate - { - private static readonly Dictionary Templates = new Dictionary(); - - private readonly string _sql; - private readonly Dictionary _args; - - public SqlTemplate(string sql, object[] args) - { - _sql = sql; - if (args.Length > 0) - _args = new Dictionary(); - for (var i = 0; i < args.Length; i++) - _args[i] = args[i].ToString(); - } - - public static SqlTemplate Get(string key, Func sqlBuilder) - { - if (Templates.TryGetValue(key, out var template)) return template; - var sql = sqlBuilder(); - return Templates[key] = new SqlTemplate(sql.SQL, sql.Arguments); - } - - // must pass the args in the proper order, faster - public Sql With(params object[] args) - { - return new Sql(_sql, args); - } - - // can pass named args, slower - // so, not much different from what Where(...) does (ie reflection) - public Sql WithNamed(object nargs) - { - var args = new object[_args.Count]; - var properties = nargs.GetType().GetProperties().ToDictionary(x => x.Name, x => x); - for (var i = 0; i < _args.Count; i++) - { - if (!properties.TryGetValue(_args[i], out var propertyInfo)) - throw new InvalidOperationException($"Invalid argument name \"{_args[i]}\"."); - args[i] = propertyInfo.GetValue(nargs); - } - return new Sql(_sql, args); - } - } - private static void WriteSql(Sql sql) { Console.WriteLine(); diff --git a/src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlCacheTests.cs b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlCacheTests.cs new file mode 100644 index 0000000000..aa12ed8ad9 --- /dev/null +++ b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlCacheTests.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NPoco; +using NUnit.Framework; + +namespace Umbraco.Tests.Persistence.NPocoTests +{ + [TestFixture] + public class NPocoSqlCacheTests + { + [Test] + public void TestSqlTemplates() + { + // this can be used for queries that we know we'll use a *lot* and + // want to cache as a (static) template for ever, and ever - note + // that using a MemoryCache would allow us to set a size limit, or + // something equivalent, to reduce risk of memory explosion + var sql = SqlTemplate.Get("xxx", () => new Sql() + .Select("*") + .From("zbThing1") + .Where("id=@id", new { id = "id" })).WithNamed(new { id = 1 }); + + WriteSql(sql); + + var sql2 = SqlTemplate.Get("xxx", () => throw new InvalidOperationException("Should be cached.")).With(1); + + WriteSql(sql2); + + var sql3 = SqlTemplate.Get("xxx", () => throw new InvalidOperationException("Should be cached.")).WithNamed(new { id = 1 }); + + WriteSql(sql3); + } + + public class SqlTemplate + { + private static readonly Dictionary Templates = new Dictionary(); + + private readonly string _sql; + private readonly Dictionary _args; + + public SqlTemplate(string sql, object[] args) + { + _sql = sql; + if (args.Length > 0) + _args = new Dictionary(); + for (var i = 0; i < args.Length; i++) + _args[i] = args[i].ToString(); + } + + public static SqlTemplate Get(string key, Func sqlBuilder) + { + if (Templates.TryGetValue(key, out var template)) return template; + var sql = sqlBuilder(); + return Templates[key] = new SqlTemplate(sql.SQL, sql.Arguments); + } + + // must pass the args in the proper order, faster + public Sql With(params object[] args) + { + return new Sql(_sql, args); + } + + // can pass named args, slower + // so, not much different from what Where(...) does (ie reflection) + public Sql WithNamed(object nargs) + { + var args = new object[_args.Count]; + var properties = nargs.GetType().GetProperties().ToDictionary(x => x.Name, x => x); + for (var i = 0; i < _args.Count; i++) + { + if (!properties.TryGetValue(_args[i], out var propertyInfo)) + throw new InvalidOperationException($"Invalid argument name \"{_args[i]}\"."); + args[i] = propertyInfo.GetValue(nargs); + } + return new Sql(_sql, args); + } + } + + private static void WriteSql(Sql sql) + { + Console.WriteLine(); + Console.WriteLine(sql.SQL); + var i = 0; + foreach (var arg in sql.Arguments) + Console.WriteLine($" @{i++}: {arg}"); + } + } +} diff --git a/src/Umbraco.Tests/Persistence/Querying/NPocoSqlTests.cs b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlTests.cs similarity index 96% rename from src/Umbraco.Tests/Persistence/Querying/NPocoSqlTests.cs rename to src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlTests.cs index d22777f5c8..1bf61f8d58 100644 --- a/src/Umbraco.Tests/Persistence/Querying/NPocoSqlTests.cs +++ b/src/Umbraco.Tests/Persistence/NPocoTests/NPocoSqlTests.cs @@ -1,274 +1,272 @@ -using System; -using System.Diagnostics; -using NPoco; -using NUnit.Framework; -using Umbraco.Core.Models.Rdbms; -using Umbraco.Core.Persistence; -using Umbraco.Tests.TestHelpers; -using Umbraco.Core.Persistence.Querying; - -namespace Umbraco.Tests.Persistence.Querying -{ - [TestFixture] - public class NPocoSqlTests : BaseUsingSqlCeSyntax - { - //x => - - [Test] - public void Where_Clause_With_Starts_With_Additional_Parameters() - { - var content = new NodeDto() { NodeId = 123, Path = "-1,123" }; - var sql = Sql().SelectAll().From() - .Where(x => x.Path.SqlStartsWith(content.Path, TextColumnType.NVarchar)); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[path]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual(content.Path + "%", sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_Starts_With_By_Variable() - { - var content = new NodeDto() {NodeId = 123, Path = "-1,123"}; - var sql = Sql().SelectAll().From() - .Where(x => x.Path.StartsWith(content.Path) && x.NodeId != content.NodeId); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[path]) LIKE upper(@0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(2, sql.Arguments.Length); - Assert.AreEqual(content.Path + "%", sql.Arguments[0]); - Assert.AreEqual(content.NodeId, sql.Arguments[1]); - } - - [Test] - public void Where_Clause_With_Not_Starts_With() - { - const int level = 1; - var sql = Sql().SelectAll().From() - .Where(x => x.Level == level && !x.Path.StartsWith("-20")); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(2, sql.Arguments.Length); - Assert.AreEqual(level, sql.Arguments[0]); - Assert.AreEqual("-20%", sql.Arguments[1]); - } - - [Test] - public void Where_Clause_With_EqualsFalse_Starts_With() - { - const int level = 1; - var sql = Sql().SelectAll().From() - .Where(x => x.Level == level && x.Path.StartsWith("-20") == false); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(2, sql.Arguments.Length); - Assert.AreEqual(level, sql.Arguments[0]); - Assert.AreEqual("-20%", sql.Arguments[1]); - } - - [Test] - public void Where_Clause_With_Equals_Clause() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Text.Equals("Hello@world.com")); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) = upper(@0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual("Hello@world.com", sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_False_Boolean() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Trashed == false); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual(true, sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_EqualsFalse_Boolean() - { - var sql = Sql().SelectAll().From().Where(x => x.Trashed == false); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual(true, sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_Boolean() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Trashed); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ([umbracoNode].[trashed] = @0)", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual(true, sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_ToUpper() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Text.ToUpper() == "hello".ToUpper()); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[text]) = upper(@0)))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual("hello", sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_ToString() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Text == 1.ToString()); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[text] = @0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual("1", sql.Arguments[0]); - } - - [Test] - public void Where_Clause_With_Wildcard() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Text.StartsWith("D")); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual("D%", sql.Arguments[0]); - } - - [Test] - public void Where_Clause_Single_Constant() - { - var sql = Sql().SelectAll().From() - .Where(x => x.NodeId == 2); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[id] = @0))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(1, sql.Arguments.Length); - Assert.AreEqual(2, sql.Arguments[0]); - } - - [Test] - public void Where_Clause_And_Constant() - { - var sql = Sql().SelectAll().From() - .Where(x => x.NodeId != 2 && x.NodeId != 3); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[id] <> @0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(2, sql.Arguments.Length); - Assert.AreEqual(2, sql.Arguments[0]); - Assert.AreEqual(3, sql.Arguments[1]); - } - - [Test] - public void Where_Clause_Or_Constant() - { - var sql = Sql().SelectAll().From() - .Where(x => x.Text == "hello" || x.NodeId == 3); - - Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[text] = @0) OR ([umbracoNode].[id] = @1)))", sql.SQL.Replace("\n", " ")); - Assert.AreEqual(2, sql.Arguments.Length); - Assert.AreEqual("hello", sql.Arguments[0]); - Assert.AreEqual(3, sql.Arguments[1]); - } - - [Test] - public void Can_Select_From_With_Type() - { - var expected = Sql(); - expected.SelectAll().From("[cmsContent]"); - - var sql = Sql(); - sql.SelectAll().From(); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - - [Test] - public void Can_InnerJoin_With_Types() - { - var expected = Sql(); - expected.SelectAll() - .From("[cmsDocument]") - .InnerJoin("[cmsContentVersion]") - .On("[cmsDocument].[versionId] = [cmsContentVersion].[VersionId]"); - - var sql = Sql(); - sql.SelectAll().From() - .InnerJoin() - .On(left => left.VersionId, right => right.VersionId); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - - [Test] - public void Can_OrderBy_With_Type() - { - var expected = Sql(); - expected.SelectAll().From("[cmsContent]").OrderBy("([cmsContent].[contentType])"); - - var sql = Sql(); - sql.SelectAll().From().OrderBy(x => x.ContentTypeId); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - - [Test] - public void Can_GroupBy_With_Type() - { - var expected = Sql(); - expected.SelectAll().From("[cmsContent]").GroupBy("[contentType]"); - - var sql = Sql(); - sql.SelectAll().From().GroupBy(x => x.ContentTypeId); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - - [Test] - public void Can_Use_Where_Predicate() - { - var expected = Sql(); - expected.SelectAll().From("[cmsContent]").Where("([cmsContent].[nodeId] = @0)", 1045); - - var sql = Sql(); - sql.SelectAll().From().Where(x => x.NodeId == 1045); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - - [Test] - public void Can_Use_Where_And_Predicate() - { - var expected = Sql(); - expected.SelectAll() - .From("[cmsContent]") - .Where("([cmsContent].[nodeId] = @0)", 1045) - .Where("([cmsContent].[contentType] = @0)", 1050); - - var sql = Sql(); - sql.SelectAll() - .From() - .Where(x => x.NodeId == 1045) - .Where(x => x.ContentTypeId == 1050); - - Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); - - Debug.Print(sql.SQL); - } - } -} +using System.Diagnostics; +using NUnit.Framework; +using Umbraco.Core.Models.Rdbms; +using Umbraco.Core.Persistence; +using Umbraco.Core.Persistence.Querying; +using Umbraco.Tests.TestHelpers; + +namespace Umbraco.Tests.Persistence.NPocoTests +{ + [TestFixture] + public class NPocoSqlTests : BaseUsingSqlCeSyntax + { + //x => + + [Test] + public void Where_Clause_With_Starts_With_Additional_Parameters() + { + var content = new NodeDto() { NodeId = 123, Path = "-1,123" }; + var sql = Sql().SelectAll().From() + .Where(x => x.Path.SqlStartsWith(content.Path, TextColumnType.NVarchar)); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[path]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual(content.Path + "%", sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_Starts_With_By_Variable() + { + var content = new NodeDto() {NodeId = 123, Path = "-1,123"}; + var sql = Sql().SelectAll().From() + .Where(x => x.Path.StartsWith(content.Path) && x.NodeId != content.NodeId); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[path]) LIKE upper(@0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(2, sql.Arguments.Length); + Assert.AreEqual(content.Path + "%", sql.Arguments[0]); + Assert.AreEqual(content.NodeId, sql.Arguments[1]); + } + + [Test] + public void Where_Clause_With_Not_Starts_With() + { + const int level = 1; + var sql = Sql().SelectAll().From() + .Where(x => x.Level == level && !x.Path.StartsWith("-20")); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(2, sql.Arguments.Length); + Assert.AreEqual(level, sql.Arguments[0]); + Assert.AreEqual("-20%", sql.Arguments[1]); + } + + [Test] + public void Where_Clause_With_EqualsFalse_Starts_With() + { + const int level = 1; + var sql = Sql().SelectAll().From() + .Where(x => x.Level == level && x.Path.StartsWith("-20") == false); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[level] = @0) AND NOT (upper([umbracoNode].[path]) LIKE upper(@1))))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(2, sql.Arguments.Length); + Assert.AreEqual(level, sql.Arguments[0]); + Assert.AreEqual("-20%", sql.Arguments[1]); + } + + [Test] + public void Where_Clause_With_Equals_Clause() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Text.Equals("Hello@world.com")); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) = upper(@0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual("Hello@world.com", sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_False_Boolean() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Trashed == false); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual(true, sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_EqualsFalse_Boolean() + { + var sql = Sql().SelectAll().From().Where(x => x.Trashed == false); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (NOT ([umbracoNode].[trashed] = @0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual(true, sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_Boolean() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Trashed); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ([umbracoNode].[trashed] = @0)", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual(true, sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_ToUpper() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Text.ToUpper() == "hello".ToUpper()); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((upper([umbracoNode].[text]) = upper(@0)))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual("hello", sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_ToString() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Text == 1.ToString()); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[text] = @0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual("1", sql.Arguments[0]); + } + + [Test] + public void Where_Clause_With_Wildcard() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Text.StartsWith("D")); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (upper([umbracoNode].[text]) LIKE upper(@0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual("D%", sql.Arguments[0]); + } + + [Test] + public void Where_Clause_Single_Constant() + { + var sql = Sql().SelectAll().From() + .Where(x => x.NodeId == 2); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE (([umbracoNode].[id] = @0))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(1, sql.Arguments.Length); + Assert.AreEqual(2, sql.Arguments[0]); + } + + [Test] + public void Where_Clause_And_Constant() + { + var sql = Sql().SelectAll().From() + .Where(x => x.NodeId != 2 && x.NodeId != 3); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[id] <> @0) AND ([umbracoNode].[id] <> @1)))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(2, sql.Arguments.Length); + Assert.AreEqual(2, sql.Arguments[0]); + Assert.AreEqual(3, sql.Arguments[1]); + } + + [Test] + public void Where_Clause_Or_Constant() + { + var sql = Sql().SelectAll().From() + .Where(x => x.Text == "hello" || x.NodeId == 3); + + Assert.AreEqual("SELECT * FROM [umbracoNode] WHERE ((([umbracoNode].[text] = @0) OR ([umbracoNode].[id] = @1)))", sql.SQL.Replace("\n", " ")); + Assert.AreEqual(2, sql.Arguments.Length); + Assert.AreEqual("hello", sql.Arguments[0]); + Assert.AreEqual(3, sql.Arguments[1]); + } + + [Test] + public void Can_Select_From_With_Type() + { + var expected = Sql(); + expected.SelectAll().From("[cmsContent]"); + + var sql = Sql(); + sql.SelectAll().From(); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + + [Test] + public void Can_InnerJoin_With_Types() + { + var expected = Sql(); + expected.SelectAll() + .From("[cmsDocument]") + .InnerJoin("[cmsContentVersion]") + .On("[cmsDocument].[versionId] = [cmsContentVersion].[VersionId]"); + + var sql = Sql(); + sql.SelectAll().From() + .InnerJoin() + .On(left => left.VersionId, right => right.VersionId); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + + [Test] + public void Can_OrderBy_With_Type() + { + var expected = Sql(); + expected.SelectAll().From("[cmsContent]").OrderBy("([cmsContent].[contentType])"); + + var sql = Sql(); + sql.SelectAll().From().OrderBy(x => x.ContentTypeId); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + + [Test] + public void Can_GroupBy_With_Type() + { + var expected = Sql(); + expected.SelectAll().From("[cmsContent]").GroupBy("[contentType]"); + + var sql = Sql(); + sql.SelectAll().From().GroupBy(x => x.ContentTypeId); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + + [Test] + public void Can_Use_Where_Predicate() + { + var expected = Sql(); + expected.SelectAll().From("[cmsContent]").Where("([cmsContent].[nodeId] = @0)", 1045); + + var sql = Sql(); + sql.SelectAll().From().Where(x => x.NodeId == 1045); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + + [Test] + public void Can_Use_Where_And_Predicate() + { + var expected = Sql(); + expected.SelectAll() + .From("[cmsContent]") + .Where("([cmsContent].[nodeId] = @0)", 1045) + .Where("([cmsContent].[contentType] = @0)", 1050); + + var sql = Sql(); + sql.SelectAll() + .From() + .Where(x => x.NodeId == 1045) + .Where(x => x.ContentTypeId == 1050); + + Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); + + Debug.Print(sql.SQL); + } + } +} diff --git a/src/Umbraco.Tests/Persistence/PetaPocoCachesTest.cs b/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs similarity index 99% rename from src/Umbraco.Tests/Persistence/PetaPocoCachesTest.cs rename to src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs index 4a77a0b22a..2e2bb7b56c 100644 --- a/src/Umbraco.Tests/Persistence/PetaPocoCachesTest.cs +++ b/src/Umbraco.Tests/Persistence/NPocoTests/PetaPocoCachesTest.cs @@ -12,7 +12,7 @@ using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; -namespace Umbraco.Tests.Persistence +namespace Umbraco.Tests.Persistence.NPocoTests { // fixme.npoco - what shall we do with those tests? // diff --git a/src/Umbraco.Tests/Persistence/Querying/QueryBuilderTests.cs b/src/Umbraco.Tests/Persistence/Querying/QueryBuilderTests.cs index 25142c365e..eacd194bd7 100644 --- a/src/Umbraco.Tests/Persistence/Querying/QueryBuilderTests.cs +++ b/src/Umbraco.Tests/Persistence/Querying/QueryBuilderTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Diagnostics; -using NPoco; +using System.Diagnostics; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; @@ -14,8 +12,6 @@ namespace Umbraco.Tests.Persistence.Querying [TestFixture] public class QueryBuilderTests : BaseUsingSqlCeSyntax { - - [Test] public void Can_Build_StartsWith_Query_For_IContent() { diff --git a/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs index 73bef21bfd..7f9d97e62e 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/UserGroupRepositoryTest.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core.Logging; @@ -17,7 +18,7 @@ namespace Umbraco.Tests.Persistence.Repositories { private UserGroupRepository CreateRepository(IScopeUnitOfWork unitOfWork) { - return new UserGroupRepository(unitOfWork, Core.Cache.CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); + return new UserGroupRepository(unitOfWork, Core.Cache.CacheHelper.CreateDisabledCacheHelper(), Mock.Of()); } [Test] @@ -336,8 +337,13 @@ namespace Umbraco.Tests.Persistence.Repositories repository.AddOrUpdate(groups[2]); unitOfWork.Complete(); + for (var i = 0; i < 3; i++) + Assert.IsNotNull(repository.Get(groups[i].Id)); + // Assert - var result = repository.GetAll((int)groups[0].Id, (int)groups[1].Id, (int)groups[2].Id).ToArray(); + var result = repository.GetAll(groups[0].Id, groups[1].Id, groups[2].Id).ToArray(); + Assert.AreEqual(3, result.Length); + Assert.AreEqual(3, result[0].AllowedSections.Count()); Assert.IsTrue(result[0].AllowedSections.Contains("content")); Assert.IsTrue(result[0].AllowedSections.Contains("media")); @@ -396,7 +402,7 @@ namespace Umbraco.Tests.Persistence.Repositories // Act var groups = repository.GetGroupsAssignedToSection("test1"); - // Assert + // Assert Assert.AreEqual(2, groups.Count()); var names = groups.Select(x => x.Name).ToArray(); Assert.IsTrue(names.Contains("TestUserGroup1")); diff --git a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs index 0b13d34204..5258eb0e86 100644 --- a/src/Umbraco.Tests/Plugins/PluginManagerTests.cs +++ b/src/Umbraco.Tests/Plugins/PluginManagerTests.cs @@ -248,8 +248,8 @@ AnotherContentFinder [Test] public void Ensure_Only_One_Type_List_Created() { - var foundTypes1 = _manager.ResolveFindMeTypes(); - var foundTypes2 = _manager.ResolveFindMeTypes(); + _ = _manager.ResolveFindMeTypes(); + _ = _manager.ResolveFindMeTypes(); Assert.AreEqual(1, _manager.TypeLists.Count(x => x.BaseType == typeof(IFindMe) && x.AttributeType == null)); } @@ -257,7 +257,7 @@ AnotherContentFinder public void Resolves_Assigned_Mappers() { var foundTypes1 = _manager.GetAssignedMapperTypes(); - Assert.AreEqual(29, foundTypes1.Count()); // 29 classes in the solution implement BaseMapper + Assert.AreEqual(29, foundTypes1.Count()); } [Test] @@ -271,14 +271,14 @@ AnotherContentFinder public void Resolves_Actions() { var actions = _manager.GetActions(); - Assert.AreEqual(36, actions.Count()); // 36 classes in the solution implement IAction + Assert.AreEqual(37, actions.Count()); } [Test] public void Resolves_Trees() { var trees = _manager.GetTrees(); - Assert.AreEqual(5, trees.Count()); // 5 classes in the solution implement BaseTree + Assert.AreEqual(5, trees.Count()); } [Test] diff --git a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs index a6ac604d6b..6b88c0e2ae 100644 --- a/src/Umbraco.Tests/Plugins/TypeFinderTests.cs +++ b/src/Umbraco.Tests/Plugins/TypeFinderTests.cs @@ -90,7 +90,7 @@ namespace Umbraco.Tests.Plugins Assert.AreEqual(0, typesFound.Count()); // 0 classes in _assemblies are marked with [Tree] typesFound = TypeFinder.FindClassesWithAttribute(new[] { typeof (UmbracoContext).Assembly }); - Assert.AreEqual(22, typesFound.Count()); // 22 classes in Umbraco.Web are marked with [Tree] + Assert.AreEqual(23, typesFound.Count()); // + classes in Umbraco.Web are marked with [Tree] } private static ProfilingLogger GetTestProfilingLogger() diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentExtensionTests.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentExtensionTests.cs index 4a77db39e1..ab4b1138c5 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentExtensionTests.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentExtensionTests.cs @@ -49,6 +49,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void IsDocumentType_Recursive_BaseType_ReturnsTrue() { + ContentTypesCache.GetPublishedContentTypeByAlias = null; // fixme this is not pretty InitializeInheritedContentTypes(); var publishedContent = ctx.ContentCache.GetById(1100); @@ -70,9 +71,9 @@ namespace Umbraco.Tests.PublishedContent if (createContentTypes) { var contentTypeService = Current.Services.ContentTypeService; - var baseType = new ContentType(-1) {Alias = "base", Name = "Base"}; + var baseType = new ContentType(-1) { Alias = "base", Name = "Base" }; const string contentTypeAlias = "inherited"; - var inheritedType = new ContentType(baseType, contentTypeAlias) {Alias = contentTypeAlias, Name = "Inherited"}; + var inheritedType = new ContentType(baseType, contentTypeAlias) { Alias = contentTypeAlias, Name = "Inherited" }; contentTypeService.Save(baseType); contentTypeService.Save(inheritedType); createContentTypes = false; diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentTestBase.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentTestBase.cs index 3511df769f..cb75758e88 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentTestBase.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentTestBase.cs @@ -5,6 +5,7 @@ using Umbraco.Core.PropertyEditors; using Umbraco.Core.PropertyEditors.ValueConverters; using Umbraco.Tests.TestHelpers; using Umbraco.Web; +using LightInject; namespace Umbraco.Tests.PublishedContent { @@ -24,7 +25,7 @@ namespace Umbraco.Tests.PublishedContent new PublishedPropertyType("content", 0, Constants.PropertyEditors.TinyMCEAlias), }; var type = new AutoPublishedContentType(0, "anything", propertyTypes); - ContentTypesCache.GetPublishedContentTypeByAlias = (alias) => type; + ContentTypesCache.GetPublishedContentTypeByAlias = alias => type; var umbracoContext = GetUmbracoContext("/test"); Umbraco.Web.Composing.Current.UmbracoContextAccessor.UmbracoContext = umbracoContext; @@ -36,7 +37,11 @@ namespace Umbraco.Tests.PublishedContent // fixme - what about the if (PropertyValueConvertersResolver.HasCurrent == false) ?? // can we risk double - registering and then, what happens? - Container.RegisterCollectionBuilder() + + var builder = Container.TryGetInstance() + ?? Container.RegisterCollectionBuilder(); + + builder.Clear() .Append() .Append() .Append(); diff --git a/src/Umbraco.Tests/Services/ContentServiceTests.cs b/src/Umbraco.Tests/Services/ContentServiceTests.cs index 250d506077..57db48fb6b 100644 --- a/src/Umbraco.Tests/Services/ContentServiceTests.cs +++ b/src/Umbraco.Tests/Services/ContentServiceTests.cs @@ -72,9 +72,9 @@ namespace Umbraco.Tests.Services contentService.SaveBlueprint(blueprint); var found = contentService.GetBlueprintsForContentTypes().ToArray(); - Assert.AreEqual(1, found.Length); - - //ensures it's not found by normal content + Assert.AreEqual(1, found.Length); + + //ensures it's not found by normal content var contentFound = contentService.GetById(found[0].Id); Assert.IsNull(contentFound); } @@ -144,8 +144,8 @@ namespace Umbraco.Tests.Services { var blueprint = MockedContent.CreateTextpageContent(i % 2 == 0 ? ct1 : ct2, "hello" + i, -1); contentService.SaveBlueprint(blueprint); - } - + } + var found = contentService.GetBlueprintsForContentTypes().ToArray(); Assert.AreEqual(10, found.Length); @@ -1333,7 +1333,7 @@ namespace Umbraco.Tests.Services Assert.That(content.Published, Is.True); Assert.That(published, Is.True); } - + /// /// Try to immitate a new child content item being created through the UI. /// This content item will have no Id, Path or Identity. @@ -1347,15 +1347,15 @@ namespace Umbraco.Tests.Services // Arrange var contentService = ServiceContext.ContentService; var content = contentService.CreateContent("Home US", -1, "umbTextpage", 0); - content.SetValue("author", "Barack Obama"); - + content.SetValue("author", "Barack Obama"); + // Act var published = contentService.SaveAndPublish(content, 0); - var childContent = contentService.CreateContent("Child", content.Id, "umbTextpage", 0); - // Reset all identity properties + var childContent = contentService.CreateContent("Child", content.Id, "umbTextpage", 0); + // Reset all identity properties childContent.Id = 0; - childContent.Path = null; - ((Content)childContent).ResetIdentity(); + childContent.Path = null; + ((Content)childContent).ResetIdentity(); var childPublished = contentService.SaveAndPublish(childContent, 0); // Assert @@ -1574,8 +1574,8 @@ namespace Umbraco.Tests.Services ServiceContext.ContentTypeService.Save(contentType); var parentPage = MockedContent.CreateSimpleContent(contentType); - ServiceContext.ContentService.Save(parentPage); - + ServiceContext.ContentService.Save(parentPage); + var childPage = MockedContent.CreateSimpleContent(contentType, "child", parentPage); ServiceContext.ContentService.Save(childPage); //assign explicit permissions to the child @@ -1637,8 +1637,8 @@ namespace Umbraco.Tests.Services ServiceContext.ContentService.AssignContentPermission(parentPage2, 'B', new[] { userGroup.Id }); //Now copy, what should happen is the child pages will now have permissions inherited from the new parent - var copy = ServiceContext.ContentService.Copy(childPage1, parentPage2.Id, false, true); - + var copy = ServiceContext.ContentService.Copy(childPage1, parentPage2.Id, false, true); + descendants = ServiceContext.ContentService.GetDescendants(parentPage2).ToArray(); Assert.AreEqual(3, descendants.Length); @@ -1686,11 +1686,11 @@ namespace Umbraco.Tests.Services var editorGroup = ServiceContext.UserService.GetUserGroupByAlias("editor"); editorGroup.StartContentId = content1.Id; - ServiceContext.UserService.Save(editorGroup); + ServiceContext.UserService.Save(editorGroup); var admin = ServiceContext.UserService.GetUserById(0); admin.StartContentIds = new[] {content1.Id}; - ServiceContext.UserService.Save(admin); + ServiceContext.UserService.Save(admin); ServiceContext.RelationService.Save(new RelationType(Constants.ObjectTypes.Document, Constants.ObjectTypes.Document, "test")); Assert.IsNotNull(ServiceContext.RelationService.Relate(content1, content2, "test")); diff --git a/src/Umbraco.Tests/Services/MemberServiceTests.cs b/src/Umbraco.Tests/Services/MemberServiceTests.cs index 9b1b57e9a0..6eb0ec0ab7 100644 --- a/src/Umbraco.Tests/Services/MemberServiceTests.cs +++ b/src/Umbraco.Tests/Services/MemberServiceTests.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Web.Security; -using NPoco; using Moq; using NUnit.Framework; using Umbraco.Core; @@ -15,11 +14,7 @@ using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; -using Umbraco.Core.Persistence.Repositories; -using Umbraco.Core.Persistence.UnitOfWork; -using Umbraco.Core.Security; using Umbraco.Core.Services; -using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Security.Providers; @@ -35,7 +30,7 @@ namespace Umbraco.Tests.Services base.SetUp(); //hack! but we have no choice until we remove the SavePassword method from IMemberService - var providerMock = new Mock(ServiceContext.MemberService) { CallBase = true }; + var providerMock = new Mock(ServiceContext.MemberService, ServiceContext.MemberTypeService) { CallBase = true }; providerMock.Setup(@base => @base.AllowManuallyChangingPassword).Returns(false); providerMock.Setup(@base => @base.PasswordFormat).Returns(MembershipPasswordFormat.Hashed); var provider = providerMock.Object; diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index 894e69a7ca..7252dfe166 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -5,6 +5,7 @@ using System.Security.Cryptography; using System.Text; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Exceptions; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Tests.TestHelpers.Entities; @@ -860,7 +861,7 @@ namespace Umbraco.Tests.Services var userService = ServiceContext.UserService; // Act & Assert - Assert.Throws(() => userService.CreateUserWithIdentity(string.Empty, "john@umbraco.io")); + Assert.Throws(() => userService.CreateUserWithIdentity(string.Empty, "john@umbraco.io")); } [Test] diff --git a/src/Umbraco.Tests/StringNewlineExtensions.cs b/src/Umbraco.Tests/StringNewlineExtensions.cs index 7e52e0f061..b26f345788 100644 --- a/src/Umbraco.Tests/StringNewlineExtensions.cs +++ b/src/Umbraco.Tests/StringNewlineExtensions.cs @@ -23,7 +23,21 @@ { if (string.IsNullOrEmpty(text)) return text; text = text.Replace("\r", ""); // remove CR - text = text.Replace("\n", "\r\n"); // add CR everywhere + text = text.Replace("\n", "\r\n"); // add CRLF everywhere + return text; + } + + /// + /// Replaces Cr/Lf by a single space. + /// + /// The text to filter. + /// The filtered text. + public static string NoCrLf(this string text) + { + if (string.IsNullOrEmpty(text)) return text; + text = text.Replace("\r\n", " "); // remove CRLF + text = text.Replace("\r", " "); // remove CR + text = text.Replace("\n", " "); // remove LF return text; } } diff --git a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs index f631ccbf38..8a0fe2f323 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseUsingSqlCeSyntax.cs @@ -48,9 +48,9 @@ namespace Umbraco.Tests.TestHelpers .Add(() => Current.TypeLoader.GetAssignedMapperTypes()); Mappers = container.GetInstance(); - var mappers = new NPoco.MapperCollection { new PocoMapper() }; - var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, mappers).Init()); - SqlContext = new SqlContext(sqlSyntax, pocoDataFactory, DatabaseType.SQLCe); + var pocoMappers = new NPoco.MapperCollection { new PocoMapper() }; + var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init()); + SqlContext = new SqlContext(sqlSyntax, pocoDataFactory, DatabaseType.SQLCe, Mappers); SetUp(); } diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 54d50cf953..146975e960 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -13,6 +13,7 @@ using Semver; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Dictionary; using Umbraco.Core.Models; @@ -62,7 +63,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting sectionService:Mock.Of()); //ensure the configuration matches the current version for tests - SettingsForTests.ConfigurationStatus = Current.RuntimeState.SemanticVersion.ToSemanticString(); + SettingsForTests.ConfigurationStatus = UmbracoVersion.SemanticVersion.ToSemanticString(); // fixme v8? ////new app context diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index eee2043879..61fe940d17 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -30,6 +30,7 @@ using Umbraco.Web; using Umbraco.Web.DI; using Umbraco.Web.Services; using Umbraco.Examine; +using Umbraco.Web._Legacy.Actions; using Current = Umbraco.Core.Composing.Current; namespace Umbraco.Tests.Testing @@ -127,6 +128,7 @@ namespace Umbraco.Tests.Testing ComposePluginManager(Options.PluginManager); ComposeDatabase(Options.Database); ComposeApplication(Options.WithApplication); + // etc ComposeWtf(); @@ -169,6 +171,17 @@ namespace Umbraco.Tests.Testing // imported from TestWithSettingsBase // which was inherited by TestWithApplicationBase so pretty much used everywhere Umbraco.Web.Composing.Current.UmbracoContextAccessor = new TestUmbracoContextAccessor(); + + // what else? + var runtimeStateMock = new Mock(); + runtimeStateMock.Setup(x => x.Level).Returns(RuntimeLevel.Run); + Container.RegisterSingleton(f => runtimeStateMock.Object); + + // ah... + Container.RegisterCollectionBuilder() + .SetProducer(Enumerable.Empty); + + Container.RegisterCollectionBuilder(); } protected virtual void ComposeCacheHelper() diff --git a/src/Umbraco.Tests/Umbraco.Tests.csproj b/src/Umbraco.Tests/Umbraco.Tests.csproj index de1c00c907..780333b691 100644 --- a/src/Umbraco.Tests/Umbraco.Tests.csproj +++ b/src/Umbraco.Tests/Umbraco.Tests.csproj @@ -227,7 +227,8 @@ - + + @@ -259,7 +260,7 @@ - + @@ -295,7 +296,7 @@ - + @@ -390,7 +391,7 @@ - + @@ -489,7 +490,7 @@ - + diff --git a/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs b/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs index d81c9351be..3a56be14ab 100644 --- a/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs +++ b/src/Umbraco.Tests/Web/Controllers/UsersControllerTests.cs @@ -29,7 +29,7 @@ namespace Umbraco.Tests.Web.Controllers public class UsersControllerTests : TestWithDatabaseBase { [Test] - public async void Save_User() + public async System.Threading.Tasks.Task Save_User() { var runner = new TestRunner((message, helper) => { @@ -83,7 +83,7 @@ namespace Umbraco.Tests.Web.Controllers [Test] - public async void GetPagedUsers_Empty() + public async System.Threading.Tasks.Task GetPagedUsers_Empty() { var runner = new TestRunner((message, helper) => { @@ -100,7 +100,7 @@ namespace Umbraco.Tests.Web.Controllers } [Test] - public async void GetPagedUsers_10() + public async System.Threading.Tasks.Task GetPagedUsers_10() { var runner = new TestRunner((message, helper) => { diff --git a/src/Umbraco.Web/DI/WebMappingProfilesCompositionRoot.cs b/src/Umbraco.Web/DI/WebMappingProfilesCompositionRoot.cs index 6dd06c17b5..347fb84996 100644 --- a/src/Umbraco.Web/DI/WebMappingProfilesCompositionRoot.cs +++ b/src/Umbraco.Web/DI/WebMappingProfilesCompositionRoot.cs @@ -7,20 +7,20 @@ namespace Umbraco.Web.DI { public void Compose(IServiceRegistry container) { - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); - container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); + container.Register(); } } } diff --git a/src/Umbraco.Web/Models/Mapping/CodeFileProfile.cs b/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs similarity index 96% rename from src/Umbraco.Web/Models/Mapping/CodeFileProfile.cs rename to src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs index b165bc3e35..17114ace87 100644 --- a/src/Umbraco.Web/Models/Mapping/CodeFileProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/CodeFileMapperProfile.cs @@ -4,9 +4,9 @@ using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { - public class CodeFileProfile : Profile + public class CodeFileMapperProfile : Profile { - public CodeFileProfile() + public CodeFileMapperProfile() { CreateMap() .ForMember(dest => dest.FileType, opt => opt.Ignore()) diff --git a/src/Umbraco.Web/Models/Mapping/ContentProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs similarity index 98% rename from src/Umbraco.Web/Models/Mapping/ContentProfile.cs rename to src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs index 4b063460f6..1d0db16538 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentMapperProfile.cs @@ -19,9 +19,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Declares how model mappings for content /// - internal class ContentProfile : Profile + internal class ContentMapperProfile : Profile { - public ContentProfile(IUserService userService, ILocalizedTextService textService, IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService) + public ContentMapperProfile(IUserService userService, ILocalizedTextService textService, IContentService contentService, IContentTypeService contentTypeService, IDataTypeService dataTypeService) { // create, capture, cache var contentOwnerResolver = new OwnerResolver(userService); diff --git a/src/Umbraco.Web/Models/Mapping/ContentPropertyProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentPropertyMapperProfile.cs similarity index 92% rename from src/Umbraco.Web/Models/Mapping/ContentPropertyProfile.cs rename to src/Umbraco.Web/Models/Mapping/ContentPropertyMapperProfile.cs index 4ba961aeee..26cb6c40a5 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentPropertyProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentPropertyMapperProfile.cs @@ -10,11 +10,11 @@ namespace Umbraco.Web.Models.Mapping /// A mapper which declares how to map content properties. These mappings are shared among media (and probably members) which is /// why they are in their own mapper /// - internal class ContentPropertyProfile : Profile + internal class ContentPropertyMapperProfile : Profile { private readonly IDataTypeService _dataTypeService; - public ContentPropertyProfile(IDataTypeService dataTypeService) + public ContentPropertyMapperProfile(IDataTypeService dataTypeService) { _dataTypeService = dataTypeService; diff --git a/src/Umbraco.Web/Models/Mapping/ContentTypeProfile.cs b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs similarity index 98% rename from src/Umbraco.Web/Models/Mapping/ContentTypeProfile.cs rename to src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs index 08be60b26d..e1bfdd8030 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentTypeProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentTypeMapperProfile.cs @@ -12,7 +12,7 @@ namespace Umbraco.Web.Models.Mapping /// /// Defines mappings for content/media/members type mappings /// - internal class ContentTypeProfile : Profile + internal class ContentTypeMapperProfile : Profile { private readonly PropertyEditorCollection _propertyEditors; private readonly IDataTypeService _dataTypeService; @@ -20,7 +20,7 @@ namespace Umbraco.Web.Models.Mapping private readonly IContentTypeService _contentTypeService; private readonly IMediaTypeService _mediaTypeService; - public ContentTypeProfile(PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService) + public ContentTypeMapperProfile(PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService) { _propertyEditors = propertyEditors; _dataTypeService = dataTypeService; diff --git a/src/Umbraco.Web/Models/Mapping/CreatorResolver.cs b/src/Umbraco.Web/Models/Mapping/CreatorResolver.cs index 4c9eff3434..0874c2cd4f 100644 --- a/src/Umbraco.Web/Models/Mapping/CreatorResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/CreatorResolver.cs @@ -2,7 +2,6 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; using UserProfile = Umbraco.Web.Models.ContentEditing.UserProfile; namespace Umbraco.Web.Models.Mapping diff --git a/src/Umbraco.Web/Models/Mapping/DashboardProfile.cs b/src/Umbraco.Web/Models/Mapping/DashboardMapperProfile.cs similarity index 88% rename from src/Umbraco.Web/Models/Mapping/DashboardProfile.cs rename to src/Umbraco.Web/Models/Mapping/DashboardMapperProfile.cs index 4d5156f2a6..aa2608875b 100644 --- a/src/Umbraco.Web/Models/Mapping/DashboardProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/DashboardMapperProfile.cs @@ -7,9 +7,9 @@ namespace Umbraco.Web.Models.Mapping /// /// A model mapper used to map models for the various dashboards /// - internal class DashboardProfile : Profile + internal class DashboardMapperProfile : Profile { - public DashboardProfile() + public DashboardMapperProfile() { CreateMap() .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => UmbracoContext.Current.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url))) diff --git a/src/Umbraco.Web/Models/Mapping/DataTypeProfile.cs b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs similarity index 98% rename from src/Umbraco.Web/Models/Mapping/DataTypeProfile.cs rename to src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs index a6c64834ef..6fc2e6376a 100644 --- a/src/Umbraco.Web/Models/Mapping/DataTypeProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs @@ -15,9 +15,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Configure's model mappings for Data types /// - internal class DataTypeProfile : Profile + internal class DataTypeMapperProfile : Profile { - public DataTypeProfile(IDataTypeService dataTypeService) + public DataTypeMapperProfile(IDataTypeService dataTypeService) { var lazyDataTypeService = new Lazy(() => dataTypeService); diff --git a/src/Umbraco.Web/Models/Mapping/EntityProfile.cs b/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs similarity index 99% rename from src/Umbraco.Web/Models/Mapping/EntityProfile.cs rename to src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs index cbce64ce09..b4775a3966 100644 --- a/src/Umbraco.Web/Models/Mapping/EntityProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/EntityMapperProfile.cs @@ -13,9 +13,9 @@ using Umbraco.Examine; namespace Umbraco.Web.Models.Mapping { - internal class EntityProfile : Profile + internal class EntityMapperProfile : Profile { - public EntityProfile() + public EntityMapperProfile() { // create, capture, cache var contentTypeUdiResolver = new ContentTypeUdiResolver(); diff --git a/src/Umbraco.Web/Models/Mapping/MacroProfile.cs b/src/Umbraco.Web/Models/Mapping/MacroMapperProfile.cs similarity index 89% rename from src/Umbraco.Web/Models/Mapping/MacroProfile.cs rename to src/Umbraco.Web/Models/Mapping/MacroMapperProfile.cs index 5179307b74..4b162be3e2 100644 --- a/src/Umbraco.Web/Models/Mapping/MacroProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/MacroMapperProfile.cs @@ -12,9 +12,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Declares model mappings for macros. /// - internal class MacroProfile : Profile + internal class MacroMapperProfile : Profile { - public MacroProfile() + public MacroMapperProfile() { //FROM IMacro TO EntityBasic CreateMap() @@ -41,7 +41,7 @@ namespace Umbraco.Web.Models.Mapping { //we'll just map this to a text box paramEditor = Current.ParameterEditors[Constants.PropertyEditors.TextboxAlias]; - Current.Logger.Warn("Could not resolve a parameter editor with alias " + property.EditorAlias + ", a textbox will be rendered in it's place"); + Current.Logger.Warn("Could not resolve a parameter editor with alias " + property.EditorAlias + ", a textbox will be rendered in it's place"); } parameter.View = paramEditor.ValueEditor.View; diff --git a/src/Umbraco.Web/Models/Mapping/MediaProfile.cs b/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs similarity index 97% rename from src/Umbraco.Web/Models/Mapping/MediaProfile.cs rename to src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs index 482d0f33a4..13e73cc465 100644 --- a/src/Umbraco.Web/Models/Mapping/MediaProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs @@ -17,9 +17,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Declares model mappings for media. /// - internal class MediaProfile : Profile + internal class MediaMapperProfile : Profile { - public MediaProfile(IUserService userService, ILocalizedTextService textService, IDataTypeService dataTypeService, IMediaService mediaService, ILogger logger) + public MediaMapperProfile(IUserService userService, ILocalizedTextService textService, IDataTypeService dataTypeService, IMediaService mediaService, ILogger logger) { // create, capture, cache var mediaOwnerResolver = new OwnerResolver(userService); diff --git a/src/Umbraco.Web/Models/Mapping/MemberProfile.cs b/src/Umbraco.Web/Models/Mapping/MemberMapperProfile.cs similarity index 98% rename from src/Umbraco.Web/Models/Mapping/MemberProfile.cs rename to src/Umbraco.Web/Models/Mapping/MemberMapperProfile.cs index b893ab485d..6ce6ff7875 100644 --- a/src/Umbraco.Web/Models/Mapping/MemberProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/MemberMapperProfile.cs @@ -19,9 +19,9 @@ namespace Umbraco.Web.Models.Mapping /// /// Declares model mappings for members. /// - internal class MemberProfile : Profile + internal class MemberMapperProfile : Profile { - public MemberProfile(IUserService userService, ILocalizedTextService textService, IMemberTypeService memberTypeService, IMemberService memberService) + public MemberMapperProfile(IUserService userService, ILocalizedTextService textService, IMemberTypeService memberTypeService, IMemberService memberService) { // create, capture, cache var memberOwnerResolver = new OwnerResolver(userService); diff --git a/src/Umbraco.Web/Models/Mapping/OwnerResolver.cs b/src/Umbraco.Web/Models/Mapping/OwnerResolver.cs index 64521bae3f..e9915b66d7 100644 --- a/src/Umbraco.Web/Models/Mapping/OwnerResolver.cs +++ b/src/Umbraco.Web/Models/Mapping/OwnerResolver.cs @@ -2,7 +2,6 @@ using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Services; -using Umbraco.Web.Models.ContentEditing; using UserProfile = Umbraco.Web.Models.ContentEditing.UserProfile; namespace Umbraco.Web.Models.Mapping diff --git a/src/Umbraco.Web/Models/Mapping/RelationProfile.cs b/src/Umbraco.Web/Models/Mapping/RelationMapperProfile.cs similarity index 83% rename from src/Umbraco.Web/Models/Mapping/RelationProfile.cs rename to src/Umbraco.Web/Models/Mapping/RelationMapperProfile.cs index 9047d99aea..31acf4e5e1 100644 --- a/src/Umbraco.Web/Models/Mapping/RelationProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/RelationMapperProfile.cs @@ -5,9 +5,9 @@ using RelationType = Umbraco.Web.Models.ContentEditing.RelationType; namespace Umbraco.Web.Models.Mapping { - internal class RelationProfile : Profile + internal class RelationMapperProfile : Profile { - public RelationProfile() + public RelationMapperProfile() { //FROM IRelationType TO RelationType CreateMap(); diff --git a/src/Umbraco.Web/Models/Mapping/SectionProfile.cs b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs similarity index 59% rename from src/Umbraco.Web/Models/Mapping/SectionProfile.cs rename to src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs index ea528026c5..11b4deff48 100644 --- a/src/Umbraco.Web/Models/Mapping/SectionProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/SectionMapperProfile.cs @@ -5,17 +5,13 @@ using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { - internal class SectionProfile : Profile + internal class SectionMapperProfile : Profile { - private readonly ILocalizedTextService _textService; - - public SectionProfile(ILocalizedTextService textService) + public SectionMapperProfile(ILocalizedTextService textService) { - _textService = textService; - CreateMap() .ForMember(dest => dest.RoutePath, opt => opt.Ignore()) - .ForMember(dest => dest.Name, opt => opt.MapFrom(src => _textService.Localize("sections/" + src.Alias, (IDictionary)null))) + .ForMember(dest => dest.Name, opt => opt.MapFrom(src => textService.Localize("sections/" + src.Alias, (IDictionary)null))) .ReverseMap(); //backwards too! } } diff --git a/src/Umbraco.Web/Models/Mapping/TabProfile.cs b/src/Umbraco.Web/Models/Mapping/TagMapperProfile.cs similarity index 67% rename from src/Umbraco.Web/Models/Mapping/TabProfile.cs rename to src/Umbraco.Web/Models/Mapping/TagMapperProfile.cs index 6e05d775f1..bcb6c2bb23 100644 --- a/src/Umbraco.Web/Models/Mapping/TabProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/TagMapperProfile.cs @@ -3,9 +3,9 @@ using Umbraco.Core.Models; namespace Umbraco.Web.Models.Mapping { - internal class TabProfile : Profile + internal class TagMapperProfile : Profile { - public TabProfile() + public TagMapperProfile() { CreateMap(); } diff --git a/src/Umbraco.Web/Models/Mapping/TemplateProfile.cs b/src/Umbraco.Web/Models/Mapping/TemplateMapperProfile.cs similarity index 90% rename from src/Umbraco.Web/Models/Mapping/TemplateProfile.cs rename to src/Umbraco.Web/Models/Mapping/TemplateMapperProfile.cs index fe2ee465d0..7eb148dbca 100644 --- a/src/Umbraco.Web/Models/Mapping/TemplateProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/TemplateMapperProfile.cs @@ -4,9 +4,9 @@ using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { - internal class TemplateProfile : Profile + internal class TemplateMapperProfile : Profile { - public TemplateProfile() + public TemplateMapperProfile() { CreateMap() .ForMember(dest => dest.Notifications, opt => opt.Ignore()); diff --git a/src/Umbraco.Web/Models/Mapping/UserProfile.cs b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs similarity index 99% rename from src/Umbraco.Web/Models/Mapping/UserProfile.cs rename to src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs index b797da4148..84026a34eb 100644 --- a/src/Umbraco.Web/Models/Mapping/UserProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/UserMapperProfile.cs @@ -14,9 +14,9 @@ using Umbraco.Web._Legacy.Actions; namespace Umbraco.Web.Models.Mapping { - internal class UserProfile : Profile + internal class UserMapperProfile : Profile { - public UserProfile(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, + public UserMapperProfile(ILocalizedTextService textService, IUserService userService, IEntityService entityService, ISectionService sectionService, IRuntimeCacheProvider runtimeCache, ActionCollection actions) { diff --git a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs index ad5fa3ac29..00bd74149b 100644 --- a/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/NestedContentPropertyEditor.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web.PropertyEditors [PropertyEditor(Constants.PropertyEditors.NestedContentAlias, "Nested Content", "nestedcontent", ValueType = "JSON", Group = "lists", Icon = "icon-thumbnail-list")] public class NestedContentPropertyEditor : PropertyEditor { - private readonly PropertyEditorCollection _propertyEditors; + private readonly Lazy _propertyEditors; internal const string ContentTypeAliasPropertyKey = "ncContentTypeAlias"; @@ -29,7 +29,7 @@ namespace Umbraco.Web.PropertyEditors set => _defaultPreValues = value; } - public NestedContentPropertyEditor(ILogger logger, PropertyEditorCollection propertyEditors) + public NestedContentPropertyEditor(ILogger logger, Lazy propertyEditors) : base (logger) { _propertyEditors = propertyEditors; @@ -45,6 +45,9 @@ namespace Umbraco.Web.PropertyEditors }; } + // has to be lazy else circular dep in ctor + private PropertyEditorCollection PropertyEditors => _propertyEditors.Value; + #region Pre Value Editor protected override PreValueEditor CreatePreValueEditor() @@ -89,7 +92,7 @@ namespace Umbraco.Web.PropertyEditors protected override PropertyValueEditor CreateValueEditor() { - return new NestedContentPropertyValueEditor(base.CreateValueEditor(), _propertyEditors); + return new NestedContentPropertyValueEditor(base.CreateValueEditor(), PropertyEditors); } internal class NestedContentPropertyValueEditor : PropertyValueEditorWrapper diff --git a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs index 374920f99d..8a9fdf8081 100644 --- a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs @@ -1,14 +1,8 @@ using System.Collections.Specialized; -using System.ComponentModel.DataAnnotations; using System.Configuration.Provider; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Web.Hosting; using System.Web.Security; using Umbraco.Core; using Umbraco.Core.Models; -using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Core.Models.Membership; @@ -23,8 +17,7 @@ namespace Umbraco.Web.Security.Providers { public MembersMembershipProvider() : this(Current.Services.MemberService, Current.Services.MemberTypeService) - { - } + { } public MembersMembershipProvider(IMembershipMemberService memberService, IMemberTypeService memberTypeService) : base(memberService) @@ -43,29 +36,26 @@ namespace Umbraco.Web.Security.Providers private readonly IMemberTypeService _memberTypeService; private string _defaultMemberTypeAlias = "Member"; - private volatile bool _hasDefaultMember = false; + private volatile bool _hasDefaultMember; private static readonly object Locker = new object(); - private bool _providerKeyAsGuid = false; + private bool _providerKeyAsGuid; - public override string ProviderName - { - get { return "MembersMembershipProvider"; } - } + public override string ProviderName => "MembersMembershipProvider"; protected override MembershipUser ConvertToMembershipUser(IMember entity) { return entity.AsConcreteMembershipUser(Name, _providerKeyAsGuid); } - public string LockPropertyTypeAlias { get; private set; } - public string LastLockedOutPropertyTypeAlias { get; private set; } - public string FailedPasswordAttemptsPropertyTypeAlias { get; private set; } - public string ApprovedPropertyTypeAlias { get; private set; } - public string CommentPropertyTypeAlias { get; private set; } - public string LastLoginPropertyTypeAlias { get; private set; } - public string LastPasswordChangedPropertyTypeAlias { get; private set; } - public string PasswordRetrievalQuestionPropertyTypeAlias { get; private set; } - public string PasswordRetrievalAnswerPropertyTypeAlias { get; private set; } + public string LockPropertyTypeAlias { get; } + public string LastLockedOutPropertyTypeAlias { get; } + public string FailedPasswordAttemptsPropertyTypeAlias { get; } + public string ApprovedPropertyTypeAlias { get; } + public string CommentPropertyTypeAlias { get; } + public string LastLoginPropertyTypeAlias { get; } + public string LastPasswordChangedPropertyTypeAlias { get; } + public string PasswordRetrievalQuestionPropertyTypeAlias { get; } + public string PasswordRetrievalAnswerPropertyTypeAlias { get; } public override void Initialize(string name, NameValueCollection config) { @@ -94,7 +84,7 @@ namespace Umbraco.Web.Security.Providers protected override Attempt GetRawPassword(string username) { - var found = MemberService.GetByUsername(username); + var found = MemberService.GetByUsername(username); if (found == null) return Attempt.Fail(); return Attempt.Succeed(found.RawPasswordValue); } diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index b22111e775..4330b6d8ce 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -222,14 +222,14 @@ - + - + @@ -477,7 +477,7 @@ - + @@ -619,10 +619,10 @@ - - - - + + + + @@ -662,8 +662,8 @@ - - + + @@ -813,15 +813,15 @@ - + - - - + + + - + - + diff --git a/src/Umbraco.Web/WebRuntimeComponent.cs b/src/Umbraco.Web/WebRuntimeComponent.cs index 8d8ebccb41..7c347d67ae 100644 --- a/src/Umbraco.Web/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/WebRuntimeComponent.cs @@ -119,7 +119,7 @@ namespace Umbraco.Web // set the default RenderMvcController Current.DefaultRenderMvcControllerType = typeof(RenderMvcController); // fixme WRONG! - ActionCollectionBuilder.Register(composition.Container) + composition.Container.RegisterCollectionBuilder() .SetProducer(() => typeLoader.GetActions()); var surfaceControllerTypes = new SurfaceControllerTypeCollection(typeLoader.GetSurfaceControllers()); diff --git a/src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs b/src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs index ff767a03f3..39058d6836 100644 --- a/src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs +++ b/src/Umbraco.Web/_Legacy/Actions/ActionCollectionBuilder.cs @@ -10,15 +10,13 @@ namespace Umbraco.Web._Legacy.Actions { private static Func> _producer; - public static ActionCollectionBuilder Register(IServiceContainer container) - { - // register the builder - per container - var builderLifetime = new PerContainerLifetime(); - container.Register(builderLifetime); + // for tests only - does not register the collection + public ActionCollectionBuilder() + { } - // get the builder, get the collection lifetime - var builder = container.GetInstance(); - var collectionLifetime = builder.CollectionLifetime; + public ActionCollectionBuilder(IServiceContainer container) + { + var collectionLifetime = CollectionLifetime; // register the collection - special lifetime // the lifetime here is custom ResettablePerContainerLifetime which will manage one @@ -29,8 +27,6 @@ namespace Umbraco.Web._Legacy.Actions // had frozen. This has been replaced by the possibility here to set the producer at any // time - but the builder is internal - and all this will be gone eventually. container.Register(factory => factory.GetInstance().CreateCollection(), collectionLifetime); - - return builder; } public ActionCollection CreateCollection()