Esempio n. 1
0
        protected void ThrowOnWrongEvent(IInOutStateEvent stateEvent)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("InOut|");

            var stateEntityId = this.DocumentNumber;                    // Aggregate Id
            var eventEntityId = stateEvent.StateEventId.DocumentNumber; // EntityBase.Aggregate.GetStateEventIdPropertyIdName();

            if (stateEntityId != eventEntityId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id {0} in state but entity id {1} in event", stateEntityId, eventEntityId);
            }
            id.Append(stateEntityId).Append(",");

            id.Append("]");

            var stateVersion = this.Version;
            var eventVersion = stateEvent.StateEventId.Version;

            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 2
0
        public virtual void AppendToStream(IIdentity id, long originalVersion, ICollection <IEvent> events)
        {
            if (events.Count == 0)
            {
                return;
            }

            var name = this.IdentityToString(id);
            var data = this.SerializeEvent(events.ToArray());

            try
            {
                this.AppendOnlyStore.Append(name, data, originalVersion);
            }
            catch (AppendOnlyStoreConcurrencyException e)
            {
                // load server events
                var server = this.LoadEventStream(id, 0, int.MaxValue);
                // throw a real problem
                throw OptimisticConcurrencyException.Create(server.Version, e.ExpectedStreamVersion, id, server.Events, events.ToList());
            }

            // technically there should be a parallel process that queries new changes
            // from the event store and sends them via messages (avoiding 2PC problem).
            // however, for demo purposes, we'll just send them to the console from here
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            foreach (var @event in events)
            {
                Logger.DebugFormat("{0} r{1} Event: {2}", id, originalVersion, @event);
            }
        }
        private static void ThrowDbUpdateConcurrencyException()
        {
            const string message        = "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.";
            var          innerException = new OptimisticConcurrencyException(message);

            throw new DbUpdateConcurrencyException(innerException.Message, innerException);
        }
        protected void ThrowOnWrongEvent(IInventoryItemRequirementEvent e)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("InventoryItemRequirement|");

            var stateEntityId = this.InventoryItemRequirementId; // Aggregate Id
            var eventEntityId = e.InventoryItemRequirementEventId.InventoryItemRequirementId;

            if (stateEntityId != eventEntityId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id {0} in state but entity id {1} in event", stateEntityId, eventEntityId);
            }
            id.Append(stateEntityId).Append(",");

            id.Append("]");

            var stateVersion = this.Version;
            var eventVersion = e.InventoryItemRequirementEventId.Version;

            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 5
0
        protected void ThrowOnWrongEvent(IAttributeSetInstanceExtensionFieldMvoStateEvent stateEvent)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("AttributeSetInstanceExtensionFieldMvo|");

            var stateEntityId = this.AttributeSetInstanceExtensionFieldId;                    // Aggregate Id
            var eventEntityId = stateEvent.StateEventId.AttributeSetInstanceExtensionFieldId; // EntityBase.Aggregate.GetStateEventIdPropertyIdName();

            if (stateEntityId != eventEntityId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id {0} in state but entity id {1} in event", stateEntityId, eventEntityId);
            }
            id.Append(stateEntityId).Append(",");

            id.Append("]");

            var stateVersion = this.AttrSetInstEFGroupVersion;
            var eventVersion = stateEvent.StateEventId.AttrSetInstEFGroupVersion;

            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
        protected void ThrowOnWrongEvent(IOrderItemShipGroupAssociationMvoEvent e)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("OrderItemShipGroupAssociationMvo|");

            var stateEntityId = this.OrderItemShipGroupAssociationId; // Aggregate Id
            var eventEntityId = e.OrderItemShipGroupAssociationMvoEventId.OrderItemShipGroupAssociationId;

            if (stateEntityId != eventEntityId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id {0} in state but entity id {1} in event", stateEntityId, eventEntityId);
            }
            id.Append(stateEntityId).Append(",");

            id.Append("]");

            var stateVersion = this.OrderVersion;
            var eventVersion = e.OrderItemShipGroupAssociationMvoEventId.OrderVersion;

            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 7
