Ejemplo n.º 1
0
 private void When(ProductCreated e)
 {
     Products.Add(new ProductDTO()
     {
         Name = e.Name, Id = e.Id
     });
 }
        public async Task <ActionResult <Product> > Create([FromBody] ProductCreated model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(
                           new
                {
                    Error = new { Message = "Invalid product created." },
                    ModelState.Values
                }
                           ));
            }
            var prod = new Product
            {
                Nombre        = model.Nombre,
                Presentacion  = model.Presentacion,
                Descripcion   = model.Descripcion,
                Precio        = model.Precio,
                FechaCreacion = model.FechaCreacion,
                ImageUrl      = model.ImageUrl,
                Id            = ""
            };

            await _productService.CreateAsync(prod);

            return(CreatedAtRoute("GetProductById", new { id = prod.Id.ToString() }, prod));
        }
Ejemplo n.º 3
0
        /// <summary>
        ///Proceso de creación de un producto, asíncrono.
        /// </summary>
        /// <param name="model">Objeto de tipo producto.</param>
        /// <returns>Retorna el nevo objeto creado con su id</returns>
        public async Task <ProductApiModel> CreateProductAsync([FromBody] ProductCreated model)
        {
            ProductApiModel pro = null;

            response = await client.PostAsJsonAsync($"{_HostProduct}v1/api/product", model);

            var jsonSerialize = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                string mensaje = JsonConvert.SerializeObject(jsonSerialize);
                throw new HttpException(new List <string> {
                    mensaje
                }, response.StatusCode);
            }

            // return URI of the created resource.
            pro = JsonConvert
                  .DeserializeObject <ProductApiModel>(jsonSerialize.ToString()
                                                       , new JsonSerializerSettings()
            {
                MissingMemberHandling =
                    MissingMemberHandling.Ignore
            });

            pro.CheckIsNotNull();

            return(pro);
        }
Ejemplo n.º 4
0
 void Apply(ProductCreated e)
 {
     Id           = e.Id.ToString();
     _price       = e.Price;
     _quantity    = e.Quantity;
     _productCode = e.ProductCode;
 }
Ejemplo n.º 5
0
 private void Apply(ProductCreated e)
 {
     Id          = e.Id;
     Name        = e.Name;
     Description = e.Description;
     Price       = e.Price;
 }
Ejemplo n.º 6
0
 private void Apply(ProductCreated e)
 {
     Id          = e.Id;
     Code        = e.Code;
     Name        = e.Name;
     Description = e.Description;
 }
Ejemplo n.º 7
0
        private void HandleProductCreated(ProductCreated ev)
        {
            var product = new Product(ev.Name);

            products.Add(product);
            ev.EntityId = product.Id;
        }
Ejemplo n.º 8
0
 private void Apply(ProductCreated @event)
 {
     Id       = @event.ProductId;
     Brand    = new BrandRef(@event.BrandId, "");
     Category = new CategoryRef(@event.CategoryId, "");
     Code     = @event.ProductCode;
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            var productService = new ProductService(new ProductRepository());

            var productEvent = new ProductCreated
            {
                Message           = "Some message",
                MessageAttributes = new Dictionary <string, MessageAttribute>()
                {
                    { "ID", new MessageAttribute {
                          DataType = "number", StringValue = "3"
                      } },
                    { "Name", new MessageAttribute {
                          DataType = "string", StringValue = "Polestar 3"
                      } }
                }
            };


            productService.HandleSaveProductEvent(productEvent);

            var products = productService.GetAllProducts();

            foreach (var p in products)
            {
                Console.WriteLine(p.Id);
                Console.WriteLine(p.Name);
            }
        }
Ejemplo n.º 10
0
 private void OnProductCreated(ProductCreated @event)
 {
     if (@event == null)
     {
         throw new ArgumentNullException(nameof(@event));
     }
     Title = @event.Title;
 }
Ejemplo n.º 11
0
 private void Apply(ProductCreated @event)
 {
     Id          = @event.AggregateRootId;
     Name        = @event.Name;
     Description = @event.Description;
     Price       = @event.Price;
     Status      = @event.Status;
 }
Ejemplo n.º 12
0
 public void CreateProduct(CreateProductCommand cmd)
 {
     if (!_products.Any(x => x.Id == cmd.Id || x.Name.Equals(cmd.Name)))
     {
         var @event = new ProductCreated(cmd.Id, cmd.Name, cmd.Description);
         Apply(@event);
         Dispatch(@event);
     }
 }
Ejemplo n.º 13
0
        public ActionResult SendObj()
        {
            var @event = new ProductCreated {
                Guid = Guid.NewGuid(), Id = 5, Name = "Twarożek"
            };

            _eventBusPublisher.Publish(@event, "ProductCreated");
            return(Ok());
        }
