예제 #1
0
        public async Task Handle(ProductAddedEvent message)
        {
            var shop = await _shopRepository.Get(message.ShopId);

            var notification = new NotificationAggregate
            {
                Id              = Guid.NewGuid().ToString(),
                Content         = "add_product",
                CreatedDateTime = DateTime.UtcNow,
                IsRead          = false,
                From            = shop.Subject,
                To              = shop.Subject,
                Parameters      = new[]
                {
                    new NotificationParameter
                    {
                        Id    = Guid.NewGuid().ToString(),
                        Type  = NotificationParameterTypes.ProductId,
                        Value = message.Id
                    }
                }
            };
            await _notificationRepository.Add(notification);

            _eventPublisher.Publish(new NotificationAddedEvent
            {
                Id      = notification.Id,
                Content = notification.Content,
                IsRead  = notification.IsRead,
                From    = notification.From,
                To      = notification.To
            });
        }
        /// <summary>
        /// Handles the AddNewProduct Command and raises corresponding events.
        /// </summary>
        /// <param name="request">Command object</param>
        /// <param name="cancellationToken"> Propagates notification that operations should be canceled.</param>
        /// <returns>AddNewProductResult a result of the command execution</returns>
        public async Task <AddNewProductResult> Handle(AddNewProductCommand request, CancellationToken cancellationToken = default(CancellationToken))
        {
            //Create Product from AddNewProductCommand request
            Product product = new Product {
                Name         = request.Name,
                Description  = request.Description,
                IsActive     = true,
                UnitPrice    = request.UnitPrice,
                UnitsInStock = request.UnitsInStock
            };

            //Log information
            _logger.LogInformation($"Add new product with name:{product.Name} and description : {product.Description} to store.");

            //Add Product to store.
            int productId = await _repository.Add(product);

            //Log information
            _logger.LogInformation($"Added product to store , new productId : {productId}");

            //Create ProductAddedEvent from request
            ProductAddedEvent @event = new ProductAddedEvent(product.ProductId, product.Name, product.Description, product.UnitPrice, product.UnitsInStock, product.IsActive);

            //Publish ProductAdded Event
            await _mediator.Publish(@event, cancellationToken);

            //Return result
            return(new AddNewProductResult {
                ProductId = productId
            });
        }
예제 #3
0
        public void ThenCartProductPriceShouldBeEqualProductPriceFromEvent()
        {
            ProductAddedEvent productAddedEvent = new ProductAddedEvent(_product);

            _cart.Apply(productAddedEvent);

            Assert.AreEqual(_product.Price, _cart.Products.First().Price);
        }
예제 #4
0
        public void ThenCartShouldBeContainProductNameFromEvent()
        {
            ProductAddedEvent productAddedEvent = new ProductAddedEvent(_product);

            _cart.Apply(productAddedEvent);

            Assert.NotNull(_product.Name);
            Assert.AreEqual(_product.Name, _cart.Products.First().Name);
        }
예제 #5
0
        public void ThenCartShouldContainOneProduct()
        {
            ProductAddedEvent productAddedEvent = new ProductAddedEvent(_product);

            _cart.Apply(productAddedEvent);

            Assert.NotNull(_cart.Products);
            Assert.True(_cart.Products.Count == 1);
        }
예제 #6
0
        public void ThenCartProductShouldBeEqualProductIdFromEvent()
        {
            ProductAddedEvent productAddedEvent = new ProductAddedEvent(_product);

            _cart.Apply(productAddedEvent);

            Assert.NotNull(_cart.Products.First().Id);
            Assert.AreEqual(_product, _cart.Products.First());
        }
예제 #7
0
        public void Twice_ThenCArtShouldContainTwoProducts()
        {
            ProductAddedEvent firstProductAddedEvent  = new ProductAddedEvent(_product);
            ProductAddedEvent secondProductAddedEvent = new ProductAddedEvent(_product);

            _cart.Apply(firstProductAddedEvent);
            _cart.Apply(secondProductAddedEvent);

            Assert.AreEqual(2, _cart.Products.Count);
        }
예제 #8
0
// ctrx
        public ProductReadModel(ProductAddedEvent @event)
        {
            Id         = @event.Id;
            Name       = @event.Name;
            CategoryId = @event.CategoryId;

            OrderAmount = 0;
            Review      = new ReviewReadModel();
            FieldValues = new Dictionary <int, object>();
        }
