Esempio n. 1
0
 public void SetUp()
 {
     BootStrapper.BootUp(this, null);
     _service = NcqrsEnvironment.Get <ICommandService>();
     _service.Execute(new CreateNewNote());
     _rand = new Random(DateTime.Now.Millisecond);
 }
Esempio n. 2
0
        protected override void When()
        {
            ExecutedCommand = WhenExecuting();
            var cmdService = NcqrsEnvironment.Get <ICommandService>();

            cmdService.Execute(ExecutedCommand);
        }
Esempio n. 3
0
 protected override void SetupDependencies()
 {
     base.SetupDependencies();
     GenerateEventSourceId();
     RecordGivenEvents();
     CommandService = NcqrsEnvironment.Get <ICommandService>();
 }
Esempio n. 4
0
        private void RecordGivenEvents()
        {
            var store            = NcqrsEnvironment.Get <IEventStore>();
            var givenEventStream = ConvertGivenEvents();

            store.Store(givenEventStream);
        }
Esempio n. 5
0
        public void Map(MapsToAggregateRootConstructorAttribute attribute, ICommand command, IMappedCommandExecutor executor)
        {
            var commandType = command.GetType();

            ValidateCommandType(commandType);

            var match = GetMatchingConstructor(attribute, commandType);
            Func <ICommand, AggregateRoot> create = (c) =>
            {
                var parameter = match.Item2.Select(p => p.GetValue(c, null));
                return((AggregateRoot)match.Item1.Invoke(parameter.ToArray()));
            };

            Action executorAction = () => executor.ExecuteActionCreatingNewInstance(create);

            if (commandType.IsDefined(typeof(TransactionalAttribute), false))
            {
                var transactionService = NcqrsEnvironment.Get <ITransactionService>();
                transactionService.ExecuteInTransaction(executorAction);
            }
            else
            {
                executorAction();
            }
        }
Esempio n. 6
0
        public void LoadItUp()
        {
            IList <Guid> ids = new List <Guid>();

            for (int i = 0; i < 5; i++)
            {
                Guid id = Guid.NewGuid();
                ids.Add(id);

                NcqrsEnvironment.Get <ICommandService>().Execute(new Env.CreateNoteCommand()
                {
                    NoteId   = id,
                    NoteText = "Hello world " + i
                });
            }


            foreach (Guid id in ids)
            {
                NcqrsEnvironment.Get <ICommandService>().Execute(new Env.ChangeNoteCommand()
                {
                    NoteId      = id,
                    NewNoteText = "Hello solar system"
                });
            }

            foreach (Guid id in ids)
            {
                NcqrsEnvironment.Get <ICommandService>().Execute(new Env.ChangeNoteCommand()
                {
                    NoteId      = id,
                    NewNoteText = "Hello galaxy"
                });
            }
        }
        public void Map(MapsToAggregateRootMethodAttribute attribute, ICommand command, IMappedCommandExecutor executor)
        {
            var commandType = command.GetType();

            ValidateCommandType(commandType);

            var match = GetMatchingMethod(attribute, commandType, attribute.MethodName);

            Action <AggregateRoot, ICommand> action =
                (agg, cmd) =>
            {
                var parameter = match.Item2.Select(p => p.GetValue(cmd, null));
                match.Item1.Invoke(agg, parameter.ToArray());
            };

            Action executorAction = () => executor.ExecuteActionOnExistingInstance(GetAggregateRootId, GetAggregateRootType, action);

            if (commandType.IsDefined(typeof(TransactionalAttribute), false))
            {
                var transactionService = NcqrsEnvironment.Get <ITransactionService>();
                transactionService.ExecuteInTransaction(executorAction);
            }
            else
            {
                executorAction();
            }
        }
 public void Send(object payload)
 {
     _message.Payload    = payload;
     _message.SenderId   = _senderId;
     _message.SenderType = GetType();
     _message.MessageId  = NcqrsEnvironment.Get <IUniqueIdentifierGenerator>().GenerateNewId();
     _sendAction(_message);
 }