Ejemplo n.º 14
0
 private void When(ProductCreated @event)
 {
     this.Id             = @event.AggregateId;
     this.Name           = @event.Name;
     this.Description    = @event.Description;
     this.Qty            = @event.TotalSalesQty;
     this.CategoryId     = @event.CategoryId;
     this.ThumbnailPath  = @event.ThumbnailPath;
     this.SlidingImgPath = @event.SlidingImgPath?.ToList() ?? new List <ImageInfo>();
 }
Ejemplo n.º 15
0
 public void Handle(ProductCreated @event)
 {
     _auditRepository.Add(new Audit()
     {
         Id          = @event.EventId.ToString(),
         Name        = @event.GetType().ToString(),
         Details     = @event.Name,
         CreatedTime = @event.EventPublished.UtcDateTime
     });
 }
Ejemplo n.º 16
0
        public XNodeEventService(ILogger <SystemService> logger,
                                 string agentId,
                                 XNodeConfiguration nodeConfig,
                                 DataStorageConfiguration dataStorageConfig,
                                 AgentConfiguration agentConfiguration,
                                 IXNodeConnectionRepository xNodeConnectionRepository,
                                 TenantIOService tenantIOService,
                                 ProducerIOService producerIOService,
                                 ConsumerIOService consumerIOService,
                                 MessageIOService messageIOService)
        {
            this.logger = logger;
            this.xNodeConnectionRepository = xNodeConnectionRepository;
            this.tenantIOService           = tenantIOService;
            this.producerIOService         = producerIOService;
            this.consumerIOService         = consumerIOService;
            this.messageIOService          = messageIOService;
            this.agentId    = agentId;
            this.nodeConfig = nodeConfig;

            var provider = new XNodeConnectionProvider(nodeConfig, dataStorageConfig, agentConfiguration, agentId);

            _connection = provider.GetHubConnection();

            _connection.On <AgentConnectedArgs>("StorageConnected", connectedArgs => StorageConnected?.Invoke(connectedArgs));
            _connection.On <AgentDisconnectedArgs>("StorageDisconnected", disconnectedArgs => StorageDisconnected?.Invoke(disconnectedArgs));

            _connection.On <TenantCreatedArgs>("TenantCreated", tenantCreated => TenantCreated?.Invoke(tenantCreated));
            _connection.On <TenantUpdatedArgs>("TenantUpdated", tenantUpdated => TenantUpdated?.Invoke(tenantUpdated));

            _connection.On <ProductCreatedArgs>("ProductCreated", productCreated => ProductCreated?.Invoke(productCreated));
            _connection.On <ProductUpdatedArgs>("ProductUpdated", productUpdated => ProductUpdated?.Invoke(productUpdated));

            _connection.On <ComponentCreatedArgs>("ComponentCreated", componentCreated => ComponentCreated?.Invoke(componentCreated));
            _connection.On <ComponentUpdatedArgs>("ComponentUpdated", componentUpdated => ComponentUpdated?.Invoke(componentUpdated));

            _connection.On <TopicCreatedArgs>("TopicCreated", topicCreated => TopicCreated?.Invoke(topicCreated));
            _connection.On <TopicUpdatedArgs>("TopicUpdated", topicUpdated => TopicUpdated?.Invoke(topicUpdated));

            _connection.On <ProducerConnectedArgs>("ProducerConnected", producerConnected => ProducerConnected?.Invoke(producerConnected));
            _connection.On <ProducerDisconnectedArgs>("ProducerDisconnected", producerDisconnected => ProducerDisconnected?.Invoke(producerDisconnected));

            _connection.On <ConsumerConnectedArgs>("ConsumerConnected", consumerConnected => ConsumerConnected?.Invoke(consumerConnected));
            _connection.On <ConsumerDisconnectedArgs>("ConsumerDisconnected", consumerDisconnected => ConsumerDisconnected?.Invoke(consumerDisconnected));
            _connection.On <ConsumerConnectedArgs>("ConsumerUnacknowledgedMessagesRequested", consumerConnected => ConsumerUnacknowledgedMessagesRequested?.Invoke(consumerConnected));
            _connection.On <MessageAcknowledgedArgs>("MessageAcknowledged", messageAcked => MessageAcknowledged?.Invoke(messageAcked));

            _connection.On <MessageStoredArgs>("MessageStored", msgStored => MessageStored?.Invoke(msgStored));

            InitializeEventHandlers();

            ConnectAsync();

            xNodeConnectionRepository.AddService(nodeConfig.ServiceUrl, agentId, this);
        }
Ejemplo n.º 17
0
 void OnProductCreated(ProductCreated productCreated)
 {
     lock (lock_)
     {
         if (CheckMessageSanity(productCreated))
         {
             var product = productCreated.Product;
             data[product.Id] = product;
         }
     }
 }
