Event raised when a new product is created.
Inheritance: DomainEvent
Example #1
0
        public async Task Consume(ConsumeContext <ICreateProductCommand> 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 productService = new ProductCatalogService(repository);

                var product = repository.Product.GetByCondition(x => x.Code.Equals(context.Message.Code) || x.Name.Equals(context.Message.Name));
                if (product?.Count() == 0)
                {
                    //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;
                }

                //create product
                var result = await productService.CreateProduct(context.Message);

                var createdEvent = new ProductCreatedEvent(result);
                await context.RespondAsync(createdEvent);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #2
0
        public async Task <ProductResponse> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new RequestNullException();
            }

            bool productAlreadyExist = _dataContext.ProductModels.Any(p => p.ProductCode == request.ProductCode);

            if (productAlreadyExist)
            {
                throw new ProductAlreadyExistException(request.ProductCode);
            }

            var productModel = new ProductModel(request.ProductCode);

            await _dataContext.ProductModels.AddAsync(productModel, cancellationToken);

            await _dataContext.SaveChangesAsync(cancellationToken);

            var productCreatedEvent = new ProductCreatedEvent(productModel.Id, productModel.ProductCode);
            await _mediator.Publish(productCreatedEvent, cancellationToken);

            ProductResponse productServiceResponse = productModel.ToProductServiceResponse();

            return(productServiceResponse);
        }
Example #3
0
        static async Task Main(string[] args)
        {
            const string rabbitMqUri = "rabbitmq://localhost";
            const string entityName  = "product-created";
            const string userName    = "******";
            const string password    = "******";

            var bus = Bus.Factory.CreateUsingRabbitMq(factory =>
            {
                factory.Host(rabbitMqUri, configurator =>
                {
                    configurator.Username(userName);
                    configurator.Password(password);
                });
                factory.Message <ProductCreatedEvent>(x => x.SetEntityName(entityName));
            });

            await Task.Run(async() =>
            {
                int i = 1;
                while (true)
                {
                    Console.Write("Press enter button for add product to queue");
                    Console.ReadLine();
                    var message = new ProductCreatedEvent
                    {
                        Id   = i,
                        Name = $"Product-{i}"
                    };
                    i++;
                    await bus.Publish <ProductCreatedEvent>(message);
                    //Console.WriteLine("");
                }
            });
        }
Example #4
0
 private void Apply(ProductCreatedEvent @event)
 {
     _id           = @event.AggregateId;
     _name         = @event.Name;
     _url          = @event.Url;
     _price        = @event.Price;
     _currencyCode = @event.CurrencyCode;
     _available    = @event.Available;
 }
Example #5
0
        public void Handle(CreateProductMessage message)
        {
            Console.WriteLine(string.Format("\nServer received Message {0}.", message.Description));
            var productCreatedEvent = new ProductCreatedEvent()
            {
                Description = message.Description
            };

            Bus.Publish(productCreatedEvent);
        }
Example #6
0
        public async Task Handle(ProductCreateCommand command, CancellationToken cancellationToken)
        {
            var aggregate = new Product();

            var productCreatedEvent =
                new ProductCreatedEvent(command.Id, command.Name, command.Price);

            aggregate.Handle(productCreatedEvent);

            await _repository.SaveAggregateEvent(aggregate, productCreatedEvent, cancellationToken);

            await _mediator.Publish(productCreatedEvent, cancellationToken);
        }
