示例#1
2
        public void PersistUpdateOf(IAggregateRoot entity)
        {
            Account account = entity as Account;

            string sql = "UPDATE Account SET Balance=@Balance WHERE Id=@Id";
            SqlParameter parameter1 = new SqlParameter("@Id", account.Id);
            SqlParameter parameter2= new SqlParameter("@Balance", account.Balance);

            using (SqlConnection conn = new SqlConnection(_connStr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.Add(parameter1);
                    cmd.Parameters.Add(parameter2);

                    int affectedCount = cmd.ExecuteNonQuery();

                    if (affectedCount <= 0) 
                    {
                        throw new Exception("update Account failed");
                    }
                }
            }
        }
		public UserSnapshot(IAggregateRoot root, string name, int age)
		{
			Id = root.Id;
			Version = root.Version;
			Name = name;
			Age = age;
		}
 public void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
 {
     if (!addedEntities.ContainsKey(entity))
     {
         addedEntities.Add(entity, unitOfWorkRepository);
     }
 }
 public void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
 {
     if (!deletedEntities.ContainsKey(entity))
     {
         deletedEntities.Add(entity, unitOfWorkRepository);
     }
 }
示例#5
0
 public void RegisterAmended(IAggregateRoot objectEntity, IUnitOfWorkRepository unitOfWorkRepository)
 {
     if (!changedEntities.ContainsKey(objectEntity))
     {
         changedEntities.Add(objectEntity, unitOfWorkRepository);
     }
 }
