Adds a couple needed hack methods, updates ContentService to have the proper event emmitting without any nested uow's and ensuring that readonly uow's are committed.

This commit is contained in:
Shannon
2017-01-23 22:16:27 +11:00
parent ac4de99f30
commit 55eb996c19
4 changed files with 271 additions and 230 deletions

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Events
{
@@ -48,6 +49,35 @@ namespace Umbraco.Core.Events
return false;
}
/// <summary>
/// Hack: this is used to perform IsRaisedEventCancelled when a uow cannot be reused
/// </summary>
/// <typeparam name="TSender"></typeparam>
/// <typeparam name="TArgs"></typeparam>
/// <param name="eventHandler"></param>
/// <param name="args"></param>
/// <param name="sender"></param>
/// <param name="uowProvider"></param>
/// <returns></returns>
internal static bool IsRaisedEventCancelled<TSender, TArgs>(
this TypedEventHandler<TSender, TArgs> eventHandler,
TArgs args,
TSender sender,
IScopeUnitOfWorkProvider uowProvider)
where TArgs : CancellableEventArgs
{
using(var uow = uowProvider.GetReadOnlyUnitOfWork())
{
if (uow.EventManager.SupportsEventCancellation)
{
uow.EventManager.TrackEvent(eventHandler, sender, args);
return args.Cancel;
}
return false;
}
}
/// <summary>
/// Raises the event
/// </summary>
@@ -85,6 +115,31 @@ namespace Umbraco.Core.Events
eventManager.TrackEvent(eventHandler, sender, args);
}
/// <summary>
/// Hack: this is used to perform IsRaisedEventCancelled when a uow cannot be reused
/// </summary>
/// <typeparam name="TSender"></typeparam>
/// <typeparam name="TArgs"></typeparam>
/// <param name="eventHandler"></param>
/// <param name="args"></param>
/// <param name="sender"></param>
/// <param name="uowProvider"></param>
internal static void RaiseEvent<TSender, TArgs>(
this TypedEventHandler<TSender, TArgs> eventHandler,
TArgs args,
TSender sender,
IScopeUnitOfWorkProvider uowProvider)
where TArgs : EventArgs
{
//This UOW is a readonly one but needs to be committed otherwise
// it will rollback outer scopes
using (var uow = uowProvider.GetUnitOfWork())
{
uow.EventManager.TrackEvent(eventHandler, sender, args);
uow.Commit();
}
}
// moves the last handler that was added to an instance event, to first position
public static void PromoteLastHandler(object sender, string eventName)
{

View File

@@ -0,0 +1,18 @@
namespace Umbraco.Core.Persistence.UnitOfWork
{
internal static class ScopeUnitOfWorkProviderExtensions
{
/// <summary>
/// Hack: When we need a unit of work for readonly operations, the uow must be committed else the
/// outer scope will rollback, so this is a hack to create a unit of work, pre-commit it and return it
/// </summary>
/// <param name="provider"></param>
/// <returns></returns>
public static IScopeUnitOfWork GetReadOnlyUnitOfWork(this IScopeUnitOfWorkProvider provider)
{
var uow = provider.GetUnitOfWork();
uow.Commit();
return uow;
}
}
}

View File

@@ -66,7 +66,7 @@ namespace Umbraco.Core.Services
public int CountPublished(string contentTypeAlias = null)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
return repository.CountPublished();
@@ -75,7 +75,7 @@ namespace Umbraco.Core.Services
public int Count(string contentTypeAlias = null)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
return repository.Count(contentTypeAlias);
@@ -84,7 +84,7 @@ namespace Umbraco.Core.Services
public int CountChildren(int parentId, string contentTypeAlias = null)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
return repository.CountChildren(parentId, contentTypeAlias);
@@ -93,7 +93,7 @@ namespace Umbraco.Core.Services
public int CountDescendants(int parentId, string contentTypeAlias = null)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
return repository.CountDescendants(parentId, contentTypeAlias);
@@ -107,7 +107,7 @@ namespace Umbraco.Core.Services
/// <param name="permissionSet"></param>
public void ReplaceContentPermissions(EntityPermissionSet permissionSet)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
repository.ReplaceContentPermissions(permissionSet);
@@ -122,7 +122,7 @@ namespace Umbraco.Core.Services
/// <param name="userIds"></param>
public void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
repository.AssignEntityPermission(entity, permission, userIds);
@@ -136,7 +136,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content)
{
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
return repository.GetPermissionsForEntity(content.Id);
@@ -164,18 +164,20 @@ namespace Umbraco.Core.Services
var parent = GetById(content.ParentId);
content.Path = string.Concat(parent.IfNotNull(x => x.Path, content.ParentId.ToString()), ",", content.Id);
var uow = UowProvider.GetUnitOfWork();
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parentId), this, uow.EventManager))
//we are using GetReadOnlyUnitOfWork because this actually doesn't write anything!
using (var uow = UowProvider.GetReadOnlyUnitOfWork())
{
content.WasCancelled = true;
return content;
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parentId), this, uow.EventManager))
{
content.WasCancelled = true;
return content;
}
content.CreatorId = userId;
content.WriterId = userId;
Created.RaiseEvent(new NewEventArgs<IContent>(content, false, contentTypeAlias, parentId), this, uow.EventManager);
}
content.CreatorId = userId;
content.WriterId = userId;
Created.RaiseEvent(new NewEventArgs<IContent>(content, false, contentTypeAlias, parentId), this, uow.EventManager);
Audit(AuditType.New, string.Format("Content '{0}' was created", name), content.CreatorId, content.Id);
@@ -204,7 +206,8 @@ namespace Umbraco.Core.Services
var content = new Content(name, parent, contentType);
content.Path = string.Concat(parent.Path, ",", content.Id);
using (var uow = UowProvider.GetUnitOfWork())
//we are using GetReadOnlyUnitOfWork because this actually doesn't write anything!
using (var uow = UowProvider.GetReadOnlyUnitOfWork())
{
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parent), this, uow.EventManager))
{
@@ -214,13 +217,13 @@ namespace Umbraco.Core.Services
content.CreatorId = userId;
content.WriterId = userId;
Created.RaiseEvent(new NewEventArgs<IContent>(content, false, contentTypeAlias, parent), this, uow.EventManager);
Audit(AuditType.New, string.Format("Content '{0}' was created", name), content.CreatorId, content.Id);
return content;
}
Audit(AuditType.New, string.Format("Content '{0}' was created", name), content.CreatorId, content.Id);
return content;
}
/// <summary>
@@ -240,23 +243,22 @@ namespace Umbraco.Core.Services
{
var contentType = FindContentTypeByAlias(contentTypeAlias);
var content = new Content(name, parentId, contentType);
var uow = UowProvider.GetUnitOfWork();
//NOTE: I really hate the notion of these Creating/Created events - they are so inconsistent, I've only just found
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parentId), this, uow.EventManager))
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parentId), this, UowProvider))
{
content.WasCancelled = true;
return content;
}
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(content), this, uow.EventManager))
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(content), this, UowProvider))
{
content.WasCancelled = true;
return content;
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
content.CreatorId = userId;
@@ -296,22 +298,21 @@ namespace Umbraco.Core.Services
var contentType = FindContentTypeByAlias(contentTypeAlias);
var content = new Content(name, parent, contentType);
var uow = UowProvider.GetUnitOfWork();
//NOTE: I really hate the notion of these Creating/Created events - they are so inconsistent, I've only just found
// out that in these 'WithIdentity' methods, the Saving/Saved events were not fired, wtf. Anyways, they're added now.
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parent), this, uow.EventManager))
if (Creating.IsRaisedEventCancelled(new NewEventArgs<IContent>(content, contentTypeAlias, parent), this, UowProvider))
{
content.WasCancelled = true;
return content;
}
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(content), this, uow.EventManager))
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(content), this, UowProvider))
{
content.WasCancelled = true;
return content;
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
content.CreatorId = userId;
@@ -338,7 +339,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IContent"/></returns>
public IContent GetById(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
return repository.Get(id);
}
@@ -354,7 +355,7 @@ namespace Umbraco.Core.Services
var idsArray = ids.ToArray();
if (idsArray.Length == 0) return Enumerable.Empty<IContent>();
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
//ensure that the result has the order based on the ids passed in
var result = repository.GetAll(idsArray);
@@ -378,7 +379,7 @@ namespace Umbraco.Core.Services
/// <returns><see cref="IContent"/></returns>
public IContent GetById(Guid key)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Key == key);
var contents = repository.GetByQuery(query);
@@ -393,7 +394,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetContentOfContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ContentTypeId == id);
var contents = repository.GetByQuery(query);
@@ -404,7 +405,7 @@ namespace Umbraco.Core.Services
internal IEnumerable<IContent> GetPublishedContentOfContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ContentTypeId == id);
var contents = repository.GetByPublishedVersion(query);
@@ -420,9 +421,9 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetByLevel(int level)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Level == level && !x.Path.StartsWith(Constants.System.RecycleBinContent.ToInvariantString()));
var query = Query<IContent>.Builder.Where(x => x.Level == level && x.Path.StartsWith(Constants.System.RecycleBinContent.ToInvariantString()) == false);
var contents = repository.GetByQuery(query);
return contents;
@@ -436,7 +437,7 @@ namespace Umbraco.Core.Services
/// <returns>An <see cref="IContent"/> item</returns>
public IContent GetByVersion(Guid versionId)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
return repository.GetByVersion(versionId);
}
@@ -450,7 +451,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetVersions(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var versions = repository.GetAllVersions(id);
return versions;
@@ -465,7 +466,7 @@ namespace Umbraco.Core.Services
/// <returns></returns>
public IEnumerable<Guid> GetVersionIds(int id, int maxRows)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var versions = repository.GetVersionIds(id, maxRows);
return versions;
@@ -497,7 +498,7 @@ namespace Umbraco.Core.Services
if (ids.Any() == false)
return new List<IContent>();
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
return repository.GetAll(ids);
}
@@ -510,7 +511,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ParentId == id);
var contents = repository.GetByQuery(query).OrderBy(x => x.SortOrder);
@@ -564,7 +565,7 @@ namespace Umbraco.Core.Services
{
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder;
@@ -626,7 +627,7 @@ namespace Umbraco.Core.Services
{
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder;
@@ -663,7 +664,7 @@ namespace Umbraco.Core.Services
Mandate.ParameterCondition(pageIndex >= 0, "pageIndex");
Mandate.ParameterCondition(pageSize > 0, "pageSize");
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder;
@@ -686,7 +687,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetChildrenByName(int parentId, string name)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ParentId == parentId && x.Name.Contains(name));
var contents = repository.GetByQuery(query);
@@ -721,7 +722,7 @@ namespace Umbraco.Core.Services
if (content.ValidatePath() == false)
throw new InvalidDataException(string.Format("The content item {0} has an invalid path: {1} with parentID: {2}", content.Id, content.Path, content.ParentId));
var uow = UowProvider.GetUnitOfWork();
var uow = UowProvider.GetReadOnlyUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
var pathMatch = content.Path + ",";
@@ -786,7 +787,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetRootContent()
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ParentId == Constants.System.Root);
var contents = repository.GetByQuery(query);
@@ -807,7 +808,7 @@ namespace Umbraco.Core.Services
_notTrashedQuery = Query<IContent>.Builder.Where(x => x.Trashed == false);
}
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
return repository.GetByPublishedVersion(_notTrashedQuery);
}
@@ -819,7 +820,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetContentForExpiration()
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Published == true && x.ExpireDate <= DateTime.Now);
var contents = repository.GetByQuery(query);
@@ -834,7 +835,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetContentForRelease()
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Published == false && x.ReleaseDate <= DateTime.Now);
var contents = repository.GetByQuery(query);
@@ -849,7 +850,7 @@ namespace Umbraco.Core.Services
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetContentInRecycleBin()
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Path.Contains(Constants.System.RecycleBinContent.ToInvariantString()));
var contents = repository.GetByQuery(query);
@@ -872,7 +873,7 @@ namespace Umbraco.Core.Services
internal int CountChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.ParentId == id);
var count = repository.Count(query);
@@ -887,7 +888,7 @@ namespace Umbraco.Core.Services
/// <returns>True if the content has any published version otherwise False</returns>
public bool HasPublishedVersion(int id)
{
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetReadOnlyUnitOfWork()))
{
var query = Query<IContent>.Builder.Where(x => x.Published == true && x.Id == id && x.Trashed == false);
int count = repository.Count(query);
@@ -1000,70 +1001,17 @@ namespace Umbraco.Core.Services
/// <param name="userId">Optional Id of the User deleting the Content</param>
Attempt<OperationStatus> IContentServiceOperations.MoveToRecycleBin(IContent content, int userId)
{
var evtMsgs = EventMessagesFactory.Get();
var evtMsgs = EventMessagesFactory.Get();
using (new WriteLock(Locker))
{
//Hack: this ensures that the entity's path is valid and if not it fixes/persists it
//see: http://issues.umbraco.org/issue/U4-9336
content.EnsureValidPath(Logger, entity => GetById(entity.ParentId), QuickUpdate);
var originalPath = content.Path;
if (Trashing.IsRaisedEventCancelled(
new MoveEventArgs<IContent>(evtMsgs, new MoveEventInfo<IContent>(content, originalPath, Constants.System.RecycleBinContent)),
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
//Hack: this ensures that the entity's path is valid and if not it fixes/persists it
//see: http://issues.umbraco.org/issue/U4-9336
content.EnsureValidPath(Logger, entity => GetById(entity.ParentId), QuickUpdate);
var originalPath = content.Path;
if (Trashing.IsRaisedEventCancelled(
new MoveEventArgs<IContent>(evtMsgs, new MoveEventInfo<IContent>(content, originalPath, Constants.System.RecycleBinContent)),
this, uow.EventManager))
{
return OperationStatus.Cancelled(evtMsgs);
}
var moveInfo = new List<MoveEventInfo<IContent>>
{
new MoveEventInfo<IContent>(content, originalPath, Constants.System.RecycleBinContent)
};
//Make sure that published content is unpublished before being moved to the Recycle Bin
if (HasPublishedVersion(content.Id))
{
//TODO: this shouldn't be a 'sub operation', and if it needs to be it cannot raise events and cannot be cancelled!
UnPublish(content, userId);
}
//Unpublish descendents of the content item that is being moved to trash
var descendants = GetDescendants(content).OrderBy(x => x.Level).ToList();
foreach (var descendant in descendants)
{
//TODO: this shouldn't be a 'sub operation', and if it needs to be it cannot raise events and cannot be cancelled!
UnPublish(descendant, userId);
}
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
content.WriterId = userId;
content.ChangeTrashedState(true);
repository.AddOrUpdate(content);
//Loop through descendants to update their trash state, but ensuring structure by keeping the ParentId
foreach (var descendant in descendants)
{
moveInfo.Add(new MoveEventInfo<IContent>(descendant, descendant.Path, descendant.ParentId));
descendant.WriterId = userId;
descendant.ChangeTrashedState(true, descendant.ParentId);
repository.AddOrUpdate(descendant);
}
uow.Commit();
}
Trashed.RaiseEvent(new MoveEventArgs<IContent>(false, evtMsgs, moveInfo.ToArray()), this, uow.EventManager);
Audit(AuditType.Move, "Move Content to Recycle Bin performed by user", userId, content.Id);
return OperationStatus.Success(evtMsgs);
}
this, UowProvider))
{
return OperationStatus.Cancelled(evtMsgs);
}
@@ -1178,22 +1126,22 @@ namespace Umbraco.Core.Services
public bool UnPublish(IContent content, int userId = 0)
{
return ((IContentServiceOperations)this).UnPublish(content, userId).Success;
var uow = UowProvider.GetUnitOfWork();
}
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
this, uow.EventManager))
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")]
public bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true)
{
var result = SaveAndPublishDo(content, userId, raiseEvents);
return result.Success;
}
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
@@ -1247,16 +1195,15 @@ namespace Umbraco.Core.Services
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
if (containsNew)
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
if (Deleting.IsRaisedEventCancelled(
{
foreach (var content in asArray)
this, uow.EventManager))
{
return OperationStatus.Cancelled(evtMsgs);
}
{
content.WriterId = userId;
//Only change the publish state if the "previous" version was actually published
if (content.Published)
content.ChangePublishedState(PublishedState.Saved);
repository.AddOrUpdate(content);
//add or update preview
repository.AddOrUpdatePreviewXml(content, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
@@ -1270,7 +1217,8 @@ namespace Umbraco.Core.Services
repository.AddOrUpdate(content);
//add or update preview
repository.AddOrUpdatePreviewXml(content, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
}
}
uow.Commit();
}
@@ -1341,17 +1289,23 @@ namespace Umbraco.Core.Services
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> IContentServiceOperations.Publish(IContent content, int userId)
using (var uow = UowProvider.GetUnitOfWork())
{
var repository = RepositoryFactory.CreateContentRepository(uow);
{
return SaveAndPublishDo(content, userId);
}
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> IContentServiceOperations.Save(IContent content, int userId, bool raiseEvents)
{
return Save(content, true, userId, raiseEvents);
}
@@ -1362,15 +1316,30 @@ namespace Umbraco.Core.Services
/// If the collection of content contains new objects that references eachother by Id or ParentId,
/// then use the overload Save method with a collection of Lazy <see cref="IContent"/>.
/// </remarks>
if (child.ContentType.Id != contentTypeId)
MoveToRecycleBin(child, userId);
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
public void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true)
//Permantly delete the content
Delete(content, userId);
{
((IContentServiceOperations)this).Save(contents, userId, raiseEvents);
}
/// <summary>
/// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="contentTypeId">Id of the <see cref="IContentType"/></param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
public void DeleteContentOfType(int contentTypeId, int userId = 0)
{
//TODO: This currently this is called from the ContentTypeService but that needs to change,
// if we are deleting a content type, we should just delete the data and do this operation slightly differently.
// This method will recursively go lookup every content item, check if any of it's descendants are
// of a different type, move them to the recycle bin, then permanently delete the content items.
// The main problem with this is that for every content item being deleted, events are raised...
// which we need for many things like keeping caches in sync, but we can surely do this MUCH better.
var childList = new List<IContent>();
var contentList = new List<IContent>();
using (new WriteLock(Locker))
@@ -1401,17 +1370,17 @@ namespace Umbraco.Core.Services
childList.Add(child);
}
if (DeletingVersions.IsRaisedEventCancelled(new DeleteRevisionsEventArgs(id, dateToRetain: versionDate), this, uow.EventManager))
return;
//track content for deletion
contentList.Add(content);
}
}
//We need to do this outside of the uow because otherwise we'll have nested uow's
//TODO: this is a problem because we are doing all of this logic in the Service when it should
//all be happening in the repository
}
DeletedVersions.RaiseEvent(new DeleteRevisionsEventArgs(id, false, dateToRetain: versionDate), this, uow.EventManager);
foreach (var child in childList)
{
if (child.ContentType.Id != contentTypeId)
MoveToRecycleBin(child, userId);
}
@@ -1428,9 +1397,7 @@ namespace Umbraco.Core.Services
}
/// <summary>
var uow = UowProvider.GetUnitOfWork();
if (DeletingVersions.IsRaisedEventCancelled(new DeleteRevisionsEventArgs(id, specificVersion: versionId), this, uow.EventManager))
/// Permanently deletes an <see cref="IContent"/> object as well as all of its Children.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
@@ -1438,15 +1405,15 @@ namespace Umbraco.Core.Services
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
public void Delete(IContent content, int userId = 0)
{
((IContentServiceOperations)this).Delete(content, userId);
}
/// <summary>
/// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date.
/// This method will never delete the latest version of a content item.
/// </summary>
DeletedVersions.RaiseEvent(new DeleteRevisionsEventArgs(id, false, specificVersion: versionId), this, uow.EventManager);
/// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
@@ -1475,32 +1442,29 @@ namespace Umbraco.Core.Services
/// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
public void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0)
{
using (new WriteLock(Locker))
{
if (DeletingVersions.IsRaisedEventCancelled(new DeleteRevisionsEventArgs(id, specificVersion: versionId), this, UowProvider))
return;
if (deletePriorVersions)
{
var content = GetByVersion(versionId);
DeleteVersions(id, content.UpdateDate, userId);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
//This ensures that the correct method is called if this method is used to Move to recycle bin.
if (parentId == Constants.System.RecycleBinContent)
{
MoveToRecycleBin(content, userId);
return;
}
{
repository.DeleteVersion(versionId);
uow.Commit();
using (var uow = UowProvider.GetUnitOfWork())
{
if (Moving.IsRaisedEventCancelled(
new MoveEventArgs<IContent>(
new MoveEventInfo<IContent>(content, content.Path, parentId)), this, uow.EventManager))
{
return;
}
DeletedVersions.RaiseEvent(new DeleteRevisionsEventArgs(id, false, specificVersion: versionId), this, uow.EventManager);
}
//used to track all the moved entities to be given to the event
var moveInfo = new List<MoveEventInfo<IContent>>();
//call private method that does the recursive moving
PerformMove(content, parentId, userId, moveInfo);
Moved.RaiseEvent(new MoveEventArgs<IContent>(false, moveInfo.ToArray()), this, uow.EventManager);
}
Audit(AuditType.Delete, "Delete Content by version performed by user", userId, Constants.System.Root);
}
}
@@ -1530,14 +1494,17 @@ namespace Umbraco.Core.Services
{
if (Moving.IsRaisedEventCancelled(
new MoveEventArgs<IContent>(
new MoveEventInfo<IContent>(content, content.Path, parentId)), this, UowProvider))
{
return;
}
//This ensures that the correct method is called if this method is used to Move to recycle bin.
if (parentId == Constants.System.RecycleBinContent)
EmptiedRecycleBin.RaiseEvent(new RecycleBinEventArgs(nodeObjectType, entities, files, success), this, uow.EventManager);
{
MoveToRecycleBin(content, userId);
return;
}
using (new WriteLock(Locker))
{
@@ -1581,12 +1548,14 @@ namespace Umbraco.Core.Services
uow.Commit();
return;
}
if (Copying.IsRaisedEventCancelled(new CopyEventArgs<IContent>(content, copy, parentId), this, uow.EventManager))
return null;
success = repository.EmptyRecycleBin();
if (success)
repository.DeleteMediaFiles(files);
EmptiedRecycleBin.RaiseEvent(new RecycleBinEventArgs(nodeObjectType, entities, files, success), this, uow.EventManager);
}
}
Audit(AuditType.Delete, "Empty Content Recycle Bin performed by user", 0, Constants.System.RecycleBinContent);
}
@@ -1623,7 +1592,7 @@ namespace Umbraco.Core.Services
using (new WriteLock(Locker))
{
var copy = content.DeepCloneWithResetIdentities();
Copied.RaiseEvent(new CopyEventArgs<IContent>(content, copy, false, parentId, relateToOriginal), this, uow.EventManager);
copy.ParentId = parentId;
// A copy should never be set to published automatically even if the original was.
copy.ChangePublishedState(PublishedState.Unpublished);
@@ -1639,20 +1608,17 @@ namespace Umbraco.Core.Services
// Update the create author and last edit author
copy.CreatorId = userId;
using (var uow = UowProvider.GetUnitOfWork())
{
if (SendingToPublish.IsRaisedEventCancelled(new SendToPublishEventArgs<IContent>(content), this, uow.EventManager))
return false;
copy.WriterId = userId;
repository.AddOrUpdate(copy);
//Save before raising event
Save(content, userId);
//add or update a preview
repository.AddOrUpdatePreviewXml(copy, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
uow.Commit();
SentToPublish.RaiseEvent(new SendToPublishEventArgs<IContent>(content, false), this, uow.EventManager);
Audit(AuditType.SendToPublish, "Send to Publish performed by user", content.WriterId, content.Id);
//Special case for the associated tags
//TODO: Move this to the repository layer in a single transaction!
return true;
}
//don't copy tags data in tags table if the item is in the recycle bin
if (parentId != Constants.System.RecycleBinContent)
{
@@ -1672,12 +1638,14 @@ namespace Umbraco.Core.Services
{
//TODO: This shouldn't recurse back to this method, it should be done in a private method
// that doesn't have a nested lock and so we can perform the entire operation in one commit.
if (RollingBack.IsRaisedEventCancelled(new RollbackEventArgs<IContent>(content), this, uow.EventManager))
return content;
Copy(child, copy.Id, relateToOriginal, true, userId);
}
}
Copied.RaiseEvent(new CopyEventArgs<IContent>(content, copy, false, parentId, relateToOriginal), this, UowProvider);
Audit(AuditType.Copy, "Copy Content performed by user", content.WriterId, content.Id);
return copy;
}
}
@@ -1686,10 +1654,9 @@ namespace Umbraco.Core.Services
/// Sends an <see cref="IContent"/> to Publication, which executes handlers and events for the 'Send to Publication' action.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to send to publication</param>
/// <param name="userId">Optional Id of the User issueing the send to publication</param>
/// <returns>True if sending publication was succesfull otherwise false</returns>
public bool SendToPublication(IContent content, int userId = 0)
RolledBack.RaiseEvent(new RollbackEventArgs<IContent>(content, false), this, uow.EventManager);
{
if (SendingToPublish.IsRaisedEventCancelled(new SendToPublishEventArgs<IContent>(content), this, UowProvider))
return false;
@@ -1715,16 +1682,18 @@ namespace Umbraco.Core.Services
/// <param name="id">Id of the <see cref="IContent"/>being rolled back</param>
/// <param name="versionId">Id of the version to rollback to</param>
/// <param name="userId">Optional Id of the User issueing the rollback of the Content</param>
var asArray = items.ToArray();
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(asArray), this, uow.EventManager))
return false;
}
/// <returns>The newly created <see cref="IContent"/> object</returns>
public IContent Rollback(int id, Guid versionId, int userId = 0)
{
var content = GetByVersion(versionId);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
if (RollingBack.IsRaisedEventCancelled(new RollbackEventArgs<IContent>(content), this, uow.EventManager))
{
uow.Commit();
return content;
}
content.WriterId = userId;
@@ -1762,10 +1731,10 @@ namespace Umbraco.Core.Services
using (new WriteLock(Locker))
{
}
var uow = UowProvider.GetUnitOfWork();
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IContent>(asArray, false), this, uow.EventManager);
using (var repository = RepositoryFactory.CreateContentRepository(uow))
{
var asArray = items.ToArray();
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IContent>(asArray), this, uow.EventManager))
@@ -1774,7 +1743,6 @@ namespace Umbraco.Core.Services
return false;
}
}
int i = 0;
foreach (var content in asArray)
@@ -1786,7 +1754,7 @@ namespace Umbraco.Core.Services
{
i++;
continue;
var uow = UowProvider.GetUnitOfWork();
}
content.SortOrder = i;
content.WriterId = userId;
@@ -1803,7 +1771,7 @@ namespace Umbraco.Core.Services
repository.AddOrUpdate(content);
//add or update a preview
var uow = UowProvider.GetUnitOfWork();
repository.AddOrUpdatePreviewXml(content, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
}
foreach (var content in shouldBePublished)
@@ -1826,7 +1794,7 @@ namespace Umbraco.Core.Services
}
Audit(AuditType.Sort, "Sorting content performed by user", userId, 0);
using (var repository = RepositoryFactory.CreateContentRepository(UowProvider.GetUnitOfWork()))
return true;
}
@@ -2100,12 +2068,11 @@ namespace Umbraco.Core.Services
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
private Attempt<UnPublishStatus> UnPublishDo(IContent content, bool omitCacheRefresh = false, int userId = 0)
var uow = UowProvider.GetUnitOfWork();
{
var newest = GetById(content.Id); // ensure we have the newest version
if (content.Version != newest.Version) // but use the original object if it's already the newest version
content = newest;
new SaveEventArgs<IContent>(content, evtMsgs), this, uow.EventManager))
var evtMsgs = EventMessagesFactory.Get();
var published = content.Published ? content : GetPublishedVersion(content.Id); // get the published version
@@ -2137,7 +2104,8 @@ namespace Umbraco.Core.Services
return Attempt.Succeed(new UnPublishStatus(content, UnPublishedStatusType.Success, evtMsgs));
}
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
@@ -2163,10 +2131,10 @@ namespace Umbraco.Core.Services
//Has this content item previously been published? If so, we don't need to refresh the children
var previouslyPublished = content.HasIdentity && HasPublishedVersion(content.Id); //content might not have an id
var publishStatus = new PublishStatus(content, PublishStatusType.Success, evtMsgs); //initially set to success
}
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IContent>(content, false, evtMsgs), this, uow.EventManager);
//Check if parent is published (although not if its a root node) - if parent isn't published this Content cannot be published
publishStatus.StatusType = CheckAndLogIsPublishable(content);
//if it is not successful, then check if the props are valid
if ((int)publishStatus.StatusType < 10)
{
//Content contains invalid property values and can therefore not be published - fire event?
@@ -2201,18 +2169,17 @@ namespace Umbraco.Core.Services
}
content.WriterId = userId;
var uow = UowProvider.GetUnitOfWork();
repository.AddOrUpdate(content);
//Generate a new preview
repository.AddOrUpdatePreviewXml(content, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
this, uow.EventManager))
if (published)
{
//Content Xml
repository.AddOrUpdateContentXml(content, c => _entitySerializer.Serialize(this, _dataTypeService, _userService, c));
}
uow.Commit();
if (raiseEvents)
@@ -2231,10 +2198,10 @@ namespace Umbraco.Core.Services
var descendants = GetPublishedDescendants(content);
_publishingStrategy.PublishingFinalized(descendants, false);
}
}
if (raiseEvents)
Saved.RaiseEvent(new SaveEventArgs<IContent>(content, false, evtMsgs), this, uow.EventManager);
Audit(AuditType.Publish, "Save and Publish performed by user", userId, content.Id);
return Attempt.If(publishStatus.StatusType == PublishStatusType.Success, publishStatus);
}
}
@@ -2324,7 +2291,7 @@ namespace Umbraco.Core.Services
}
return true;
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
}
private PublishStatusType CheckAndLogIsPublishable(IContent content)
{

View File

@@ -513,6 +513,7 @@
<Compile Include="Persistence\UnitOfWork\IScopeUnitOfWork.cs" />
<Compile Include="Persistence\UnitOfWork\IScopeUnitOfWorkProvider.cs" />
<Compile Include="Persistence\UnitOfWork\ScopeUnitOfWorkProvider.cs" />
<Compile Include="Persistence\UnitOfWork\ScopeUnitOfWorkProviderExtensions.cs" />
<Compile Include="PropertyEditors\DecimalValidator.cs" />
<Compile Include="PropertyEditors\PropertyEditorValueTypes.cs" />
<Compile Include="PropertyEditors\ValueConverters\GridValueConverter.cs" />