Example #7
0
        public async Task <Guid> CreateNewProduct(string ean, string sku, string name, string url, Currency price, string description, int unitInStock, bool isOnSale, DateTime?onSaleFrom, DateTime?onSaleTo)
        {
            try
            {
                var product = Product.Create(ean, sku, name, url);
                if (price != null)
                {
                    product.SetPrice(price);
                }

                if (!string.IsNullOrEmpty(description))
                {
                    product.ChangeDescription(description);
                }

                if (unitInStock > 0)
                {
                    product.SetUnitInStock(unitInStock);
                }

                if (isOnSale)
                {
                    if (onSaleFrom == null)
                    {
                        product.SetOnSale();
                    }
                    else if (onSaleTo == null)
                    {
                        product.SetOnSale((DateTime)onSaleFrom);
                    }
                    else
                    {
                        product.SetOnSale((DateTime)onSaleFrom, (DateTime)onSaleTo);
                    }
                }

                Repository.Add(product);
                await Repository.SaveChangesAsync();

                var @event = new ProductCreatedEvent(product.Id, product.EanCode, product.Sku, product.Name);
                EventBus.RaiseEvent(@event);

                return(product.Id);
            }
            catch
            {
                throw;
            }
        }
        public void HandleCreatedProductEventOnAgg()
        {
            var          id    = Guid.NewGuid();
            const string name  = "Test Product Name";
            const int    price = 400;

            var productCreatedEvent = new ProductCreatedEvent(id, name, price);

            var agg = new Kanayri.Domain.Product.Product();

            agg.Handle(productCreatedEvent);

            Assert.Equal(id, agg.Id);
            Assert.Equal(name, agg.Name);
            Assert.Equal(price, agg.Price);
        }
        public void HandlePriceChangedEventOnAgg()
        {
            var id = Guid.NewGuid();

            var productCreatedEvent = new ProductCreatedEvent(id, "mock name", 500);

            var agg = new Kanayri.Domain.Product.Product();

            agg.Handle(productCreatedEvent);

            const int newPrice          = 600;
            var       priceChangedEvent = new ProductPriceChangedEvent(id, newPrice);

            agg.Handle(priceChangedEvent);

            Assert.Equal(newPrice, agg.Price);
        }
Example #10
0
        public void ProductCreatedEvent_Ctor_Should_Set_Arguments_Correctly()
        {
            Guid   productId = Guid.NewGuid();
            string ean       = "ean";
            string sku       = "sku";
            string name      = "name";

            var @event = new ProductCreatedEvent(productId, ean, sku, name);

            Assert.Equal(productId, @event.ProductId);
            Assert.Equal(ean, @event.EanCode);
            Assert.Equal(sku, @event.Sku);
            Assert.Equal(name, @event.Name);

            Assert.Equal(productId, @event.AggregateId);
            Assert.Equal(typeof(Catalog.Models.Product), @event.AggregateType);
        }
        public void Serialize_Event_Test()
        {
            var productEvent = new ProductCreatedEvent(
                new Product
                {
                    Id = Guid.NewGuid(),
                    Name = "Product_Name",
                    Model = "Product_Model \t",
                    IsDeleted = false,
                    CreatorUserId = Guid.NewGuid(),
                    CreationTime = DateTime.Now
                }
            );

            var eventData = new DomainEventData<Product>(productEvent);

            var json = JsonSerializationHelper.Serialize(eventData);

            Assert.IsNotNull(json);
            Assert.IsTrue(json.Contains("\"Version\":1"));
        }
        public void Serialize_Event_MakeGenericType_Test()
        {
            var productEvent = new ProductCreatedEvent(
                new Product
                {
                    Id = Guid.NewGuid(),
                    Name = "Product_Name",
                    Model = "Product_Model",
                    IsDeleted = false,
                    CreatorUserId = Guid.NewGuid(),
                    CreationTime = DateTime.Now
                }
            );

            var eventDataType = typeof(DomainEventData<>).MakeGenericType(productEvent.Source.GetType());
            var obj = Activator.CreateInstance(eventDataType, productEvent);

            var json = JsonSerializationHelper.Serialize(obj);

            Assert.IsNotNull(json);
            Assert.IsTrue(json.Contains("\"Version\":1"));
        }
Example #13
0
 private void onProductCreated(ProductCreatedEvent e)
 {
     Id    = e.ProductId;
     _name = e.Name;
 }
Example #14
0
 internal void Apply(ProductCreatedEvent @event)
 {
     Name    = @event.Name;
     Barcode = @event.Barcode;
     Code    = @event.Code;
 }
Example #15
0
 private void OnCreated(ProductCreatedEvent @event)
 {
     this.Id    = @event.Id;
     this.Title = @event.Title;
 }
Example #16
0
	private void OnCreated(ProductCreatedEvent @event)
	{
		this.Id = @event.Id;
		this.Title = @event.Title;
	}
Example #17
0
 private void When(ProductCreatedEvent @event)
 {
     Name = @event.Name;
 }
Example #18
0
 public void Handle(ProductCreatedEvent message)
 {
     AggregateRoot.Name        = message.Name;
     AggregateRoot.ProductType = message.ProductType;
 }