示例#6
0
 public void Add(IAggregateRoot entity, IUnitOfWorkRepository uowRepository)
 {
     if (!_addedEntities.ContainsKey(entity))
     {
         _addedEntities.Add(entity, uowRepository);
     }
 }
		public void RegisterUpdate(IAggregateRoot aggregateRoot, IUnitOfWorkRepository repository)
		{
			if (!_updatedAggregates.ContainsKey(aggregateRoot))
			{
				_updatedAggregates.Add(aggregateRoot, repository);
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="AggregateChangedEventArgs"/> class.
        /// </summary>
        /// <param name="aggregateRoot">The aggregate root.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="oldValue">The old value.</param>
        /// <param name="newValue">The new value.</param>
        public AggregateChangedEventArgs(
            IAggregateRoot aggregateRoot,
            IEntity entity,
            string propertyName,
            object oldValue,
            object newValue )
        {
            if ( aggregateRoot == null )
            {
                throw new ArgumentNullException ( "aggregateRoot" );
            }

            if ( entity == null )
            {
                throw new ArgumentNullException ( "entity" );
            }

            if ( string.IsNullOrWhiteSpace ( propertyName ) )
            {
                throw new ArgumentNullException ( "propertyName" );
            }

            AggregateChangedType = AggregateChangedType.PropertyValueChanged;
            AggregateRoot = aggregateRoot;
            SourceEntity = entity;
            PropertyName = propertyName;
            OldValue = oldValue;
            NewValue = newValue;
        }
 public void Add(IAggregateRoot aggregateRoot)
 {
     if (!_aggregateRoots.ContainsKey(aggregateRoot.AggregateRootId))
     {
         _aggregateRoots.TryAdd(aggregateRoot.AggregateRootId, aggregateRoot);
     }
 }
		public void RegisterDeletion(IAggregateRoot aggregateRoot, IUnitOfWorkRepository repository)
		{
			if (!_deletedAggregates.ContainsKey(aggregateRoot))
			{
				_deletedAggregates.Add(aggregateRoot, repository);
			}
		}
示例#11
0
 public void RegisterRemoved(IAggregateRoot objectEntity, IUnitOfWorkRepository unitOfWorkRepository)
 {
     if (!removedEntities.ContainsKey(objectEntity))
     {
         removedEntities.Add(objectEntity, unitOfWorkRepository);
     }
 }
 public void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository repository)
 {
     List<IAggregateRoot> items = null;
     if (!add.TryGetValue(repository, out items))
     {
         items = new List<IAggregateRoot>();
         add.Add(repository, items);
     }
     items.Add(entity);
 }
示例#13
0
 private EventStreamRecord BuildEventStream(IAggregateRoot aggregateRoot, string commandId)
 {
     return new EventStreamRecord()
     {
         AggregateRootId = aggregateRoot.AggregateRootId,
         CommandId = commandId,
         Version = aggregateRoot.Version,
         EventDatas = _binarySerializer.Serialize(aggregateRoot.GetUnCommitEvents())
     };
 }
		public void Handle(IAggregateRoot root, IDomainEvent ev)
		{
			MethodInvoker invoker;
			if (!_handlers.TryGetValue(ev.GetType(), out invoker))
			{
				throw new InvalidOperationException(string.Format("Apply method for event [{0}] wasn't resolved in [{1}]", ev.GetType().Name, root.GetType().Name));
			}

			invoker.Invoke(root, new object[] {ev});
		}
示例#15
0
 private DomainEventStreamMessage CreateMessage(IAggregateRoot aggregateRoot)
 {
     return new DomainEventStreamMessage(
         ObjectId.GenerateNewStringId(),
         aggregateRoot.UniqueId,
         aggregateRoot.Version + 1,
         aggregateRoot.GetType().FullName,
         aggregateRoot.GetChanges(),
         new Dictionary<string, string>());
 }
示例#16
0
 public void Store(IDocumentSession session, IAggregateRoot root)
 {
    if (ShouldPersistSnapshot(root))
    {
       StoreSnapshot(session, root);
       SetRecentSnaphotVersion(session, root);
    }
    else
    {
       StoreEvents(session, root);
    }
 }
示例#17
0
        public Snapshot CreateSnapshot(IAggregateRoot aggregateRoot)
        {
            if (aggregateRoot == null)
            {
                throw new ArgumentNullException("aggregateRoot");
            }

            var payload = _binarySerializer.Serialize(aggregateRoot);
            var aggregateRootTypeCode = _aggregateRootTypeCodeProvider.GetTypeCode(aggregateRoot.GetType());

            return new Snapshot(aggregateRootTypeCode, aggregateRoot.UniqueId, aggregateRoot.Version, payload, DateTime.Now);
        }
        private static string CreateMessage(IAggregateRoot aggRoot, ICommand c, Exception ex)
        {
            var msg = "The action you were trying to perform succeeded, however not all systems have been updated yet.";
            msg += Environment.NewLine;
            msg += Environment.NewLine;
            msg += "Aggregate ID: " + aggRoot.AggregateId.ToString();
            msg += Environment.NewLine;
            msg += "Command ID: " + c.CommandId.ToString();
            msg += Environment.NewLine;
            msg += "Exception: " + ex.GetType().Name + " - " + ex.Message;

            return msg;
        }
		internal static void Apply(IAggregateRoot root, IDomainEvent ev)
		{
			var rootType = root.GetType();
			EventHandlerRegistry registry;
			if (!_handlers.TryGetValue(rootType, out registry))
			{
				registry = new EventHandlerRegistry(ApplyMethodResolver.ResolveAll(rootType));
				_handlers[rootType] = registry;
			}

			registry.Handle(root, ev);

			//ResolveApplyMethodDelegate(root.GetType(), ev.GetType())(root, ev);
		}
示例#20
0
 public void RegisterAdd(IAggregateRoot entity, IUnitOfWorkRepository unitOfWorkRepository)
 {
     if (_ItemQueue == null)
         _ItemQueue = new Queue<UnitItem>();
     UnitItem unitItem=new UnitItem()
     { Entity = entity, UnitOfWorkRepository = unitOfWorkRepository, Operator = UnitOperator.Add };
     if (_ItemQueue.Contains(unitItem))
     {
         throw new Exception("exist Entity in RegistorAdd!");
     }
     else
     {
         _ItemQueue.Enqueue(unitItem);
     }
 }
        private static string CreateMessage(IAggregateRoot aggRoot, Guid originalVersion, Guid currentVersion)
        {
            var aggType = aggRoot.GetType().Name;

            var msg = string.Format("The {0} you were trying to save has been updated by another user, you will have to start the editing process again to retry.", aggType);
            msg += Environment.NewLine;
            msg += Environment.NewLine;
            msg += "Aggregate ID: " + aggRoot.AggregateId.ToString();
            msg += Environment.NewLine;
            msg += "Original Version: " + originalVersion.ToString();
            msg += Environment.NewLine;
            msg += "Current Version: " + currentVersion.ToString();

            return msg;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AggregateChangedEventArgs"/> class.
        /// </summary>
        /// <param name="aggregateRoot">The aggregate root.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="aggregateChangedType">Type of the aggregate changed.</param>
        /// <param name="collectionItem">The collection item.</param>
        public AggregateChangedEventArgs(
            IAggregateRoot aggregateRoot,
            IEntity entity,
            string propertyName,
            AggregateChangedType aggregateChangedType,
            object collectionItem )
        {
            if ( aggregateRoot == null )
            {
                throw new ArgumentNullException ( "aggregateRoot" );
            }

            if ( entity == null )
            {
                throw new ArgumentNullException ( "entity" );
            }

            if ( string.IsNullOrWhiteSpace ( propertyName ) )
            {
                throw new ArgumentNullException ( "propertyName" );
            }

            if ( aggregateChangedType == AggregateChangedType.PropertyValueChanged )
            {
                throw new ArgumentException ( "This constructor is for collection changes only." );
            }

            if ( collectionItem == null )
            {
                throw new ArgumentNullException ( "collectionItem" );
            }

            AggregateChangedType = aggregateChangedType;
            AggregateRoot = aggregateRoot;
            SourceEntity = entity;
            PropertyName = propertyName;

            if ( AggregateChangedType == AggregateChangedType.CollectionItemAdded )
            {
                NewValue = collectionItem;
            }
            else
            {
                OldValue = collectionItem;
            }
        }
 public void ReplayEvents(IAggregateRoot aggregateRoot, IEnumerable<EventStream> eventStreams)
 {
     foreach (var eventStream in eventStreams)
     {
         VerifyEvent(aggregateRoot, eventStream);
         if (aggregateRoot.UniqueId == null && eventStream.Version == 1L)
         {
             aggregateRoot.UniqueId = eventStream.AggregateRootId;
         }
         foreach (var evnt in eventStream.Events)
         {
             HandleEvent(aggregateRoot, evnt);
         }
         IncreaseAggregateVersion(aggregateRoot);
         if (aggregateRoot.Version != eventStream.Version)
         {
             throw new ENodeException("Aggregate root version mismatch, aggregateId:{0}, current version:{1}, expected version:{2}", aggregateRoot.UniqueId, aggregateRoot.Version, eventStream.Version);
         }
     }
 }
        private bool TryGetFromSnapshot(string aggregateRootId, Type aggregateRootType, out IAggregateRoot aggregateRoot)
        {
            aggregateRoot = null;

            var snapshot = _snapshotStore.GetLastestSnapshot(aggregateRootId, aggregateRootType);
            if (snapshot == null) return false;

            aggregateRoot = _snapshotter.RestoreFromSnapshot(snapshot);
            if (aggregateRoot == null) return false;

            if (aggregateRoot.UniqueId != aggregateRootId)
            {
                throw new Exception(string.Format("Aggregate root restored from snapshot not valid as the aggregate root id not matched. Snapshot aggregate root id:{0}, expected aggregate root id:{1}", aggregateRoot.UniqueId, aggregateRootId));
            }

            var aggregateRootTypeCode = _aggregateRootTypeCodeProvider.GetTypeCode(aggregateRootType);
            var eventStreamsAfterSnapshot = _eventStore.QueryAggregateEvents(aggregateRootId, aggregateRootTypeCode, snapshot.Version + 1, int.MaxValue);
            aggregateRoot.ReplayEvents(eventStreamsAfterSnapshot);
            return true;
        }
 public void PersistUncommitedEvents(IAggregateRoot aggregate)
 {
     try
     {
         persistenceManager.ExecuteNonQuery(
             "INSERT INTO [Events] (Id, aggregate_id, version, data) VALUES (@Id, @AggregateId, @Version, @Data)",
             new
             {
                 Id = Guid.NewGuid(),
                 Version = aggregate.Version + 1,
                 AggregateId = aggregate.Id,
                 Data = Serialize(aggregate.UncommitedEvents)
             });
     }
     catch (SqlException se)
     {
         // Thanks Jonathan Oliver's CQRS Event Store
         if (se.Number == UniqueKeyViolation) throw new ConcurrencyException();
         throw;
     }
 }
        private bool TryGetFromSnapshot(string aggregateRootId, Type aggregateRootType, out IAggregateRoot aggregateRoot)
        {
            aggregateRoot = _aggregateSnapshotter.RestoreFromSnapshot(aggregateRootType, aggregateRootId);

            if (aggregateRoot == null) return false;

            if (aggregateRoot.GetType() != aggregateRootType || aggregateRoot.UniqueId != aggregateRootId)
            {
                throw new Exception(string.Format("AggregateRoot recovery from snapshot is invalid as the aggregateRootType or aggregateRootId is not matched. Snapshot: [aggregateRootType:{0},aggregateRootId:{1}], expected: [aggregateRootType:{2},aggregateRootId:{3}]",
                    aggregateRoot.GetType(),
                    aggregateRoot.UniqueId,
                    aggregateRootType,
                    aggregateRootId));
            }

            var aggregateRootTypeName = _typeNameProvider.GetTypeName(aggregateRootType);
            var eventStreamsAfterSnapshot = _eventStore.QueryAggregateEvents(aggregateRootId, aggregateRootTypeName, aggregateRoot.Version + 1, int.MaxValue);
            aggregateRoot.ReplayEvents(eventStreamsAfterSnapshot);

            return true;
        }
示例#27
0
 public Entity(SerializationInfo info, StreamingContext context)
 {
     _root  = (IAggregateRoot)info.GetValue("_root", typeof(IAggregateRoot));
     _state = (TEntityState)info.GetValue("_state", typeof(TEntityState));
 }
示例#28
0
 public void RegisterForTracking(IAggregateRoot aggregatedRoot)
 {
     _objectsTracked.Add(aggregatedRoot);
 }
示例#29
0
 public void PersistDeletionOf(IAggregateRoot entity)
 {
     this.Remove((TZ)entity);
 }
示例#30
0
 protected void RegisterUpdated(IAggregateRoot obj)
 {
     DataContext.Current.RegisterUpdated(obj, this);
 }
示例#31
0
 public static List <IDomainEvent> GetAllDomainEvents(IAggregateRoot aggregate)
 {
     return(GetAllDomainEvents(aggregate as Entity));
 }
 public RepositoryPrePersistEventArgs(IAggregateRoot target, RepositoryAction action)
 {
     this.Target = target;
     this.Action = action;
     this.Allow  = true; //默认是允许执行后续操作的
 }
示例#33
0
        public void PersistUpdateOf(IAggregateRoot entity)
        {
            Book updatedBook = _bookMapper.ToDocument((Core.Entities.Book)entity);

            _books.ReplaceOne(book => book.Id == updatedBook.Id, updatedBook);
        }
示例#34
0
 public ChildEntity(IAggregateRoot aggregateRoot, IEnumerable <IChildEntityEvent> events)
     : base(aggregateRoot, events)
 {
 }
示例#35
0
 public ChildEntity(IAggregateRoot aggregateRoot, ChildEntityId id, string name)
     : base(aggregateRoot, new ChildCreated((ParentEntityId)aggregateRoot.Id, id, name, DateTime.UtcNow))
 {
 }
示例#36
0
 public AggregateCacheInfo(IAggregateRoot aggregateRoot)
 {
     AggregateRoot = aggregateRoot;
     LastUpdateTime = DateTime.Now;
 }
示例#37
0
 private static bool ShouldPersistSnapshot(IAggregateRoot root)
 {
     return(root.Version % 3 == 1);
 }
示例#38
0
 public void Set(IAggregateRoot aggregateRoot)
 {
     SetInternal(aggregateRoot);
 }
示例#39
0
 public void PersistUpdateOf(IAggregateRoot root)
 {
     throw new NotImplementedException();
 }
 public TestChildEntity(IAggregateRoot aggregateRoot, string id, string name)
     : base(aggregateRoot, new TestEntityChildAdded((string)aggregateRoot.Id, id, name))
 {
 }
示例#41
0
        public void PersistDeletionOf(IAggregateRoot entity)
        {
            Book bookToDelete = _bookMapper.ToDocument((Core.Entities.Book)entity);

            _books.DeleteOne(book => book.Id == bookToDelete.Id);
        }
        public EventProviderDescriptor(IAggregateRoot aggregateRoot)
        {
            Contract.Requires(aggregateRoot != null);

            Value = aggregateRoot.ToString();
        }
示例#43
0
        public void PersistCreationOf(IAggregateRoot entity)
        {
            Book book = _bookMapper.ToDocument((Core.Entities.Book)entity);

            _books.InsertOne(book);
        }
示例#44
0
 public Task AddAsync(IAggregateRoot aggregateRoot)
 {
     Add(aggregateRoot);
     return(Task.CompletedTask);
 }
示例#45
0
 public void PersistUpdateOf(IAggregateRoot entity)
 {
 }
示例#46
0
 public void PersistCreationOf(IAggregateRoot entity)
 {
 }
示例#47
0
 public bool ShouldCreateSnapshot(IAggregateRoot snapshotAggregateRoot)
 {
     return(true);
 }
示例#48
0
        protected void RegisterRollbackUpdate(IAggregateRoot obj)
        {
            var args = new RepositoryRollbackEventArgs(obj, this, RepositoryAction.Update);

            DataContext.Current.RegisterRollback(args);
        }
示例#49
0
 public void PersistDeletionOf(IAggregateRoot entity)
 {
 }
示例#50
0
 /// <summary>
 /// 创建对象
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="unitofWorkRepository"></param>
 public void RegisterNew(IAggregateRoot entity, IUnitOfWorkRepository unitofWorkRepository)
 {
     unitofWorkRepository.PersistCreationOf(entity);
 }
示例#51
0
 public EntityRepositoryPair(IAggregateRoot entity, IUnitOfWorkRepository repository)
 {
     Entity     = entity;
     Repository = repository;
 }
示例#52
0
 public void PersistDeletionOf(IAggregateRoot entity)
 {
     throw new NotImplementedException();
 }
示例#53
0
 public void PersistUpdateOf(IAggregateRoot entity)
 {
     this.Save((TZ)entity);
 }
示例#54
0
 public EntityEntry(IAggregateRoot instance, EntityState entityState)
 {
     Instance    = instance;
     EntityState = entityState;
 }
示例#55
0
 /// <summary>
 /// 修改对象
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="unitofWorkRepository"></param>
 public void RegisterAmended(IAggregateRoot entity, IUnitOfWorkRepository unitofWorkRepository)
 {
     unitofWorkRepository.PersistUpdateOf(entity);
 }
示例#56
0
 /// <summary>
 /// Refuses the specified root.
 /// </summary>
 /// <typeparam name="TEntity">The type of the entity.</typeparam>
 /// <param name="root">The root.</param>
 /// <param name="event">The @event.</param>
 public void Refuse(IAggregateRoot <TEntity, TId> root, IDomainEvent <TEntity> @event)
 {
     //Raul no hace nada es el por defecto, por defecto me la pelo
 }
示例#57
0
 public void Track(IAggregateRoot root)
 {
     _trackedObjects.Add(root);
 }
示例#58
0
 /// <summary>
 /// 删除对象
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="unitofWorkRepository"></param>
 public void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository unitofWorkRepository)
 {
     unitofWorkRepository.PersistDeletionOf(entity);
 }
 /// <summary>
 /// Registers an entity to be removed when commited.
 /// </summary>
 /// <param name="entity">Entity.</param>
 /// <param name="repository">Repository.</param>
 public virtual void RegisterRemoved(IAggregateRoot entity, IUnitOfWorkRepository repository)
 {
     Entities.Add(new EntityRepositoryPair(new UnitOfWorkEntity(entity, UnitOfWorkEntityState.Removed), repository));
 }
示例#60
0
        public void PersistUpdate(IAggregateRoot aggregateRoot)
        {
            DatabaseType databaseType = RetrieveDatabaseTypeFrom(aggregateRoot);

            ObjectContextFactory.Create().UpdateEntity <DatabaseType>(databaseType);
        }