Exemplo n.º 1
0
        public HttpResponseMessage Post(CreateGlobalAdminDTO dto)
        {
            try
            {
                if (!HasAccess())
                {
                    return(Forbidden());
                }

                var user = _userRepository.GetByKey(dto.UserId);

                //if already global admin, return conflict
                if (user.IsGlobalAdmin)
                {
                    return(Conflict(user.Name + " is already global admin"));
                }

                user.IsGlobalAdmin = true;
                _domainEvents.Raise(new AccessRightsChanged(dto.UserId));
                _userRepository.Save();

                var outDto = Mapper.Map <UserDTO>(user);

                return(Created(outDto));
            }
            catch (Exception e)
            {
                return(LogError(e));
            }
        }
Exemplo n.º 2
0
 public void EnableMonitoring()
 {
     domainEvents.Raise(new MonitoringEnabledForEndpoint {
         Endpoint = Convert(Id)
     });
     Monitored = true;
 }
Exemplo n.º 3
0
        private void AnnounceFailedMessage(IReadOnlyDictionary <string, string> headers, FailureDetails failureDetails)
        {
            var failingEndpointId = Address.Parse(failureDetails.AddressOfFailingEndpoint).Queue;

            string failedMessageId;

            if (headers.TryGetValue("ServiceControl.Retry.UniqueMessageId", out failedMessageId))
            {
                domainEvents.Raise(new MessageFailed
                {
                    FailureDetails  = failureDetails,
                    EndpointId      = failingEndpointId,
                    FailedMessageId = failedMessageId,
                    RepeatedFailure = true
                });
            }
            else
            {
                domainEvents.Raise(new MessageFailed
                {
                    FailureDetails  = failureDetails,
                    EndpointId      = failingEndpointId,
                    FailedMessageId = headers.UniqueId(),
                });
            }
        }
Exemplo n.º 4
0
        private void RemoveSystemTaskRefs(KLEChange kleChange)
        {
            var removedTaskRef = _existingTaskRefRepository.GetWithReferencePreload(t => t.ItSystems).First(t => t.TaskKey == kleChange.TaskKey);

            foreach (var itSystem in removedTaskRef.ItSystems.ToList())
            {
                itSystem.TaskRefs.Remove(removedTaskRef);
                _domainEvents.Raise(new EntityUpdatedEvent <ItSystem>(itSystem));
            }
        }
        public void DetectEndpointFromLocalAudit(EndpointDetails newEndpointDetails)
        {
            var endpointInstanceId = newEndpointDetails.ToInstanceId();

            if (endpoints.TryAdd(endpointInstanceId.UniqueId, new EndpointInstanceMonitor(endpointInstanceId, false, domainEvents)))
            {
                domainEvents.Raise(new NewEndpointDetected {
                    DetectedAt = DateTime.UtcNow, Endpoint = newEndpointDetails
                });
            }
        }
Exemplo n.º 6
0
        internal void Start()
        {
            ArchiveState   = ArchiveState.ArchiveStarted;
            CompletionTime = null;

            domainEvents.Raise(new ArchiveOperationStarting
            {
                RequestId   = RequestId,
                ArchiveType = ArchiveType,
                Progress    = GetProgress(),
                StartTime   = Started
            });
        }
Exemplo n.º 7
0
        public void Handle(UnArchiveMessages messages)
        {
            FailedMessage[] failedMessages;

            using (var session = store.OpenSession())
            {
                session.Advanced.UseOptimisticConcurrency = true;

                failedMessages = session.Load <FailedMessage>(messages.FailedMessageIds.Select(FailedMessage.MakeDocumentId));

                foreach (var failedMessage in failedMessages)
                {
                    if (failedMessage.Status == FailedMessageStatus.Archived)
                    {
                        failedMessage.Status = FailedMessageStatus.Unresolved;
                    }
                }

                session.SaveChanges();
            }

            domainEvents.Raise(new FailedMessagesUnArchived
            {
                MessagesCount = failedMessages.Length
            });
        }
Exemplo n.º 8
0
        public User AddUser(User user, bool sendMailOnCreation, int orgId)
        {
            // hash his salt and default password
            var utcNow = DateTime.UtcNow;

            user.Salt = _cryptoService.Encrypt(utcNow + " spices");
            user.Uuid = Guid.NewGuid();

            user.Password = _useDefaultUserPassword
                ? _cryptoService.Encrypt(_defaultUserPassword + user.Salt)
                : _cryptoService.Encrypt(utcNow + user.Salt);

            if (!_authorizationContext.AllowCreate <User>(orgId))
            {
                throw new SecurityException();
            }

            _userRepository.Insert(user);
            _userRepository.Save();

            var savedUser = _userRepository.Get(u => u.Id == user.Id).FirstOrDefault();

            _domainEvents.Raise(new EntityDeletedEvent <User>(savedUser));

            if (sendMailOnCreation)
            {
                IssueAdvisMail(savedUser, false, orgId);
            }

            return(savedUser);
        }