0
        public async Task AppendToStream(IIdentity id, long expectedVersion, ICollection <IEvent> events)
        {
            if (events.Count == 0)
            {
                return;
            }

            var name = id.ToString();
            var data = this.serializer.SerializeEvent(events.ToArray());

            try
            {
                await this.appender.Append(name, data, expectedVersion);
            }
            catch (AppendOnlyStoreConcurrencyException e)
            {
                // load server events
                var server = await this.LoadEventStream(id, 0, int.MaxValue);

                // throw a real problem
                throw OptimisticConcurrencyException.Create(server.Version, e.ExpectedStreamVersion, id, server.Events);
            }

            foreach (var @event in events)
            {
                Logger.DebugFormat("{0} r{1} Event: {2}", id, expectedVersion, @event);
            }
        }
Esempio n. 8
0
        public void AppendEventsToStream(string name, long streamVersion, ICollection <Event> events)
        {
            if (events.Count == 0)
            {
                return;
            }
            // functional events don't have an identity

            try
            {
                _msgStore.AppendToStore(name, streamVersion, events.Cast <object>().ToArray());
            }
            catch (AppendOnlyStoreConcurrencyException e)
            {
                // load server events
                var server = LoadEventStream(name);
                // throw a real problem
                throw OptimisticConcurrencyException.Create(server.StreamVersion, e.ExpectedStreamVersion, name, server.Events);
            }
            // sync handling. Normally we would push this to async
            foreach (var @event in events)
            {
                _msgHandler.Handle(@event);
            }
        }
Esempio n. 9
0
        public void AfterThrowing(OptimisticConcurrencyException ex)
        {
            var ctx        = new XmlApplicationContext("~/Springs/ErrorSpring.xml");
            var errorAdmin = (IErrorBl)ctx["ErrorAdmin"];

            errorAdmin.RegistrarErrorServicio(ex.Message, string.Format("MENSAJE :{0}///EXCEPCION INTERNA : {1}///DATA : {2} ///FUENTE : {3}///SITIO_DESTINO : {4}///SEGUIMIENTO DE PILA : {5}", ex.Message, ex.InnerException, ex.Data, ex.Source, ex.TargetSite, ex.StackTrace));
            throw new FaultException <Exception>(ex, new FaultReason("Los datos que desea modificar han cambiado. Por favor regrese a la vista principal de datos e intente nuevamente."));
        }
        public void ShouldThisBeRetried_OptimisticConcurrencyException_ShouldBeRetired(int currentRetryCount, bool expectedShouldThisBeRetried)
        {
            // Assert
            var optimisticConcurrencyException = new OptimisticConcurrencyException(A <string>());

            // Act
            var shouldThisBeRetried = Sut.ShouldThisBeRetried(optimisticConcurrencyException, A <TimeSpan>(), currentRetryCount);

            // Assert
            shouldThisBeRetried.ShouldBeRetried.Should().Be(expectedShouldThisBeRetried);
        }
Esempio n. 11
0
            public void OptimisticConcurrencyException_with_relationship_entries_is_wrapped_as_IA_update_exception()
            {
                var original = new OptimisticConcurrencyException("Bang!", null, new[] { CreateEntityEntry(), CreateRelationshipEntry() });

                var wrapped = new EagerInternalContext(new Mock <DbContext>().Object).WrapUpdateException(original);

                Assert.IsType <DbUpdateException>(wrapped);
                Assert.Equal(Strings.DbContext_IndependentAssociationUpdateException, wrapped.Message);
                Assert.Empty(wrapped.Entries);
                Assert.Same(original, wrapped.InnerException);
            }