Ejemplo n.º 18
0
        static void proccessProductCreated(ProductCreated newProduct)
        {
            var pli = MapProductLineItem(newProduct);

            pli.CategoryName = newProduct.CategoryName;
            using (var redisClient = new RedisClient())
                using (var cacheProduct = redisClient.As <ProductLineItem>())
                {
                    cacheProduct.Store(pli);
                }
        }
Ejemplo n.º 19
0
        public void Handle(ProductCreated @event)
        {
            Product product = new Product()
            {
                Id    = @event.Id,
                Name  = @event.Name,
                Price = @event.Price
            };

            _orderRepository.SaveProduct(product);
        }
Ejemplo n.º 20
0
        private void Handle(ProductCreated evt)
        {
            var product = new Product()
            {
                Id    = evt.Id,
                Name  = evt.Name,
                Price = evt.Price
            };

            _indexer.Index(product);
            _graphIndexer.AddProduct(product);
        }
 private void OnProductCreated(ProductCreated evt)
 {
     _ctx.Products.Add(new Product
     {
         Id              = evt.AggregateId,
         Name            = evt.Name,
         Price           = evt.Price,
         Quantity        = 0,
         Reserved        = 0,
         LastEventNumber = evt.Metadata.EventNumber
     });
     _ctx.SaveChanges();
 }