Exemplo n.º 9
0
        private bool TryDispatchEventBatch()
        {
            using (var session = store.OpenSession())
            {
                RavenQueryStatistics stats;
                var awaitingDispatching = session.Query <ExternalIntegrationDispatchRequest>().Statistics(out stats).Take(settings.ExternalIntegrationsDispatchingBatchSize).ToArray();

                if (awaitingDispatching.Length == 0)
                {
                    // If the index hasn't caught up, try again
                    return(stats.IndexEtag.CompareTo(latestEtag) < 0);
                }

                var allContexts = awaitingDispatching.Select(r => r.DispatchContext).ToArray();
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug($"Dispatching {allContexts.Length} events.");
                }
                var eventsToBePublished = eventPublishers.SelectMany(p => p.PublishEventsForOwnContexts(allContexts, session));

                foreach (var eventToBePublished in eventsToBePublished)
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Publishing external event on the bus.");
                    }

                    try
                    {
                        bus.Publish(eventToBePublished);
                    }
                    catch (Exception e)
                    {
                        Logger.Error("Failed dispatching external integration event.", e);

                        var m = new ExternalIntegrationEventFailedToBePublished
                        {
                            EventType = eventToBePublished.GetType()
                        };
                        try
                        {
                            m.Reason = e.GetBaseException().Message;
                        }
                        catch (Exception)
                        {
                            m.Reason = "Failed to retrieve reason!";
                        }
                        domainEvents.Raise(m);
                    }
                }
                foreach (var dispatchedEvent in awaitingDispatching)
                {
                    session.Delete(dispatchedEvent);
                }

                session.SaveChanges();
            }

            return(true);
        }
Exemplo n.º 10
0
        public void Handle(ReclassifyErrors message)
        {
            if (Interlocked.Exchange(ref executing, 1) != 0)
            {
                // Prevent more then one execution at a time
                return;
            }

            try
            {
                var failedMessagesReclassified = reclassifier.ReclassifyFailedMessages(store, message.Force, classifiers);

                if (failedMessagesReclassified > 0)
                {
                    domainEvents.Raise(new ReclassificationOfErrorMessageComplete
                    {
                        NumberofMessageReclassified = failedMessagesReclassified
                    });
                }
            }
            finally
            {
                Interlocked.Exchange(ref executing, 0);
            }
        }
Exemplo n.º 11
0
 public void Handle(MarkPendingRetryAsResolved message)
 {
     MarkMessageAsResolved(message.FailedMessageId);
     domainEvents.Raise(new MessageFailureResolvedManually
     {
         FailedMessageId = message.FailedMessageId
     });
 }
        public void Handle(DeleteCustomCheck message)
        {
            store.DatabaseCommands.Delete(store.Conventions.DefaultFindFullDocumentKeyFromNonStringIdentifier(message.Id, typeof(CustomCheck), false), null);

            domainEvents.Raise(new CustomCheckDeleted {
                Id = message.Id
            });
        }
Exemplo n.º 13
0
        public async Task <Student> EnrollStudent(string name, string email, string address)
        {
            _logger.LogInformation("Enroll Student {}", name);

            var studentEntity = new Student(name, email, address);

            await _studentRepository.Save(studentEntity);

            // publish the event
            _domainEvents.Raise(new StudentEnrolled
            {
                StudentId = studentEntity.Id.ToString(),
                Name      = studentEntity.Name,
                Email     = studentEntity.Email
            });

            return(studentEntity);
        }
Exemplo n.º 14
0
        public HttpResponseMessage PostMainContract(int contractId, int usageId)
        {
            var item = _repository.GetByKey(new object[] { contractId, usageId });

            if (item == null)
            {
                return(NotFound());
            }

            if (!AllowModify(item.ItSystemUsage))
            {
                return(Forbidden());
            }

            item.ItSystemUsage.MainContract = item;
            _domainEvent.Raise(new EntityUpdatedEvent <ItSystemUsage>(item.ItSystemUsage));
            _repository.Save();
            return(Ok());
        }
