Ejemplo n.º 1
0
    private static async Task DoDatabaseRequestsAsync(IServiceProvider serviceProvider, LoggingLevelSwitch loggingLevelSwitch)
    {
        await using var scope = serviceProvider.CreateAsyncScope();

        var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >();
        var ctx    = scope.ServiceProvider.GetRequiredService <ProductsDbContext>();

        await InsertProductAsync(ctx, new Product(Guid.NewGuid(), ProductName.Create("Apple"), ProductCategory.Fruits, SpecialProductType.Special, Boundary.Create(1, 2)));

        try
        {
            loggingLevelSwitch.MinimumLevel = LogEventLevel.Fatal;
            await InsertProductAsync(ctx, new Product(Guid.NewGuid(), ProductName.Create("Pear"), ProductCategory.Get("Invalid Category"), SpecialProductType.Special, Boundary.Create(1, 2)));

            loggingLevelSwitch.MinimumLevel = LogEventLevel.Information;
        }
        catch (DbUpdateException)
        {
            logger.LogError("Error during persistence of invalid category");
        }

        var products = await ctx.Products.AsNoTracking().Where(p => p.Category == ProductCategory.Fruits).ToListAsync();

        logger.LogInformation("Loaded products: {@Products}", products);
    }
Ejemplo n.º 2
0
        private static void Main(string[] args)
        {
            Console.Write("Digite o nome do seu produto");

            var input = Console.ReadLine();

            var productName = ProductName
                              .Create(input);

            if (productName.IsSuccess)
            {
                var product = new Product(productName.Value);

                var unitOfWork = new SalesUnitOfWork();

                //var repository = new Repository<Product>(unitOfWork);
                var repository = new ProductRepository(unitOfWork);

                repository.Add(product);

                //unitOfWork.Add(product); //commando de insert do sql server

                unitOfWork.SaveChanges(); //Comando de commit do sql server

                Console.WriteLine("Sucesso!");
            }
            else
            {
                Console.WriteLine(productName.Error);
            }

            Console.ReadKey();
        }
Ejemplo n.º 3
0
 public void GivenOrderHasAnItemProductWithQuantity(string product, int quantity)
 {
     AddEvent(new OrderLineCreated(
                  _orderIdentifier,
                  OrderLineIdentifier.Create(1),
                  ProductIdentifier.Parse(product),
                  ProductName.Create("Test"),
                  quantity));
 }
Ejemplo n.º 4
0
 public override Core.OrderManagement.Orders.Events.OrderLineCreated ConvertToIntern(OrderLineCreated e)
 {
     return(new Core.OrderManagement.Orders.Events.OrderLineCreated(
                OrderIdentifier.Parse(e.OrderIdentifier),
                OrderLineIdentifier.Parse(e.OrderLineIdentifier),
                ProductIdentifier.Parse(e.ProductIdentifier),
                ProductName.Create(e.ProductName),
                e.Quantity));
 }
Ejemplo n.º 5
0
        public void Configure(EntityTypeBuilder <Product> builder)
        {
            builder
            .HasKey(k => k.Id);

            builder.Property(p => p.ProductName)
            .HasConversion(p => p.Value,
                           p => ProductName.Create(p).Value)
            .IsRequired()
            .HasMaxLength(80)
            .HasColumnType("varchar");
        }
        public async Task HandleAsync(RegisterProductCommand args)
        {
            var productName = ProductName
                              .Create(args.ProductName);

            if (productName.IsSuccess)
            {
                var product = new Product(productName.Value);

                _repository
                .Add(product);

                await _unitOfWork
                .CommitAsync();
            }
        }
Ejemplo n.º 7
0
        public async Task HandleAsync(EditProductCommand command)
        {
            var product = await _repository
                          .GetAsync(command.Id);

            var productName = ProductName
                              .Create(command.ProductName);

            product
            .Edit(productName.Value);

            _repository
            .Modify(product);

            await _unitOfWork
            .CommitAsync();
        }
Ejemplo n.º 8
0
        public OrderLine CreateOrderLine(ProductIdentifier productIdentifier, int quantity)
        {
            if (Lines.Any(ol => ol.ProductIdentifier == productIdentifier))
            {
                throw new InvalidOperationException($"An orderline with product {productIdentifier} already exists");
            }

            var orderLineIdentifier = OrderLineIdentifier.NextIdentifier(Lines.LastIdentifier);

            ApplyChange(
                new OrderLineCreated(
                    OrderIdentifier,
                    orderLineIdentifier,
                    productIdentifier,
                    ProductName.Create("Unknown"),
                    quantity));

            return(Lines.Get(orderLineIdentifier));
        }
