예제 #1
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var modelName = bindingContext.ModelName;

            var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(Task.CompletedTask);
            }

            var value = valueProviderResult.FirstValue;

            // not good for prod, but good enough for a demo 🙂
            if (bindingContext.ModelType == typeof(CartId) && CartId.TryParse(value, out var cartId))
            {
                bindingContext.Result = ModelBindingResult.Success(cartId);
            }
            else if (bindingContext.ModelType == typeof(ItemId) && ItemId.TryParse(value, out var itemId))
            {
                bindingContext.Result = ModelBindingResult.Success(itemId);
            }
            else
            {
                bindingContext.Result = ModelBindingResult.Failed();
            }

            return(Task.CompletedTask);
        }
예제 #2
0
        public void AddToCart(Medication album, int quantity)
        {
            var cartAlbum = _applicationDbContext.DrugCart.SingleOrDefault(s => s.Drug.DrugId == album.DrugId && s.Cart.CartId == CartId);// razlika
            var cart      = _applicationDbContext.Cart.FirstOrDefault(t => t.CartId == CartId);

            System.Diagnostics.Debug.WriteLine("kart" + CartId.ToString());
            if (cartAlbum == null)
            {
                cartAlbum = new DrugCart
                {
                    Cart     = this,
                    Drug     = album,
                    Quantity = 1
                };
                _applicationDbContext.DrugCart.Add(cartAlbum);
                System.Diagnostics.Debug.WriteLine("CARTALBUM" + cartAlbum.DrugCartId.ToString());
            }
            else
            {
                cartAlbum.Quantity++;
            }
            _applicationDbContext.SaveChanges();
            foreach (DrugCart dc in _applicationDbContext.DrugCart.ToList())
            {
                System.Diagnostics.Debug.WriteLine("DCS" + dc.DrugCartId.ToString());
            }
        }
예제 #3
0
        public CartProxy Find(CartId id)
        {
            List<Parameter> parameterList = new List<Parameter>();

            string where = "where" + Environment.NewLine ;
            where += _indent + "Cart.CustomerId = @customerId";

            parameterList.Add(new Parameter("customerId", id.CustomerId));

            TextBuilder tb = new TextBuilder(_templateSql, new { where = where });

            string sql = tb.Generate();

            DagentDatabase db = new DagentDatabase(_connection);

            CartProxy cart = db.Query<CartProxy>(sql, parameterList.ToArray())
                .Unique("CustomerId")
                .Create(row => new CartProxy(row.Get<int>("CustomerId")))
                .Each((model, row) =>
                {
                    row.Map(model, x => x.CartItemList, "CartItemNo")
                        .Create(() => new CartItemEntity(row.Get<int>("CustomerId"), row.Get<int>("CartItemNo")))
                        .Do();
                })
                .Single();

            return cart;
        }
예제 #4
0
        public async Task CreateAsync(string customerId)
        {
            var cart = new Cart(CartId.NewCartId(), new CustomerId(customerId));

            subscriber.Subscribe <CartCreatedEvent>(async @event => await HandleAsync(cartCreatedEventHandlers, @event));
            await cartRepository.SaveAsync(cart);
        }
 public IActionResult AddItemToCart(
     [FromRoute] CartId cartId,
     AddItemToCartModel addItemToCart,
     [FromServices] IRequestHandler <AddItemToCartRequest, Result <Unit> > handler)
 => handler
 .Handle(new AddItemToCartRequest(cartId, addItemToCart.ItemId, addItemToCart.Quantity))
 .ToActionResult();
        public async Task DeleteProductFromCart()
        {
            var services = new ServiceCollection();

            services.AddTransient <IProductRepository, FakeProductRepository>();

            using var resolver = EventFlowOptions.New
                                 .UseServiceCollection(services)
                                 .AddDefaults(typeof(CartContext).Assembly)
                                 .UseEntityFrameworkEventStore <CartContext>()
                                 .ConfigureEntityFramework(EntityFrameworkConfiguration.New)
                                 .AddDbContextProvider <CartContext, MySqlCartContextProvider>()
                                 .AddEvents(typeof(ProductAddedEvent), typeof(ProductRemovedEvent))
                                 .AddCommands(typeof(AddProductCommand), typeof(RemoveProductCommand))
                                 .AddCommandHandlers(typeof(AddProductCommandHandler), typeof(RemoveProductCommandHandler))
                                 .CreateResolver();

            var commandBus     = resolver.Resolve <ICommandBus>();
            var aggregateStore = resolver.Resolve <IAggregateStore>();

            CartId    cartId    = CartId.NewCartId();
            ProductId productId = new ProductId(Guid.Empty);

            await commandBus.PublishAsync(new AddProductCommand(cartId, productId), CancellationToken.None);

            var cart = await aggregateStore.LoadAsync <Cart, CartId>(cartId, CancellationToken.None);

            Assert.AreEqual(1, cart.Products.Count);

            await commandBus.PublishAsync(new RemoveProductCommand(cartId, productId), CancellationToken.None);

            cart = await aggregateStore.LoadAsync <Cart, CartId>(cartId, CancellationToken.None);

            Assert.AreEqual(0, cart.Products.Count);
        }