Exemplo n.º 15
0
        public Result <OrganizationRight, OperationFailure> AssignRole(int organizationId, int userId, OrganizationRole roleId)
        {
            var right = new OrganizationRight
            {
                OrganizationId = organizationId,
                Role           = roleId,
                UserId         = userId
            };

            if (!_authorizationContext.AllowCreate <OrganizationRight>(organizationId, right))
            {
                return(OperationFailure.Forbidden);
            }

            right = _organizationRightRepository.Insert(right);
            _domainEvents.Raise(new AccessRightsChanged(userId));
            _organizationRightRepository.Save();
            return(right);
        }
Exemplo n.º 16
0
        public Result <ExternalReference, OperationError> AddReference(
            int rootId,
            ReferenceRootType rootType,
            string title,
            string externalReferenceId,
            string url,
            Display display)
        {
            return(_referenceRepository
                   .GetRootEntity(rootId, rootType)
                   .Match
                   (
                       onValue: root =>
            {
                if (!_authorizationContext.AllowModify(root))
                {
                    return new OperationError("Not allowed to modify root entity", OperationFailure.Forbidden);
                }

                return root
                .AddExternalReference(new ExternalReference
                {
                    Title = title,
                    ExternalReferenceId = externalReferenceId,
                    URL = url,
                    Display = display,
                    Created = _operationClock.Now,
                })
                .Match <Result <ExternalReference, OperationError> >
                (
                    onSuccess: createdReference =>
                {
                    _referenceRepository.SaveRootEntity(root);
                    _domainEvents.Raise(new EntityCreatedEvent <ExternalReference>(createdReference));
                    return createdReference;
                },
                    onFailure: error => error
                );
            },
                       onNone: () => new OperationError("Root entity could not be found", OperationFailure.NotFound)
                   ));
        }
        private void Notify(DataProcessingRegistration dataProcessingRegistration, LifeCycleEventType changeType)
        {
            switch (changeType)
            {
            case LifeCycleEventType.Created:
                _domainEvents.Raise(new EntityCreatedEvent <DataProcessingRegistration>(dataProcessingRegistration));
                break;

            case LifeCycleEventType.Updated:
                _domainEvents.Raise(new EntityUpdatedEvent <DataProcessingRegistration>(dataProcessingRegistration));
                break;

            case LifeCycleEventType.Deleted:
                _domainEvents.Raise(new EntityDeletedEvent <DataProcessingRegistration>(dataProcessingRegistration));
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(changeType), changeType, null);
            }
        }
Exemplo n.º 18
0
        public Result <ItProject, OperationFailure> AddProject(string name, int organizationId)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (name.Length > ItProjectConstraints.MaxNameLength)
            {
                return(OperationFailure.BadInput);
            }
            var project = ItProjectFactory.Create(name, organizationId);

            if (!_authorizationContext.AllowCreate <ItProject>(organizationId, project))
            {
                return(OperationFailure.Forbidden);
            }

            _projectRepository.Insert(project);
            _projectRepository.Save();
            _domainEvents.Raise(new EntityCreatedEvent <ItProject>(project));
            return(project);
        }
Exemplo n.º 19
0
        private OrganizationRight AddOrganizationRoleToUser(User user, Organization organization, OrganizationRole organizationRole)
        {
            var result = _organizationRights.Insert(new OrganizationRight
            {
                Organization = organization,
                User         = user,
                Role         = organizationRole,
            });

            _domainEvents.Raise(new AccessRightsChanged(user.Id));
            _organizationRights.Save();

            return(result);
        }
            public void ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e)
            {
                try
                {
                    var destination     = message.Headers["ServiceControl.TargetEndpointAddress"];
                    var messageUniqueId = message.Headers["ServiceControl.Retry.UniqueMessageId"];
                    Log.Warn($"Failed to send '{messageUniqueId}' message to '{destination}' for retry. Attempting to revert message status to unresolved so it can be tried again.", e);

                    using (var session = store.OpenSession())
                    {
                        var failedMessage = session.Load <FailedMessage>(FailedMessage.MakeDocumentId(messageUniqueId));
                        if (failedMessage != null)
                        {
                            failedMessage.Status = FailedMessageStatus.Unresolved;
                        }

                        var failedMessageRetry = session.Load <FailedMessageRetry>(FailedMessageRetry.MakeDocumentId(messageUniqueId));
                        if (failedMessageRetry != null)
                        {
                            session.Delete(failedMessageRetry);
                        }

                        session.SaveChanges();
                    }
                    string reason;
                    try
                    {
                        reason = e.GetBaseException().Message;
                    }
                    catch (Exception)
                    {
                        reason = "Failed to retrieve reason!";
                    }
                    domainEvents.Raise(new MessagesSubmittedForRetryFailed
                    {
                        Reason          = reason,
                        FailedMessageId = messageUniqueId,
                        Destination     = destination
                    });
                }
                catch (Exception ex)
                {
                    // If something goes wrong here we just ignore, not the end of the world!
                    Log.Error("A failure occurred when trying to handle a retry failure.", ex);
                }
                finally
                {
                    executeOnFailure();
                }
            }