Esempio n. 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventSource"/> class.
        /// </summary>
        protected EventSource()
        {
            InitialVersion = 0;

            var idGenerator = NcqrsEnvironment.Get <IUniqueIdentifierGenerator>();

            EventSourceId = idGenerator.GenerateNewId();
        }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonEventFormatter"/> class
        /// with a given type resolver.
        /// </summary>
        /// <param name="typeResolver">The <see cref="IEventTypeResolver"/> to use
        /// when resolving event types/names.</param>
        /// <exception cref="ArgumentNullException"><paramref name="typeResolver"/> is <value>null</value>.</exception>
        public JsonEventFormatter(IEventTypeResolver typeResolver)
        {
            Contract.Requires <ArgumentNullException>(typeResolver != null, "typeResolver");

            _typeResolver = typeResolver;
            _serializer   = new JsonSerializer {
                ContractResolver = NcqrsEnvironment.Get <IContractResolver>()
            };
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Event"/> class.
        /// </summary>
        public Event()
        {
            var idGenerator = NcqrsEnvironment.Get <IUniqueIdentifierGenerator>();
            var clock       = NcqrsEnvironment.Get <IClock>();

            EventIdentifier = idGenerator.GenerateNewId();
            EventTimeStamp  = clock.UtcNow();
            EventVersion    = DefaultVersion;
        }
 public void Public_event_handlers_should_be_mapped()
 {
     using (var work = NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork(Guid.NewGuid()))
     {
         var target = new TheAggregateRoot();
         target.ApplyEvent(new EventForPublicMethod());
         target.OnEventForPublicMethodInvokedCount.Should().Be(1);
     }
 }
Esempio n. 13
0
        public void When_get_is_called_when_the_environmemt_is_not_configured_defaults_should_still_be_returned()
        {
            NcqrsEnvironment.Deconfigure();

            var defaultClock = new DateTimeBasedClock();

            NcqrsEnvironment.SetDefault <IClock>(defaultClock);

            NcqrsEnvironment.Get <IClock>().Should().Be(defaultClock);
        }
Esempio n. 14
0
        protected override void ExecuteInContext(IUnitOfWorkContext context, AddInvoiceItem command)
        {
            ITaxRepository taxRepo = NcqrsEnvironment.Get <ITaxRepository>();
            Tax            tax     = taxRepo.FindByCode(command.TaxCode, command.OwnerId);

            Invoice invoice = context.GetById <Invoice>(command.InvoiceId, command.KnownVersion);

            invoice.AddInvoiceItem(command.ItemId, command.Description, command.Quantity, command.Price, command.DiscountInPercent, tax, command.OwnerId, command.UserName);
            context.Accept();
        }
Esempio n. 15
0
 public void Process(object message)
 {
     using (var work = NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork())
     {
         var incomingMessage     = ReceiveMessage(message);
         var targetAggregateRoot = GetReceiver(work, incomingMessage);
         targetAggregateRoot.ProcessMessage(incomingMessage);
         work.Accept();
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Used by WCF to enumerate all types inheriting from <see cref="CommandBase"/>,
        /// so that instances of them can be sent to a service operation that expects a command.
        /// </summary>
        /// <returns>An enumeration of all classes in the current AppDomain inheriting from <see cref="CommandBase" /></returns>
        public static IEnumerable <Type> GetKnownTypes()
        {
            var knownCommandsEnumerator = NcqrsEnvironment.Get <IKnownCommandsEnumerator>();

            if (knownCommandsEnumerator == null)
            {
                throw new InvalidOperationException("No Ncqrs.Commanding.IKnownCommandsEnumerator implementation registered with the NcqrsEnvironment.");
            }
            return(knownCommandsEnumerator.GetAllCommandTypes());
        }
        public void Methods_marked_as_no_event_handler_should_not_be_mapped()
        {
            using (var work = NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork(Guid.NewGuid()))
            {
                var target = new TheAggregateRoot();

                Action act = () => target.ApplyEvent(new EventForNoEventHandlerMethod());

                act.ShouldThrow <EventNotHandledException>();
            }
        }
        public void Method_with_a_wrong_method_name_should_not_be_mapped()
        {
            using (var work = NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork(Guid.NewGuid()))
            {
                var target = new TheAggregateRoot();

                Action act = () => target.ApplyEvent(new EventForMethodWithWrongMethodName());

                act.ShouldThrow <EventNotHandledException>();
            }
        }
Esempio n. 19
0
        public Note(Guid noteId, String text) : base(noteId)
        {
            var clock = NcqrsEnvironment.Get <IClock>();

            ApplyEvent(new NewNoteAddedEvent
            {
                NoteId       = noteId,
                Text         = text,
                CreationDate = clock.UtcNow()
            });
        }
Esempio n. 20
0
        public Note(Guid id, string text) : base(id)
        {
            var clock = NcqrsEnvironment.Get <IClock>();

            this.ApplyEvent(new NoteAdded
            {
                Id           = id,
                Text         = text,
                CreationDate = clock.UtcNow()
            });
        }
Esempio n. 21
0
        public void Setting_a_default_should_override_the_exiting_default()
        {
            var defaultFoo    = MockRepository.GenerateMock <IFoo>();
            var newDefaultFoo = MockRepository.GenerateMock <IFoo>();

            NcqrsEnvironment.SetDefault <IFoo>(defaultFoo);
            NcqrsEnvironment.SetDefault <IFoo>(newDefaultFoo);

            var result = NcqrsEnvironment.Get <IFoo>();

            result.Should().BeSameAs(newDefaultFoo);
        }
Esempio n. 22
0
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        /// <returns>The aggregateroot of type <typeparamref name="TAggRoot"/> on which we executed the command.</returns>
        void ICommandExecutor <TCommand> .Execute(TCommand command)
        {
            var factory = NcqrsEnvironment.Get <IUnitOfWorkFactory>();

            using (var work = factory.CreateUnitOfWork())
            {
                var aggregateroot = _aggregaterootfetchfunc(_getidfromcommandfunc(command));
                _mappedmethodforcommandfunc(command, aggregateroot);

                work.Accept();
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            NcqrsEnvironment.SetDefault(InitializeEventStore());
            NcqrsEnvironment.SetDefault(InitializeCommandService());

            var commandService = NcqrsEnvironment.Get <ICommandService>();
            var id             = new Guid("AE6920ED-381A-467D-8DB2-EE91E851F431");

            commandService.Execute(new ChangeNameCommand(id, "Jane Smith Doe"));

            Console.WriteLine("If you see this message and no exception occurred, it had probably worked. You are all clear now!");
            Console.ReadKey(true);
        }
Esempio n. 24
0
        /// <summary>
        /// Constructor, initializes a new instance of <see cref="MappedCommandToAggregateRootMethod&lt;TCommand, TAggRoot&gt;"/>.
        /// </summary>
        /// <param name="getidfromcommandfunc">The method responsible for retrieving the id of the aggregateroot from the command.</param>
        /// <remarks>Marked as internal because the construction is only allowed in the framework.</remarks>
        internal MappedCommandToAggregateRootMethod(Func <TCommand, Guid> getidfromcommandfunc)
        {
            _getidfromcommandfunc = getidfromcommandfunc;

            // default get aggregateroot code
            var factory = NcqrsEnvironment.Get <IUnitOfWorkFactory>();

            using (var work = factory.CreateUnitOfWork())
            {
                _aggregaterootfetchfunc = (guid) => work.GetById <TAggRoot>(guid);
                work.Accept();
            }
        }
        public void After_sending_message_event_is_applied()
        {
            using (NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork())
            {
                IMessagingAggregateRoot root = new TestMessagingAggregateRoot();
                root.ProcessMessage(new IncomingMessage()
                {
                    Payload = new TestMessage()
                });

                Assert.AreEqual(1, ((AggregateRoot)root).GetUncommittedEvents().Count());
            }
        }
Esempio n. 26
0
        public IUnitOfWorkContext CreateUnitOfWork()
        {
            if (UnitOfWork.Current != null)
            {
                throw new InvalidOperationException("There is already a unit of work created for this context.");
            }

            var store = NcqrsEnvironment.Get <IEventStore>();
            var bus   = NcqrsEnvironment.Get <IEventBus>();

            var repository = new DomainRepository(store, bus);

            return(new UnitOfWork(repository));
        }
Esempio n. 27
0
        public void Applying_an_event_should_not_effect_the_initial_version()
        {
            using (NcqrsEnvironment.Get <IUnitOfWorkFactory>().CreateUnitOfWork())
            {
                var theAggregate = new MyAggregateRoot();

                theAggregate.InitialVersion.Should().Be(0);
                theAggregate.MethodThatCausesAnEventThatHasAHandler();
                theAggregate.InitialVersion.Should().Be(0);
                theAggregate.MethodThatCausesAnEventThatHasAHandler();
                theAggregate.InitialVersion.Should().Be(0);
                theAggregate.MethodThatCausesAnEventThatHasAHandler();
            }
        }
Esempio n. 28
0
        public Note(Guid noteId, String text) : base(noteId)
        {
            var clock = NcqrsEnvironment.Get <IClock>();

            // Apply a NewNoteAdded event that reflects the
            // creation of this instance. The state of this
            // instance will be update in the handler of
            // this event (the OnNewNoteAdded method).
            ApplyEvent(new NewNoteAdded
            {
                Text         = text,
                CreationDate = clock.UtcNow()
            });
        }
        protected void Reply(object payload)
        {
            var message = new OutgoingMessage
            {
                Payload          = payload,
                SenderId         = EventSourceId,
                SenderType       = GetType(),
                MessageId        = NcqrsEnvironment.Get <IUniqueIdentifierGenerator>().GenerateNewId(),
                ReceiverId       = MessagingContext.MessageBeingProcessed.SenderId,
                RelatedMessageId = MessagingContext.MessageBeingProcessed.MessageId
            };

            ApplyEvent(new MessageSentEvent(DateTime.Now, message));
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            NcqrsEnvironment.SetDefault(InitializeEventStore());
            NcqrsEnvironment.SetDefault(InitializeCommandService());

            var commandService = NcqrsEnvironment.Get <ICommandService>();
            var id             = new Guid("AE6920ED-381A-467D-8DB2-EE91E851F431");

            commandService.Execute(new ChangeNameCommand(id, "Jane", "Doe"));

            Console.WriteLine("If you see this message and no exception occurred, it had probably worked. Now you can run AppV3.");
            Console.WriteLine("Press any key to continue");
            Console.ReadLine();
        }