Esempio n. 12
0
            public void OptimisticConcurrencyException_with_null_entries_is_wrapped_as_normal_update_exception()
            {
                var original = new OptimisticConcurrencyException("Bang!");

                var wrapped = new EagerInternalContext(new Mock <DbContext>().Object).WrapUpdateException(original);

                Assert.IsType <DbUpdateConcurrencyException>(wrapped);
                Assert.Equal("Bang!", wrapped.Message);
                Assert.Empty(wrapped.Entries);
                Assert.Same(original, wrapped.InnerException);
            }
        public void GivenOptimisticConcurrencyException_WhenMapped_ThenReturnsForbiddenHttpStatusWithProperMessage()
        {
            //Given
            var id        = Guid.NewGuid();
            var version   = Guid.NewGuid();
            var exception = OptimisticConcurrencyException.For <TestEntity>(id, version);

            //When
            var codeInfo = ExceptionToHttpStatusMapper.Map(exception);

            //Then
            codeInfo.Code.Should().Be(HttpStatusCode.Conflict);
            codeInfo.Message.Should()
            .Be($"Cannot modify {typeof(TestEntity).Name} with id: {id}. Version `{version}` did not match.");
        }
Esempio n. 14
0
        public virtual DbUpdateException WrapUpdateException(
            UpdateException updateException)
        {
            if (updateException.StateEntries != null && updateException.StateEntries.Any <ObjectStateEntry>((Func <ObjectStateEntry, bool>)(e => e.Entity == null)))
            {
                return(new DbUpdateException(this, updateException, true));
            }
            OptimisticConcurrencyException innerException = updateException as OptimisticConcurrencyException;

            if (innerException == null)
            {
                return(new DbUpdateException(this, updateException, false));
            }
            return((DbUpdateException) new DbUpdateConcurrencyException(this, innerException));
        }
Esempio n. 15
0
        public void UpdateAuto(AutoDto modified, AutoDto original)
        {
            try
            {
                WriteActualMethod();
                BusinessComponent.UpdateAuto(modified.ConvertToEntity(), original.ConvertToEntity());
            }
            catch (LocalOptimisticConcurrencyException <Auto> ex)
            {
                OptimisticConcurrencyException <AutoDto> enThrow = new OptimisticConcurrencyException <AutoDto>();
                enThrow.Entity = ex.Entity.ConvertToDto();

                throw new FaultException <OptimisticConcurrencyException <AutoDto> >(enThrow);
            }
        }
Esempio n. 16
0
            public void OptimisticConcurrencyException_without_relationship_entries_is_wrapped_as_normal_update_exception()
            {
                var entity1  = new object();
                var entity2  = new object();
                var original = new OptimisticConcurrencyException(
                    "Bang!", null, new[] { CreateEntityEntry(entity1), CreateEntityEntry(entity2) });

                var wrapped = new EagerInternalContext(new Mock <DbContext>().Object).WrapUpdateException(original);

                Assert.IsType <DbUpdateConcurrencyException>(wrapped);
                Assert.Equal("Bang!", wrapped.Message);
                Assert.Equal(2, wrapped.Entries.Count());
                Assert.Same(entity1, wrapped.Entries.First().Entity);
                Assert.Same(entity2, wrapped.Entries.Skip(1).First().Entity);
                Assert.Same(original, wrapped.InnerException);
            }
        public void UpdateReservation(ReservationDto modified, ReservationDto original)
        {
            try
            {
                WriteActualMethod();
                BusinessComponent.UpdateReservation(modified.ConvertToEntity(), original.ConvertToEntity());
            }
            catch (LocalOptimisticConcurrencyException <Reservation> ex)
            {
                var enThrow = new OptimisticConcurrencyException <ReservationDto> {
                    Entity = ex.Entity.ConvertToDto()
                };

                throw new FaultException <OptimisticConcurrencyException <ReservationDto> >(enThrow);
            }
        }
        public void UpdateKunde(KundeDto modified, KundeDto original)
        {
            try
            {
                WriteActualMethod();
                component.UpdateKunde(modified.ConvertToEntity(), original.ConvertToEntity());
            }
            catch (LocalOptimisticConcurrencyException <Kunde> ex)
            {
                var e = new OptimisticConcurrencyException <KundeDto> {
                    Entity = ex.Entity.ConvertToDto()
                };

                throw new FaultException <OptimisticConcurrencyException <KundeDto> >(e);
            }
        }