Exemplo n.º 21
0
        public Result <ItInterface, OperationFailure> Delete(int id)
        {
            using (var transaction = _transactionManager.Begin(IsolationLevel.Serializable))
            {
                var itInterface = _repository.GetByKey(id);

                if (itInterface == null)
                {
                    return(OperationFailure.NotFound);
                }

                if (!_authorizationContext.AllowDelete(itInterface))
                {
                    return(OperationFailure.Forbidden);
                }

                if (itInterface.ExhibitedBy != null)
                {
                    return(OperationFailure.Conflict);
                }

                var dataRows = itInterface.DataRows.ToList();
                foreach (var dataRow in dataRows)
                {
                    _dataRowRepository.DeleteByKey(dataRow.Id);
                }
                _dataRowRepository.Save();

                // delete it interface
                _domainEvents.Raise(new EntityDeletedEvent <ItInterface>(itInterface));
                _repository.DeleteWithReferencePreload(itInterface);
                _repository.Save();

                transaction.Commit();
                return(itInterface);
            }
        }
 public HttpResponseMessage PostSetResponsibleOrgUnit(int usageId, int orgUnitId, bool?responsible)
 {
     try
     {
         var entity      = _responsibleOrgUnitRepository.GetByKey(new object[] { usageId, orgUnitId });
         var systemUsage = _systemUsageRepository.GetByKey(usageId);
         if (systemUsage == null)
         {
             return(NotFound());
         }
         if (!AllowModify(systemUsage))
         {
             return(Forbidden());
         }
         systemUsage.ResponsibleUsage = entity;
         _domainEvents.Raise(new EntityUpdatedEvent <ItSystemUsage>(systemUsage));
         _responsibleOrgUnitRepository.Save();
         return(Ok());
     }
     catch (Exception e)
     {
         return(LogError(e));
     }
 }
Exemplo n.º 23
0
        public Result <ItContract, OperationFailure> Delete(int id)
        {
            var contract = _repository.GetById(id);

            if (contract == null)
            {
                return(OperationFailure.NotFound);
            }

            if (!_authorizationContext.AllowDelete(contract))
            {
                return(OperationFailure.Forbidden);
            }
            using (var transaction = _transactionManager.Begin(IsolationLevel.ReadCommitted))
            {
                try
                {
                    //Delete the economy streams to prevent them from being orphaned
                    foreach (var economyStream in GetEconomyStreams(contract))
                    {
                        DeleteEconomyStream(economyStream);
                    }
                    _economyStreamRepository.Save();

                    //Delete the contract
                    var deleteByContractId = _referenceService.DeleteByContractId(id);
                    if (deleteByContractId.Failed)
                    {
                        transaction.Rollback();
                        return(deleteByContractId.Error);
                    }
                    _domainEvents.Raise(new ContractDeleted(contract));
                    _repository.DeleteContract(contract);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    _logger.Error(e, $"Failed to delete it contract with id: {contract.Id}");
                    transaction.Rollback();
                    return(OperationFailure.UnknownError);
                }
            }
            return(contract);
        }
        void UpdatedCount()
        {
            using (var session = store.OpenSession())
            {
                var failedUnresolvedMessageCount = session.Query <FailedMessage, FailedMessageViewIndex>().Count(p => p.Status == FailedMessageStatus.Unresolved);
                var failedArchivedMessageCount   = session.Query <FailedMessage, FailedMessageViewIndex>().Count(p => p.Status == FailedMessageStatus.Archived);

                if (lastUnresolvedCount == failedUnresolvedMessageCount && lastArchivedCount == failedArchivedMessageCount)
                {
                    return;
                }
                lastUnresolvedCount = failedUnresolvedMessageCount;
                lastArchivedCount   = failedArchivedMessageCount;

                domainEvents.Raise(new MessageFailuresUpdated
                {
                    Total           = failedUnresolvedMessageCount, // Left here for backwards compatibility, to be removed eventually.
                    UnresolvedTotal = failedUnresolvedMessageCount,
                    ArchivedTotal   = failedArchivedMessageCount
                });
            }
        }