Ejemplo n.º 9
0
        public HttpResponse CreateProduct(ProductDefinition definition)
        {
            Result <ProductName>      productName    = ProductName.Create(definition.Name);
            Result <ManufacturerName> manufacturer   = ManufacturerName.Create(definition.Manufacturer);
            Result <Maybe <Email> >   emailOrNothing = GetImporterEmail(definition);

            return(Result.Combine(productName, manufacturer, emailOrNothing)
                   .OnSuccess(() => new Product
            {
                ProductId = definition.ProductId,
                Category = definition.Category,
                Name = productName.Value,
                Manufacturer = manufacturer.Value,
                ImporterEmail = emailOrNothing.Value,
                Quantity = definition.Quantity
            })
                   .OnSuccess(p => _repository.Add(p))
                   .OnBoth(r => r.IsSuccess ? Commit() : Response.BadRequest(r.Error)));
        }
    public static void Demo(ILogger logger)
    {
        logger.Information("==== Demo for ValueObjectAttribute ====");

        var bread = ProductName.Create("Bread");

        logger.Information("Product name: {Bread}", bread);

        string valueOfTheProductName = bread;

        logger.Information("Implicit conversion of ProductName -> string: {Key}", valueOfTheProductName);

        try
        {
            ProductName.Create("  ");
            logger.Warning("This line won't be reached.");
        }
        catch (ValidationException)
        {
            logger.Information("ValidationException is thrown because a product name cannot be an empty string.");
        }

        var validationResult = ProductName.TryCreate("Milk", out var milk);

        if (validationResult == ValidationResult.Success)
        {
            logger.Information("Product name '{Name}' created with 'TryCreate'.", milk);
        }

        // Thanks to setting "NullInFactoryMethodsYieldsNull = true"
        var nullProduct = ProductName.Create(null);

        logger.Information("Null-Product name: {NullProduct}", nullProduct);

        var nullValidationResult = ProductName.TryCreate(null, out nullProduct);

        if (nullValidationResult == ValidationResult.Success)
        {
            logger.Information("Null-Product name: {NullProduct}", nullProduct);
        }
    }
Ejemplo n.º 11
0
 public override Core.OrderManagement.Products.Events.ProductCreated ConvertToIntern(ProductCreated e)
 {
     return(new Core.OrderManagement.Products.Events.ProductCreated(
                ProductIdentifier.Parse(e.ProductIdentifier),
                ProductName.Create(e.ProductName)));
 }
Ejemplo n.º 12
0
        static async Task Main()
        {
            var eventsConverter = new EventsConverter();

            //var e = new Core.OrderManagement.Orders.Events.OrderCreated(OrderIdentity.New());
            //System.Console.WriteLine(JsonSerializer.Serialize(e, new JsonSerializerOptions { WriteIndented = true }));


            //var a = EventMapping.Convert(e);
            //var json = JsonSerializer.Serialize(a, new JsonSerializerOptions { WriteIndented = true, Converters = { new IdentityJsonConverter() } });

            //System.Console.WriteLine(json);

            //var data2 = JsonSerializer.Deserialize<OrderCreated>(json);
            //var e2 = EventMapping.Convert2(data2);

            //System.Console.WriteLine(JsonSerializer.Serialize(e, e.GetType(), new JsonSerializerOptions { WriteIndented = true }));

            //return;

            var aggregateContext = new AggregateContext();

            IEventStore eventStore        = new EventStoreDb(eventsConverter, new Uri("http://localhost:2113"));
            var         productRepository = new ProductRepository(eventStore, aggregateContext);

            var product1 = Product.Create(aggregateContext, ProductName.Create("Brood"));

            await productRepository.SaveAsync(product1);

            product1.ChangeName(ProductName.Create("Boterham"));
            await productRepository.SaveAsync(product1);



            var productRepository2 = new ProductRepository(eventStore, aggregateContext);

            var product1A = await productRepository2.GetAsync(product1.Identifier);

            //System.Console.WriteLine(JsonSerializer.Serialize(product, new JsonSerializerOptions { WriteIndented = true }));
            //System.Console.WriteLine(JsonSerializer.Serialize(product2, new JsonSerializerOptions { WriteIndented = true }));


            var orderRepository = new OrderRepository(eventStore, aggregateContext);


            var order = Order.Create(
                aggregateContext,
                OrderIdentifier.New(),
                CustomerIdentifier.New());

            var faultyLine = order.CreateOrderLine(ProductIdentifier.New(), 1);

            faultyLine.Remove();

            var prod2 = ProductIdentifier.New();
            var prod3 = ProductIdentifier.New();
            var prod4 = ProductIdentifier.New();


            order.CreateOrderLine(product1, 1);
            order.CreateOrderLine(prod2, 2);
            order.CreateOrderLine(prod3, 1);
            order.CreateOrderLine(prod4, 1);

            var prod3OrderLine = order.Lines.Get(prod3);

            prod3OrderLine.Remove();

            var prod1OrderLine = order.Lines.Get(product1.Identifier);

            prod1OrderLine.AdjustQuantity(3);


            await orderRepository.SaveAsync(order);

            var order2 = await orderRepository.GetAsync(order.OrderIdentifier);


            var product1B = await productRepository2.GetAsync(product1.Identifier);

            product1B.ChangeName(ProductName.Create("Stok brood"));
            await productRepository2.SaveAsync(product1B);
        }