Esempio n. 19
0
        protected void ThrowOnWrongEvent(IAttributeSetInstanceExtensionFieldStateEvent stateEvent)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("AttributeSetInstanceExtensionField|");

            var stateEntityIdGroupId = (this as IGlobalIdentity <AttributeSetInstanceExtensionFieldId>).GlobalId.GroupId;
            var eventEntityIdGroupId = stateEvent.StateEventId.GroupId;

            if (stateEntityIdGroupId != eventEntityIdGroupId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id GroupId {0} in state but entity id GroupId {1} in event", stateEntityIdGroupId, eventEntityIdGroupId);
            }
            id.Append(stateEntityIdGroupId).Append(",");

            var stateEntityIdIndex = (this as IGlobalIdentity <AttributeSetInstanceExtensionFieldId>).GlobalId.Index;
            var eventEntityIdIndex = stateEvent.StateEventId.Index;

            if (stateEntityIdIndex != eventEntityIdIndex)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id Index {0} in state but entity id Index {1} in event", stateEntityIdIndex, eventEntityIdIndex);
            }
            id.Append(stateEntityIdIndex).Append(",");

            id.Append("]");

            if (ForReapplying)
            {
                return;
            }
            var stateVersion = this.Version;
            var eventVersion = stateEvent.Version;

            if (AttributeSetInstanceExtensionFieldState.VersionZero == eventVersion)
            {
                eventVersion = stateEvent.Version = stateVersion;
            }
            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 20
0
        protected void ThrowOnWrongEvent(IInOutLineStateEvent stateEvent)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("InOutLine|");

            var stateEntityIdInOutDocumentNumber = (this as IGlobalIdentity <InOutLineId>).GlobalId.InOutDocumentNumber;
            var eventEntityIdInOutDocumentNumber = stateEvent.StateEventId.InOutDocumentNumber;

            if (stateEntityIdInOutDocumentNumber != eventEntityIdInOutDocumentNumber)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id InOutDocumentNumber {0} in state but entity id InOutDocumentNumber {1} in event", stateEntityIdInOutDocumentNumber, eventEntityIdInOutDocumentNumber);
            }
            id.Append(stateEntityIdInOutDocumentNumber).Append(",");

            var stateEntityIdLineNumber = (this as IGlobalIdentity <InOutLineId>).GlobalId.LineNumber;
            var eventEntityIdLineNumber = stateEvent.StateEventId.LineNumber;

            if (stateEntityIdLineNumber != eventEntityIdLineNumber)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id LineNumber {0} in state but entity id LineNumber {1} in event", stateEntityIdLineNumber, eventEntityIdLineNumber);
            }
            id.Append(stateEntityIdLineNumber).Append(",");

            id.Append("]");

            if (ForReapplying)
            {
                return;
            }
            var stateVersion = this.Version;
            var eventVersion = stateEvent.Version;

            if (InOutLineState.VersionZero == eventVersion)
            {
                eventVersion = stateEvent.Version = stateVersion;
            }
            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 21