Exemplo n.º 25
0
            public override void Enrich(IReadOnlyDictionary <string, string> headers, IDictionary <string, object> metadata)
            {
                string oldRetryId;
                string newRetryMessageId;

                var isOldRetry = headers.TryGetValue("ServiceControl.RetryId", out oldRetryId);
                var isNewRetry = headers.TryGetValue("ServiceControl.Retry.UniqueMessageId", out newRetryMessageId);

                var hasBeenRetried = isOldRetry || isNewRetry;

                metadata.Add("IsRetried", hasBeenRetried);

                if (!hasBeenRetried)
                {
                    return;
                }

                domainEvents.Raise(new MessageFailureResolvedByRetry
                {
                    FailedMessageId             = isOldRetry ? headers.UniqueId() : newRetryMessageId,
                    AlternativeFailedMessageIds = GetAlternativeUniqueMessageId(headers).ToArray()
                });
            }
Exemplo n.º 26
0
        public void Wait(DateTime started, string originator = null, string classifier = null, DateTime?last = null)
        {
            RetryState = RetryState.Waiting;
            NumberOfMessagesPrepared  = 0;
            NumberOfMessagesForwarded = 0;
            TotalNumberOfMessages     = 0;
            NumberOfMessagesSkipped   = 0;
            CompletionTime            = null;
            Originator = originator;
            Started    = started;
            Failed     = false;
            Last       = last;
            Classifier = classifier;

            domainEvents.Raise(new RetryOperationWaiting
            {
                RequestId = requestId,
                RetryType = retryType,
                Progress  = GetProgress(),
                StartTime = Started
            });
        }
