I have implemented an event handler for the following use case:
- Validate some custom permissions
If the user doesn't have these permissions then undo checkout of the item and then throw an exception.
EventSystem.Subscribe(HandlerForInitiated, EventPhases.Initiated);
And this is the pseudo code for the "HandlerForInitiated
" method:
private void HandlerForInitiated(RepositoryLocalObject subject, CheckInEventArgs args, EventPhases phase)
{
Log.InfoFormat("Trying to check-in [{0}] {1} of type: {2} ", subject.Id,subject.Title,subject.Id.ItemType);
bool allowed = true;
var type = subject.Id.ItemType;
try
{
var user = subject.Session.User;
allowed = IsActionAllowed(subject, user);
Log.DebugFormat("Is Allowed: {0}", allowed);
if (!allowed)
{
Log.InfoFormat("User {0} [{1}] is not allowed to check-in items of type {2}.", user.Title, user.Id, type);
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
if (!allowed)
{
TryUndoCheckOut(subject);
throw new Exception("You are not allowed to perform this action. Contact the Tridion CoE for support");
}
}
This is the TryUndoCheckOut
method:
private void TryUndoCheckOut(RepositoryLocalObject subject)
{
if (subject is VersionedItem && subject.IsLocked)
{
var vi = (VersionedItem)subject;
if (vi.LockType.HasFlag(LockType.CheckedOut))
{
Log.DebugFormat("Item {0} is checked out!", subject.Id);
try
{
Log.Debug("Undoing check-out...");
vi.UndoCheckOut();
Log.Debug("Undo-checkout successful!");
}
catch (Exception ex)
{
Log.ErrorFormat("Error while trying to undo check out for item: {0}", subject.Id);
}
}
}
}
When I check the component in the CME it remains checked-out although I don't get any errors.