0
        protected void ThrowOnWrongEvent(IUserClaimStateEvent stateEvent)
        {
            var id = new System.Text.StringBuilder();

            id.Append("[").Append("UserClaim|");

            var stateEntityIdUserId = (this as IGlobalIdentity <UserClaimId>).GlobalId.UserId;
            var eventEntityIdUserId = stateEvent.StateEventId.UserId;

            if (stateEntityIdUserId != eventEntityIdUserId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id UserId {0} in state but entity id UserId {1} in event", stateEntityIdUserId, eventEntityIdUserId);
            }
            id.Append(stateEntityIdUserId).Append(",");

            var stateEntityIdClaimId = (this as IGlobalIdentity <UserClaimId>).GlobalId.ClaimId;
            var eventEntityIdClaimId = stateEvent.StateEventId.ClaimId;

            if (stateEntityIdClaimId != eventEntityIdClaimId)
            {
                throw DomainError.Named("mutateWrongEntity", "Entity Id ClaimId {0} in state but entity id ClaimId {1} in event", stateEntityIdClaimId, eventEntityIdClaimId);
            }
            id.Append(stateEntityIdClaimId).Append(",");

            id.Append("]");

            if (ForReapplying)
            {
                return;
            }
            var stateVersion = this.Version;
            var eventVersion = stateEvent.Version;

            if (UserClaimState.VersionZero == eventVersion)
            {
                eventVersion = stateEvent.Version = stateVersion;
            }
            if (stateVersion != eventVersion)
            {
                throw OptimisticConcurrencyException.Create(stateVersion, eventVersion, id.ToString());
            }
        }
Esempio n. 22
0
        public void AppendEventsToStream(IIdentity id, long streamVersion, ICollection <IEvent> events)
        {
            if (events.Count == 0)
            {
                return;
            }
            // functional events don't have an identity
            var name = IdentityToKey(id);

            try
            {
                _store.AppendToStore(name, MessageAttribute.Empty, streamVersion, events.Cast <object>().ToArray());
            }
            catch (AppendOnlyStoreConcurrencyException e)
            {
                // load server events
                var server = LoadEventStream(id);
                // throw a real problem
                throw OptimisticConcurrencyException.Create(server.StreamVersion, e.ExpectedStreamVersion, id, server.Events);
            }
        }
Esempio n. 23
0
        public static HttpStatusCodeInfo Map(Exception exception)
        {
            if (CustomMaps.ContainsKey(exception.GetType()))
            {
                return(CustomMaps[exception.GetType()](exception));
            }

            var code = exception switch
            {
                ValidationException _ => HttpStatusCode.BadRequest,
                System.ComponentModel.DataAnnotations.ValidationException _ => HttpStatusCode.BadRequest,
                ArgumentException _ => HttpStatusCode.BadRequest,
                UnauthorizedAccessException _ => HttpStatusCode.Unauthorized,
                InvalidOperationException _ => HttpStatusCode.Forbidden,
                NotFoundException _ => HttpStatusCode.NotFound,
                OptimisticConcurrencyException _ => HttpStatusCode.Conflict,
                NotImplementedException _ => HttpStatusCode.NotImplemented,
                _ => HttpStatusCode.InternalServerError
            };

            return(new HttpStatusCodeInfo(code, exception.Message));
        }
        public void An_OptimisticConcurrencyException_is_a_concurrency_exception()
        {
            var exception = new OptimisticConcurrencyException();

            exception.IsConcurrencyException().Should().BeTrue();
        }
 // <summary>
 // Initializes a new instance of the <see cref="DbUpdateConcurrencyException" /> class.
 // </summary>
 // <param name="context"> The context. </param>
 // <param name="innerException"> The inner exception. </param>
 internal DbUpdateConcurrencyException(InternalContext context, OptimisticConcurrencyException innerException)
     : base(context, innerException, involvesIndependentAssociations: false)
 {
 }
Esempio n. 26
0
 internal DbUpdateConcurrencyException(
     InternalContext context,
     OptimisticConcurrencyException innerException)
     : base(context, (UpdateException)innerException, false)
 {
 }
        public void An_OptimisticConcurrencyException_is_a_concurrency_exception()
        {
            var exception = new OptimisticConcurrencyException();

            exception.IsConcurrencyException().Should().BeTrue();
        }