Exemplo n.º 27
0
        public void Handle(ArchiveMessage message)
        {
            using (var session = store.OpenSession())
            {
                var failedMessage = session.Load <FailedMessage>(new Guid(message.FailedMessageId));

                if (failedMessage == null)
                {
                    return; //No point throwing
                }

                if (failedMessage.Status != FailedMessageStatus.Archived)
                {
                    failedMessage.Status = FailedMessageStatus.Archived;

                    domainEvents.Raise(new FailedMessageArchived
                    {
                        FailedMessageId = message.FailedMessageId
                    });
                }

                session.SaveChanges();
            }
        }
        public void Handle(ArchiveAllInGroup message)
        {
            if (retryingManager.IsRetryInProgressFor(message.GroupId))
            {
                logger.Warn($"Attempt to archive a group ({message.GroupId}) which is currently in the process of being retried");
                return;
            }

            logger.Info($"Archiving of {message.GroupId} started");
            ArchiveOperation archiveOperation;

            using (var session = store.OpenSession())
            {
                session.Advanced.UseOptimisticConcurrency = true; // Ensure 2 messages don't split the same operation into batches at once

                archiveOperation = documentManager.LoadArchiveOperation(session, message.GroupId, ArchiveType.FailureGroup);

                if (archiveOperation == null)
                {
                    var groupDetails = documentManager.GetGroupDetails(session, message.GroupId);
                    if (groupDetails.NumberOfMessagesInGroup == 0)
                    {
                        logger.Warn($"No messages to archive in group {message.GroupId}");

                        return;
                    }

                    logger.Info($"Splitting group {message.GroupId} into batches");
                    archiveOperation = documentManager.CreateArchiveOperation(session, message.GroupId, ArchiveType.FailureGroup, groupDetails.NumberOfMessagesInGroup, groupDetails.GroupName, batchSize);
                    session.SaveChanges();

                    logger.Info($"Group {message.GroupId} has been split into {archiveOperation.NumberOfBatches} batches");
                }
            }

            archiveOperationManager.StartArchiving(archiveOperation);

            while (archiveOperation.CurrentBatch < archiveOperation.NumberOfBatches)
            {
                using (var batchSession = store.OpenSession())
                {
                    var nextBatch = documentManager.GetArchiveBatch(batchSession, archiveOperation.Id, archiveOperation.CurrentBatch);
                    if (nextBatch == null)
                    {
                        // We're only here in the case where Raven indexes are stale
                        logger.Warn($"Attempting to archive a batch ({archiveOperation.Id}/{archiveOperation.CurrentBatch}) which appears to already have been archived.");
                    }
                    else
                    {
                        logger.Info($"Archiving {nextBatch.DocumentIds.Count} messages from group {message.GroupId} starting");
                    }

                    documentManager.ArchiveMessageGroupBatch(batchSession, nextBatch);

                    archiveOperationManager.BatchArchived(archiveOperation.RequestId, archiveOperation.ArchiveType, nextBatch?.DocumentIds.Count ?? 0);

                    archiveOperation = archiveOperationManager.GetStatusForArchiveOperation(archiveOperation.RequestId, archiveOperation.ArchiveType).ToArchiveOperation();

                    documentManager.UpdateArchiveOperation(batchSession, archiveOperation);

                    batchSession.SaveChanges();

                    if (nextBatch != null)
                    {
                        logger.Info($"Archiving of {nextBatch.DocumentIds.Count} messages from group {message.GroupId} completed");
                    }
                }
            }

            logger.Info($"Archiving of group {message.GroupId} is complete. Waiting for index updates.");
            archiveOperationManager.ArchiveOperationFinalizing(archiveOperation.RequestId, archiveOperation.ArchiveType);
            if (!documentManager.WaitForIndexUpdateOfArchiveOperation(store, archiveOperation.RequestId, archiveOperation.ArchiveType, TimeSpan.FromMinutes(5)))
            {
                logger.Warn($"Archiving group {message.GroupId} completed but index not updated.");
            }

            logger.Info($"Archiving of group {message.GroupId} completed");
            archiveOperationManager.ArchiveOperationCompleted(archiveOperation.RequestId, archiveOperation.ArchiveType);
            documentManager.RemoveArchiveOperation(store, archiveOperation);

            domainEvents.Raise(new FailedMessageGroupArchived
            {
                GroupId       = message.GroupId,
                GroupName     = archiveOperation.GroupName,
                MessagesCount = archiveOperation.TotalNumberOfMessages
            });
        }
 // This is only needed because we might get this from legacy not yet converted instances
 public Task Handle(MessageFailureResolvedByRetry message, IMessageHandlerContext context)
 {
     return(domainEvents.Raise(message));
 }
        public Result <ItSystemUsage, OperationFailure> ExecuteSystemUsageMigration(int usageSystemId, int toSystemId)
        {
            if (!CanExecuteMigration())
            {
                return(OperationFailure.Forbidden);
            }

            using (var transaction = _transactionManager.Begin(IsolationLevel.Serializable))
            {
                try
                {
                    // **********************************
                    // *** Check migration conditions ***
                    // **********************************

                    // If migration description cannot be retrieved, bail out
                    var migrationConsequences = GetSystemUsageMigration(usageSystemId, toSystemId);
                    if (migrationConsequences.Ok == false)
                    {
                        return(migrationConsequences.Error);
                    }
                    var migration   = migrationConsequences.Value;
                    var systemUsage = migration.SystemUsage;
                    var oldSystem   = migration.FromItSystem;
                    var newSystem   = migration.ToItSystem;

                    //If modification of the target usage is not allowed, bail out
                    if (!_authorizationContext.AllowModify(systemUsage))
                    {
                        return(OperationFailure.Forbidden);
                    }

                    // If target equals current system, bail out
                    if (systemUsage.ItSystemId == migration.ToItSystem.Id)
                    {
                        return(systemUsage);
                    }

                    // *************************
                    // *** Perform migration ***
                    // *************************

                    // Delete UsedByRelation interfaces
                    var relationsMigrated = PerformRelationMigrations(migration);
                    if (relationsMigrated == false)
                    {
                        transaction.Rollback();
                        return(OperationFailure.UnknownError);
                    }
                    //***********************************************
                    //Perform final switchover of "source IT-System"
                    //***********************************************

                    // Delete access types (they are bound to the system)
                    DeleteAccessTypes(systemUsage);

                    // Switch the ID
                    systemUsage.ItSystemId = toSystemId;
                    _systemUsageRepository.Update(systemUsage);

                    //Raise events for all affected roots
                    _domainEvents.Raise(new EntityUpdatedEvent <ItSystemUsage>(systemUsage));
                    _domainEvents.Raise(new EntityUpdatedEvent <ItSystem>(oldSystem));
                    _domainEvents.Raise(new EntityUpdatedEvent <ItSystem>(newSystem));
                    transaction.Commit();
                    return(systemUsage);
                }
                catch (Exception e)
                {
                    _logger.Error(e, $"Migrating usageSystem with id: {usageSystemId}, to system with id: {toSystemId} failed");
                    transaction.Rollback();
                    return(OperationFailure.UnknownError);
                }
            }
        }