예제 #9
0
        public Task Handle(ProductAddedEvent message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var notifier = _connectionManager.GetHubContext <Notifier>();

            notifier.Clients.All.productAdded(_responseBuilder.GetProductAddedEvent(message));
            return(Task.FromResult(0));
        }
        public int Handle(AddProductCommand command)
        {
            // command validation ommited
            var product = new Product(command.Name, command.CategoryId);

            _database.Products.Add(product);
            _database.SaveChanges();

            var @event = new ProductAddedEvent(product.Id, product.Name, product.CategoryId);

            _mediator.Publish(@event);

            return(product.Id);
        }
예제 #11
0
        /// <summary>
        ///  Receive messages continuously from a Topic
        /// </summary>
        /// <param name="message"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Log the incoming msg
            _logger.LogInformation($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

            //Deserialize incoming msg
            ProductAddedEvent @event = JsonConvert.DeserializeObject <ProductAddedEvent> (Encoding.UTF8.GetString(message.Body));

            //Publish message to call the event handler
            await _mediator.Publish(@event, token).ConfigureAwait(false);

            // Complete the message so that it is not received again.
            await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken).ConfigureAwait(false);
        }
    public void Add(Product product)
    {
        var args = new NewProductArgs {
            Product = product
        };

        ProductAddedEvent?.Invoke(this, args);
        var retvals = args.ReturnValues;

        foreach (var ret in retvals)
        {
            Console.WriteLine(ret);
        }
    }
예제 #13
0
        private async Task AddProduct(ProductAddedEvent @event)
        {
            var entity = new ProductEntity
            {
                Id           = @event.Id,
                Name         = @event.Name.ToString(),
                Type         = @event.Type.ToString(),
                PartitionKey = @event.Type.ToString(),
                RowKey       = @event.Id.ToString(),
                Timestamp    = DateTime.UtcNow,
                IsActive     = @event.IsActive
            };

            await _tableStorageRepository.InsertAsync(TableReference, entity).ConfigureAwait(false);
        }
예제 #14
0
        public async Task HandleAsync(ProductAddedEvent @event)
        {
            var product = await productRepository.GetByIdAsync(@event.ProductId.IdAsString());

            var cart = await cartRepository.GetByIdAsync(@event.AggregateId.IdAsString());

            var cartItem = CartItemReadModel.CreateFor(@event.AggregateId.IdAsString(), @event.ProductId.IdAsString());

            cartItem.ProductName = product.Name;
            cartItem.Quantity    = @event.Quantity;
            cart.TotalItems     += @event.Quantity;
            await cartRepository.UpdateAsync(cart);

            await cartItemRepository.InsertAsync(cartItem);
        }
        public void Handle(ProductAddedEvent @event, DatabaseContext db)
        {
            try
            {
                var product = @event.Product;

                var categoryIds = !string.IsNullOrWhiteSpace(product.CategoryIds) ? product.CategoryIds.Split(',')
                                  .Select(Int32.Parse)
                                  .ToList() : new List <int>();

                var categories = db.Set <Category>()
                                 .Where(category => categoryIds.Contains(category.Id))
                                 .Distinct()
                                 .ToList();

                var productDetails = new ProductReadModel()
                {
                    AggregateRootId = product.Id,
                    Name            = product.Name,
                    CreatedDate     = product.CreateDate.UtcDateTime,
                    Code            = product.Code,
                    Amount          = product.Amount,
                    PhotoHeight     = product.Photo.Height,
                    PhotoUrl        = product.Photo.Url,
                    PhotoWidth      = product.Photo.Width,
                    CategoryIds     = product.CategoryIds,
                    CategoryNames   = categories?.Any() == true?string.Join(',', categories.Select(category => category.Name).ToList()) : string.Empty
                };

                db.Set <ProductReadModel>().Add(productDetails);

                @event.Message = "Product Succesfully placed...";
            }
            catch (Exception exc)
            {
                throw;
            }
        }
예제 #16
0
 internal void Apply(ProductAddedEvent ev)
 {
     Items.Add(new CartItem(ev.ProductId, ev.Quantity));
 }
예제 #17
0
 public async Task SendProductAdded(ProductAddedEvent productAddedEvent)
 {
     await Clients.All.SendAsync(SendMethods.ProductAdded.ToString(), productAddedEvent);
 }
 private ConsumeContext<ProductAddedEvent> GetContext(string productName = productName, string reference = reference)
 {
     var productAddedEvent = new ProductAddedEvent(productName, reference);
     return Mock.Of<ConsumeContext<ProductAddedEvent>>(x => x.Message == productAddedEvent);
 }
 public void Handle(ProductAddedEvent domainEvent)
 {
     throw new NotImplementedException();
 }