public void Handle(ProductUpdatedEvent @event, DatabaseContext db)
        {
            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 productReadModel = db.Set <ProductReadModel>().FirstOrDefault(x => x.AggregateRootId == @event.AggregateRootId);

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

                db.Set <ProductReadModel>().Update(productReadModel);
            }
        }
Example #2
0
        public void Update(
            DateTime addedDate,
            string addedBy,
            Guid departmentId,
            string title,
            string description,
            string SKU,
            decimal unitPrice,
            int discountPercentage,
            int unitsInStock,
            string smallImageUrl,
            string fullImageUrl,
            int votes,
            int totalRating)
        {
            var @event = new ProductUpdatedEvent
            {
                AggregateId        = Id,
                AddedBy            = addedBy,
                AddedDate          = addedDate,
                DepartmentId       = departmentId,
                Description        = description,
                DiscountPercentage = discountPercentage,
                FullImageUrl       = fullImageUrl,
                SKU           = SKU,
                SmallImageUrl = smallImageUrl,
                Title         = title,
                TotalRating   = totalRating,
                UnitPrice     = unitPrice,
                UnitsInStock  = unitsInStock,
                Votes         = votes
            };

            ApplyChange(@event);
        }
        /// <summary>
        /// Handles the UpdateProduct Command and raises corresponding events.
        /// </summary>
        /// <param name="request">Command Object</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns></returns>
        public async Task <Unit> Handle(UpdateProductCommand request, CancellationToken cancellationToken = default(CancellationToken))
        {
            //Create Product from command
            Product product = new Product {
                ProductId    = request.ProductId,
                Name         = request.Name,
                Description  = request.Description,
                IsActive     = request.IsActive,
                UnitPrice    = request.UnitPrice,
                UnitsInStock = request.UnitsInStock
            };

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

            //Updated Product
            await _repository.Update(product);

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

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

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

            //Return void
            return(new Unit());
        }
        public IIntegrationMessage OnUpdate(ProductUpdatedEvent message) =>
        message.Source.Status == ProductStatus.Published
                ? new Integration.Events.ProductUpdatedEvent
        {
            Product = MapProductDto(message.Source)
        }

                : null;
        private ConsumeContext <ProductUpdatedEvent> GetContext(string productName, string reference, string oldReference)
        {
            var productUpdatedEvent
                = new ProductUpdatedEvent {
                ProductName = productName, Reference = reference, OldReference = oldReference
                };

            return(Mock.Of <ConsumeContext <ProductUpdatedEvent> >(x => x.Message == productUpdatedEvent));
        }
 public void Handle(ProductUpdatedEvent notification)
 {
     var response = _elasticClient.Update(DocumentPath <ProductUpdatedEvent>
                                          .Id(notification.Id),
                                          u => u
                                          .Index("alias-product")
                                          .Type("product")
                                          .DocAsUpsert(true)
                                          .Doc(notification));
 }
Example #7
0
        public Task Handle(ProductUpdatedEvent message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

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

            notifier.Clients.All.productUpdated(_responseBuilder.GetProductUpdatedEvent(message));
            return(Task.FromResult(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
            ProductUpdatedEvent @event = JsonConvert.DeserializeObject <ProductUpdatedEvent> (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);
        }
Example #9
0
 public void Handle(ProductUpdatedEvent @event)
 {
     AddedBy            = @event.AddedBy;
     AddedDate          = @event.AddedDate;
     Id                 = @event.AggregateId;
     DepartmentId       = @event.DepartmentId;
     Description        = @event.Description;
     DiscountPercentage = @event.DiscountPercentage;
     FullImageUrl       = @event.FullImageUrl;
     SKU                = @event.SKU;
     SmallImageUrl      = @event.SmallImageUrl;
     Title              = @event.Title;
     TotalRating        = @event.TotalRating;
     UnitPrice          = @event.UnitPrice;
 }
        public async Task Consume(ConsumeContext <IUpdateProductCommand> context)
        {
            try
            {
                var connectionStringSettings = new ConnectionStringSettings();
                var blobStorageSettings      = new BlobStorageSettings();
                _configurationRoot.GetSection("ConnectionStrings").Bind(connectionStringSettings);
                _configurationRoot.GetSection("BlobStorage").Bind(blobStorageSettings);

                var dbContext  = ProductDbContext.GetProductDbContext(connectionStringSettings.DefaultConnection);
                var repository = new RepositoryWrapper(dbContext);

                var product = repository.Product.GetProductById(context.Message.Id);
                if (product != null)
                {
                    //delete existing blob
                    var deleteblob = new PhotoBlob(blobStorageSettings);
                    await deleteblob.DeleteBlob(product.BlobName);

                    //upload photo to blob
                    var repo       = BlobConfigurator.GetMessageDataRepository(blobStorageSettings);
                    var bytesArray = Convert.FromBase64String(context.Message.Photo);
                    var payload    = repo.PutBytes(bytesArray).Result;
                    context.Message.BlobName = payload.Address.AbsolutePath;
                }

                var productService = new ProductCatalogService(repository);
                var result         = await productService.UpdateProduct(context.Message);

                var updatedEvent = new ProductUpdatedEvent(result);
                await context.RespondAsync(updatedEvent);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #11
0
 public Task Handle(ProductUpdatedEvent message, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
        public Task Handle(ProductUpdatedEvent message, CancellationToken cancellationToken)
        {
            // Send some greetings e-mail

            return(Task.CompletedTask);
        }
 public void Handle(ProductUpdatedEvent message)
 {
     // Send some notification e-mail
 }
 protected virtual void OnProductUpdated(Product product, ProductEventArgs e)
 {
     ProductUpdatedEvent?.Invoke(product, e);
 }
 public Task Handle(ProductUpdatedEvent notification, CancellationToken cancellationToken)
 {
     return(Task.CompletedTask);
 }
 public void Handle(ProductUpdatedEvent domainEvent)
 {
     throw new NotImplementedException();
 }