Ejemplo n.º 22
0
        public async Task <IActionResult> CreateProduct([FromBody] ProductCreated request)
        {
            var jsonRequest = JsonSerializer.Serialize(request, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            this._logger.LogInformation($"[{nameof(PublisherController)}] - Send to [{nameof(DaprPublisher)}]: {jsonRequest}");

            await this._daprPublisher.Publish(request);

            return(Ok());
        }
Ejemplo n.º 23
0
        public void Product_Should_Be_Created()
        {
            var productId = Guid.NewGuid();
            var name      = Random <string>();

            var @event = new ProductCreated(productId, name);

            new ScenarioFor <Product>(
                () => Product.Create(productId, name)
                )
            .When(product => { })
            .ThenAssert(@event);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> CreateProduct([FromBody] CreateProductRequest request)
        {
            var productCreated = new ProductCreated
            {
                Id    = Guid.NewGuid(),
                Name  = request.Name,
                price = request.price
            };

            await _messagePublisher.Publish(productCreated);

            return(Ok());
        }
Ejemplo n.º 25
0
        /*private void Handle(OrderCreated evt)
         * {
         *  var existinBasket = _indexer.Get<Basket>(evt.BasketId);
         *  existinBasket.BasketState = BasketState.Paid;
         *  _indexer.Index(existinBasket);
         *
         *  _graphClient.Cypher
         *      .Match("(customer:Customer)-[:HAS_BASKET]->(basket:Basket)-[]->(product:Product)")
         *      .Where((Basket basket) => basket.Id == evt.BasketId)
         *      .Create("customer-[:BOUGHT]->product")
         *      .ExecuteWithoutResults();
         * }
         *
         * private void Handle(BasketCheckedOut evt)
         * {
         *  var basket = _indexer.Get<Basket>(evt.Id);
         *  basket.BasketState = BasketState.CheckedOut;
         *  _indexer.Index(basket);
         * }
         *
         * private void Handle(CustomerIsCheckingOutBasket evt)
         * {
         *  var basket = _indexer.Get<Basket>(evt.Id);
         *  basket.BasketState = BasketState.CheckingOut;
         *  _indexer.Index(basket);
         * }*/

        /*private void Handle(ItemAdded evt)
         * {
         *  var existingBasket = _indexer.Get<Basket>(evt.Id);
         *  var orderLines = existingBasket.OrderLines;
         *  if (orderLines == null || orderLines.Length == 0)
         *  {
         *      existingBasket.OrderLines = new[] { evt.OrderLine };
         *  }
         *  else
         *  {
         *      var orderLineList = orderLines.ToList();
         *      orderLineList.Add(evt.OrderLine);
         *      existingBasket.OrderLines = orderLineList.ToArray();
         *  }
         *
         *  _indexer.Index(existingBasket);
         *
         *  _graphClient.Cypher
         *      .Match("(basket:Basket)", "(product:Product)")
         *      .Where((Basket basket) => basket.Id == evt.Id)
         *      .AndWhere((Product product) => product.Id == evt.OrderLine.ProductId)
         *      .Create("basket-[:HAS_ORDERLINE {orderLine}]->product")
         *      .WithParam("orderLine", evt.OrderLine)
         *      .ExecuteWithoutResults();
         * }*/

        /*private void Handle(BasketCreated evt)
         * {
         *  var newBasket = new Basket()
         *  {
         *      Id = evt.Id,
         *      OrderLines = null,
         *      BasketState = BasketState.Shopping
         *  };
         *  _indexer.Index(newBasket);
         *  _graphClient.Cypher
         *      .Create("(basket:Basket {newBasket})")
         *      .WithParam("newBasket", newBasket)
         *      .ExecuteWithoutResults();
         *
         *  _graphClient.Cypher
         *      .Match("(customer:Customer)", "(basket:Basket)")
         *      .Where((Customer customer) => customer.Id == evt.CustomerId)
         *      .AndWhere((Basket basket) => basket.Id == evt.Id)
         *      .Create("customer-[:HAS_BASKET]->basket")
         *      .ExecuteWithoutResults();
         * }*/

        private void Handle(ProductCreated evt)
        {
            var product = new Product()
            {
                Id   = evt.Id,
                Name = evt.Name
            };

            _indexer.Index(product);
            _graphClient.Cypher
            .Create("(product:Product {newProduct})")
            .WithParam("newProduct", product)
            .ExecuteWithoutResults();
        }
Ejemplo n.º 26
0
        public async Task <ProductVM> Handle(AddProductCmd request, CancellationToken cancellationToken)
        {
            ProductId  productId  = this.repository.GenerateProductId();
            CategoryId categoryId = this.categoryIdTranslator.Translate(request.CategoryId);

            Product product = Product.CreateProduct(productId, request.Name,
                                                    request.Description, request.TotalSalesQty, categoryId,
                                                    request.ThumbnailPath, request.SlidingImgPath);
            ProductCreated @event = product.DomainEvents.First(evt => evt is ProductCreated) as ProductCreated;

            this.repository.Save(product, @event);

            ProductVM rm = this.productRMTranslator.Translate(product);

            return(await Task.FromResult(rm));
        }
Ejemplo n.º 27
0
        public async Task <string> Create(string title, int amount)
        {
            var product = new Product
            {
                Id     = Guid.NewGuid().ToString(),
                Title  = title,
                Amount = amount,
            };
            var @event = await CreateEvent(
                product.Id, EventTypes.ProductCreated, product);

            var productCreated = ProductCreated.Create(@event, product);

            messageQueue.Publish(productCreated);
            return(product.Id);
        }
        public void When_CreateProduct_ProductCreated()
        {
            var command = new CreateProduct(id, "Test Product", 2);

            command.Metadata.CausationId   = command.Metadata.CommandId;
            command.Metadata.CorrelationId = causationAndCorrelationId;

            When(command);

            var expectedEvent = new ProductCreated(id, "Test Product", 2);

            expectedEvent.Metadata.CausationId   = command.Metadata.CommandId;
            expectedEvent.Metadata.CorrelationId = causationAndCorrelationId;
            expectedEvent.Metadata.ProcessId     = command.Metadata.ProcessId;

            Then(expectedEvent);
        }
        public async Task Publish(ProductCreated request)
        {
            var jsonRequest = JsonSerializer.Serialize(request, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            var requestStringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

            this._logger.LogInformation($"[{nameof(DaprPublisher)}] - Preparing publish: {jsonRequest}");

            this._logger.LogInformation($"[{nameof(DaprPublisher)}] - Publish Address: {this._httpClient.BaseAddress}");

            var response = await this._httpClient.PostAsync("/v1.0/publish/ProductCreated", requestStringContent);

            response.EnsureSuccessStatusCode();
        }
Ejemplo n.º 30
0
        public void Aggregate_Should_Be_Created_And_Publish_ProductCreated_Event()
        {
            var productId   = Random <Guid>();
            var brandId     = Random <int>();
            var productCode = Random <string>();
            var categoryId  = Random <int>();

            var productCreated = new ProductCreated(
                productId,
                productCode,
                brandId, categoryId);

            ScenarioFor(
                () => Product.Create(productId, categoryId, brandId, productCode)
                )
            .When(product => { })
            .Then(productCreated);
        }
Ejemplo n.º 31
0
 private void Handle(ProductCreated evt)
 {
     var product = new Product()
     {
         Id = evt.Id,
         Name = evt.Name,
         Price = evt.Price
     };
     _indexer.Index(product);
     _graphClient.Cypher
         .Create("(product:Product {newProduct})")
         .WithParam("newProduct", product)
         .ExecuteWithoutResults();
 }
Ejemplo n.º 32
0
 private void Apply(ProductCreated obj)
 {
     Id = obj.Id;
     Name = obj.Name;
     Price = obj.Price;
 }
 public void Handle(ProductCreated evnt)
 {
     _connection.Insert(evnt, "eventsourcing_sample_product", _transaction);
 }
 protected virtual void Handle(ProductCreated evnt)
 {
     _entityManager.BuildAndSave<ProductEntity>(evnt);
 }