예제 #7
0
        //
        // GET: /ShoppingCart/AddToCart/5

        public async Task <ActionResult> AddToCart(int id)
        {
            // Retrieve the product from the database
            var addedProduct = db.Products
                               .Single(product => product.ProductId == id);

            // Start timer for save process telemetry
            var startTime = DateTime.Now;

            // Add it to the shopping cart
            var cart = ShoppingCart.GetCart(db, CartId.GetCartId(HttpContext));

            cart.AddToCart(addedProduct);

            await db.SaveChangesAsync(CancellationToken.None);

            // Trace add process
            var measurements = new Dictionary <string, double>()
            {
                { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
            };

            telemetry.TrackEvent("Cart/Server/Add", null, measurements);

            // Go back to the main store page for more shopping
            return(RedirectToAction("Index"));
        }
예제 #8
0
        public async Task <ActionResult> AddressAndPayment(Order order)
        {
            var formCollection = Request.Form;

            try
            {
                if (string.Equals(formCollection.GetValues("PromoCode").FirstOrDefault(), PromoCode,
                                  StringComparison.OrdinalIgnoreCase) == false)
                {
                    return(View(order));
                }
                else
                {
                    order.Username  = User.Identity.GetUserName();
                    order.OrderDate = DateTime.Now;

                    //Add the Order
                    db.Orders.Add(order);

                    //Process the order
                    var cart = ShoppingCart.GetCart(db, CartId.GetCartId(HttpContext));
                    cart.CreateOrder(order);

                    // Save all changes
                    await db.SaveChangesAsync(CancellationToken.None);

                    return(RedirectToAction("Complete", new { id = order.OrderId }));
                }
            }
            catch
            {
                //Invalid - redisplay with errors
                return(View(order));
            }
        }
예제 #9
0
        //
        // GET: /ShoppingCart/

        public ActionResult Index()
        {
            var cart       = ShoppingCart.GetCart(db, CartId.GetCartId(HttpContext));
            var items      = cart.GetCartItems();
            var itemsCount = items.Sum(x => x.Count);
            var subTotal   = items.Sum(x => x.Count * x.Product.Price);
            var shipping   = itemsCount * (decimal)5.00;
            var tax        = (subTotal + shipping) * (decimal)0.05;
            var total      = subTotal + shipping + tax;

            var costSummary = new OrderCostSummary
            {
                CartSubTotal = subTotal.ToString("C"),
                CartShipping = shipping.ToString("C"),
                CartTax      = tax.ToString("C"),
                CartTotal    = total.ToString("C")
            };


            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModel
            {
                CartItems        = items,
                CartCount        = itemsCount,
                OrderCostSummary = costSummary
            };


            // Track cart review event with measurements
            telemetry.TrackTrace("Cart/Server/Index");

            // Return the view
            return(View(viewModel));
        }
예제 #10
0
        public async Task AddProductToCart()
        {
            var rmqUri = new Uri("amqp://*****:*****@localhost:5672/vhost");

            var services = new ServiceCollection();

            services.AddTransient <IProductRepository, FakeProductRepository>();
            using var resolver = EventFlowOptions.New
                                 .UseServiceCollection(services)
                                 .AddDefaults(typeof(CartContext).Assembly)
                                 .UseEntityFrameworkEventStore <CartContext>()
                                 .ConfigureEntityFramework(EntityFrameworkConfiguration.New)
                                 .AddDbContextProvider <CartContext, MySqlCartContextProvider>()
                                 .AddEvents(typeof(ProductAddedEvent))
                                 .AddCommands(typeof(AddProductCommand))
                                 .AddCommandHandlers(typeof(AddProductCommandHandler))
                                 .PublishToRabbitMq(RabbitMqConfiguration.With(rmqUri))
                                 .CreateResolver();

            var commandBus     = resolver.Resolve <ICommandBus>();
            var aggregateStore = resolver.Resolve <IAggregateStore>();

            CartId cartId = CartId.NewCartId();
            await commandBus.PublishAsync(
                new AddProductCommand(cartId, new ProductId(Guid.Empty)),
                CancellationToken.None);

            Cart cart = await aggregateStore.LoadAsync <Cart, CartId>(cartId, CancellationToken.None);

            Assert.AreEqual(1, cart.Products.Count);
        }
예제 #11
0
        private Cart(CartId cartId, IReadOnlyCollection <CartItem> cartItems)
        {
            Require.NotNull(cartId, nameof(cartId));
            Require.NotNull(cartItems, nameof(cartItems));

            Id     = cartId;
            _items = cartItems.ToDictionary(i => i.ItemId, i => i);
        }
        public override int GetHashCode()
        {
            int hashCode = -2134810397;

            hashCode = hashCode * -1521134295 + CartId.GetHashCode();
            hashCode = hashCode * -1521134295 + ProductId.GetHashCode();
            hashCode = hashCode * -1521134295 + Quantity.GetHashCode();
            return(hashCode);
        }
예제 #13
0
        public void Setup()
        {
            _cartId = new CartId($"cart-{Guid.NewGuid()}");
            _cart   = new Cart(_cartId);

            ProductId productId = new ProductId(Guid.NewGuid());

            _product = new Product(productId, "TestProduct", 50);
        }
예제 #14
0
        public void NoDiscount()
        {
            var cartId  = new CartId("some-normal-cart");
            var storage = new SpyStorage();

            App.ApplyDiscount(cartId, storage);

            Assert.Null(storage.Saved);
        }
예제 #15
0
        public void MissingCart()
        {
            var cartId  = new CartId("missing-cart");
            var storage = new SpyStorage();

            App.ApplyDiscount(cartId, storage);

            Assert.Null(storage.Saved);
        }
 public ActionResult <CartModel> Get(
     [FromRoute] CartId cartId,
     [FromServices] IRequestHandler <GetCartRequest, Either <Error, GetCartResponse> > handler)
 => handler
 .Handle(new GetCartRequest(cartId))
 .ToActionResult(response => new CartModel
                 (
                     response.CartId,
                     response.Items.Select(i => new CartItemModel(i.ItemId, i.Quantity))
                 ));
예제 #17
0
        public Cart Please()
        {
            Cart cart = new Cart(CartId.NewCartId());

            foreach (var product in _products)
            {
                cart.Apply(new ProductAddedEvent(product));
            }

            return(cart);
        }
예제 #18
0
        public void HappyPath()
        {
            var cartId  = new CartId("some-gold-cart");
            var storage = new SpyStorage();

            App.ApplyDiscount(cartId, storage);

            var expected = new Cart(new CartId("some-gold-cart"), new CustomerId("gold-customer"), new Amount(50));

            Assert.Equal(expected, storage.Saved);
        }
 static Cart LoadCart(CartId id)
 {
     if (id.Value.Contains("gold"))
     {
         return(new Cart(id, new CustomerId("gold-customer"), new Amount(100)));
     }
     if (id.Value.Contains("normal"))
     {
         return(new Cart(id, new CustomerId("normal-customer"), new Amount(100)));
     }
     return(Cart.MissingCart);
 }
예제 #20
0
        public async Task <Cart> LoadAsync(CartId cartId)
        {
            using (var sqlConnection = new SqlConnection(connectionString))
            {
                await sqlConnection.OpenAsync();

                var eventRows = await sqlConnection.QueryAsync(
                    "select event_type, payload from events where aggregate_id = @AggregareId order by version ASC ",
                    new { AggregareId = cartId.Id });

                IEnumerable <DomainEvent <CartId> > events = GetEventsFrom(eventRows);
                return(Cart.FromEvents(events));
            }
        }
예제 #21
0
        public async Task <ActionResult> RemoveFromCart([FromUri] int id)
        {
            // Start timer for save process telemetry
            var startTime = DateTime.Now;

            // Retrieve the current user's shopping cart
            var cart = ShoppingCart.GetCart(db, CartId.GetCartId(HttpContext));

            // Get the name of the product to display confirmation
            var    cartItem    = db.CartItems.Include("Product").Single(item => item.CartItemId == id);
            string productName = cartItem.Product.Title;

            // Remove from cart
            int itemCount = cart.RemoveFromCart(id);

            await db.SaveChangesAsync(CancellationToken.None);

            string removed = (itemCount > 0) ? " 1 copy of " : string.Empty;

            // Trace remove process
            var measurements = new Dictionary <string, double>()
            {
                { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
            };

            telemetry.TrackEvent("Cart/Server/Remove", null, measurements);

            // Display the confirmation message
            var items      = cart.GetCartItems();
            var itemsCount = items.Sum(x => x.Count);
            var subTotal   = items.Sum(x => x.Count * x.Product.Price);
            var shipping   = itemsCount * (decimal)5.00;
            var tax        = (subTotal + shipping) * (decimal)0.05;
            var total      = subTotal + shipping + tax;

            var results = new ShoppingCartRemoveViewModel
            {
                Message = removed + productName +
                          " has been removed from your shopping cart.",
                CartSubTotal = subTotal.ToString("C"),
                CartShipping = shipping.ToString("C"),
                CartTax      = tax.ToString("C"),
                CartTotal    = total.ToString("C"),
                CartCount    = itemsCount,
                ItemCount    = itemCount,
                DeleteId     = id
            };

            return(Json(results));
        }
    public static Cart HasCartInitializedEventWith(
        this Cart cart,
        Guid id,
        Guid clientId)
    {
        var @event = cart.PublishedEvent <CartInitialized>();

        @event.Should().NotBeNull();
        @event.Should().BeOfType <CartInitialized>();
        @event !.CartId.Should().Be(id);
        @event.ClientId.Should().Be(clientId);
        @event.CartStatus.Should().Be(CartStatus.Pending);

        return(cart);
    }
        public static void ApplyDiscount(CartId cartId, IStorage <Cart> storage)
        {
            var cart = LoadCart(cartId);

            if (cart != Cart.MissingCart)
            {
                var rule = LookupDiscountRule(cart.CustomerId);
                if (rule != DiscountRule.NoDiscount)
                {
                    var discount    = rule.Compute(cart);
                    var updatedCart = UpdateAmount(cart, discount);
                    Save(updatedCart, storage);
                }
            }
        }
예제 #24
0
        public IHttpActionResult New()
        {
            try
            {
                var cartId  = new CartId(Guid.NewGuid());
                var newCart = new Cart(cartId);
                newCart.Publish(_eventStream);

                return(Created(new Uri(Request.RequestUri, cartId.Value.ToString()), "New cart created"));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
    public void ForTentativeCart_ShouldSucceed()
    {
        // Given
        var cart = CartBuilder
                   .Create()
                   .Initialized()
                   .Build();

        // When
        cart.Confirm();

        // Then
        cart.Status.Should().Be(CartStatus.Confirmed);
        cart.Version.Should().Be(2);

        var @event = cart.PublishedEvent <CartConfirmed>();

        @event.Should().NotBeNull();
        @event.Should().BeOfType <CartConfirmed>();
        @event !.CartId.Should().Be(cart.Id);
    }
예제 #26
0
        public static ShoppingCart GetCart(IServiceProvider services)
        {
            Guid     CartId;
            ISession session   = services.GetRequiredService <IHttpContextAccessor>()?.HttpContext.Session;
            var      dbContext = services.GetService <AppDbContext>();

            //var cartIdFromSession = session.GetString("CartId");
            Guid cartIdFromSession;

            if (!string.IsNullOrEmpty(session.GetString("CartId")) && Guid.TryParse(session.GetString("CartId"), out cartIdFromSession))
            {
                CartId = cartIdFromSession;
            }
            else
            {
                CartId = Guid.NewGuid();
            }
            session.SetString("CartId", CartId.ToString());
            return(new ShoppingCart(dbContext)
            {
                ShoppingCartId = CartId
            });
        }
 public AddItemToCartRequest(CartId cartId, ItemId itemId, int quantity)
 {
     CartId   = cartId;
     ItemId   = itemId;
     Quantity = quantity;
 }
 public override string ToString()
 {
     return($"{{{nameof(CartId)}={CartId.ToString()}, {nameof(ProductId)}={ProductId.ToString()}, {nameof(Quantity)}={Quantity.ToString()}}}");
 }
 public IActionResult RemoveItemFromCart([FromRoute] CartId cartId, [FromRoute] ItemId itemId)
 => throw new NotImplementedException();
 public ActionResult <CartModel> Get([FromRoute] CartId cartId)
 => throw new NotImplementedException();
 public IActionResult UpdateItemInCart([FromRoute] CartId cartId, [FromRoute] ItemId itemId, UpdateItemInCart updateItemInCart)
 => throw new NotImplementedException();