示例#1
0
        static void Main(string[] args)
        {
            Console.WriteLine("Shopping Cart coding test by Scott K. Fraley");
            Console.WriteLine();
            Console.WriteLine("OUTPUT:");

            // Set the tax rate to be used
            TaxRate oTaxRate = new TaxRate(10.0);

            // instantiate the repository (which contains the data, and is
            // 'built' during construction.)
            ShoppingCartRepository repository =
                new ShoppingCartRepository(oTaxRate);

            // Since the calculations take place as the Shopping Carts are
            // created, all we need to do now is print the receipts!
            foreach (ShoppingCart shoppingCart in repository.GetAll())
            {
                shoppingCart.PrintReceipt();
            }

            Console.WriteLine();
            Console.Write("Press any key to continue (or exit the Cmd window in this case)...");
            Console.ReadLine();
        }
        public void TestMethod1()
        {
            //Arrange
            var testRepo = new ShoppingCartRepository(mockContext.Object);
            var testId = 1; //Matches the id found in testShoppingCartProduct

            //Act
            var result = testRepo.FindShoppingCartByUserId(testId);

            //Assert
            //Assert.AreEqual("Product Two", result.FirstOrDefault().Name);
        }
        public async void CartItemUpdatedEventRaised_WhenProductRemoved()
        {
            var shoppingCartItemUpdatedRaised = false;
            var shoppingCartService = new MockShoppingCartService();
            shoppingCartService.RemoveProductFromShoppingCartAsyncDelegate =
                (s, s1) => Task.FromResult(string.Empty);
            var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();
            shoppingCartItemUpdatedEvent.Subscribe((_) =>
            {
                shoppingCartItemUpdatedRaised = true;
            });
            var eventAggregator = new MockEventAggregator();
            eventAggregator.GetEventDelegate = type => shoppingCartItemUpdatedEvent;
            var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());

            await target.RemoveProductFromShoppingCartAsync("TestProductId");

            Assert.IsTrue(shoppingCartItemUpdatedRaised);
        }
        public void AddProductToCart_AddsNewShoppingCartItemToExistingCart_WithSameProduct()
        {
            var target = new ShoppingCartRepository();

            target.AddProductToCart("TestUser", new Product {
                ProductNumber = "123"
            });
            target.AddProductToCart("TestUser", new Product {
                ProductNumber = "123"
            });

            var cart = target.GetById("TestUser");

            Assert.IsNotNull(cart);
            Assert.AreEqual(1, cart.ShoppingCartItems.Count);

            var items = cart.ShoppingCartItems.Where(item => item.Product.ProductNumber == "123");

            Assert.AreEqual(1, items.Count());
            Assert.AreEqual(2, items.First().Quantity);
        }
示例#5
0
        public ActionResult CartIconNumber()
        {
            var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null)
            {
                ViewBag.IsAuthenticated = false;
                ViewData["iconcount"]   = "0";
                return(PartialView());
            }

            var ticket = FormsAuthentication.Decrypt(cookie.Value);

            ViewBag.IsAuthenticated = true;
            ViewBag.UserName        = ticket.UserData;
            var repository = new ShoppingCartRepository();
            var Data       = repository.FindByMemberID(ticket.UserData);

            ViewData["iconcount"] = Data.Count().ToString();
            return(PartialView());
        }
示例#6
0
        public void GetById_CartNotFound_ReturnNull()
        {
            var target = new ShoppingCartRepository(_databaseSettings);

            var cart1 = new CartBuilder().WithId(null).WithCustomerId("1").Build();

            target.Create(cart1);

            var cart2 = new CartBuilder().WithId(null).WithCustomerId("2").Build();

            target.Create(cart2);


            var cart3 = new CartBuilder().WithId(null).WithCustomerId("3").Build();

            target.Create(cart3);

            var actual = target.FindById(Invalid_ID);

            Assert.Null(actual);
        }
示例#7
0
        public void GetAll_HasOneCart_returnAllShoppingCartsInformation()
        {
            var repository = new ShoppingCartRepository(_databaseSettings);

            var cart = new CartBuilder()
                       .WithId(null)
                       .WithCustomerId("1")
                       .WithItems(new List <Item> {
                CreateItem()
            })
                       .Build();

            repository.Create(cart);


            var target = CreateShoppingCartController(repository);

            var actual = target.GetAll();

            var cartItem = cart.Items[0];
            var expected =
                new ShoppingCartDto
            {
                Id              = cart.Id,
                CustomerId      = cart.CustomerId,
                CustomerType    = cart.CustomerType,
                ShippingAddress = cart.ShippingAddress,
                ShippingMethod  = cart.ShippingMethod,
                Items           = new List <ItemDto>
                {
                    new(ProductId : cartItem.ProductId,
                        ProductName : cartItem.ProductName,
                        Price : cartItem.Price,
                        Quantity : cartItem.Quantity
                        )
                }
            };

            Assert.Equal(expected, actual.Single());
        }
示例#8
0
        public void Delete_ValidData_RemoveShoppingCartToDB()
        {
            var cart = new CartBuilder()
                       .WithId(null)
                       .WithCustomerId("1")
                       .WithItems(new List <Item> {
                CreateItem()
            })
                       .Build();

            var repository = new ShoppingCartRepository(_databaseSettings);

            repository.Create(cart);

            var target = CreateShoppingCartController(repository);

            var result = target.DeleteCart(cart.Id);

            var value = repository.FindById(cart.Id);

            Assert.Null(value);
        }
        public async Task GetShoppingCartAsync_CachesCart()
        {
            var shoppingCart        = new ShoppingCart(new Collection <ShoppingCartItem>());
            var shoppingCartService = new MockShoppingCartService()
            {
                GetShoppingCartAsyncDelegate = s => Task.FromResult(shoppingCart)
            };

            var target            = new ShoppingCartRepository(shoppingCartService, null, null, new MockSessionStateService());
            var firstCartReturned = await target.GetShoppingCartAsync();

            shoppingCartService.GetShoppingCartAsyncDelegate = s =>
            {
                Assert.Fail("Should not have called proxy second time.");
                return(Task.FromResult((ShoppingCart)null));
            };

            var secondCartReturned = await target.GetShoppingCartAsync();

            Assert.AreSame(shoppingCart, firstCartReturned);
            Assert.AreSame(shoppingCart, secondCartReturned);
        }
        public async void CartItemUpdatedEventRaised_WhenProductRemoved()
        {
            var shoppingCartItemUpdatedRaised = false;
            var shoppingCartService           = new MockShoppingCartService();

            shoppingCartService.RemoveProductFromShoppingCartAsyncDelegate =
                (s, s1) => Task.FromResult(string.Empty);
            var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();

            shoppingCartItemUpdatedEvent.Subscribe((_) =>
            {
                shoppingCartItemUpdatedRaised = true;
            });
            var eventAggregator = new MockEventAggregator();

            eventAggregator.GetEventDelegate = type => shoppingCartItemUpdatedEvent;
            var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());

            await target.RemoveProductFromShoppingCartAsync("TestProductId");

            Assert.IsTrue(shoppingCartItemUpdatedRaised);
        }
示例#11
0
        public async Task CountTotal_EmptyShoppingCart()
        {
            var serviceProvider = BuildInMemoryDBProvider();

            using (var dbContext = serviceProvider.GetService <DatabaseContext>())
            {
                //Arrange
                var shoppingCart = new ShoppingCart()
                {
                    Id    = "1",
                    Items = new List <ShoppingCartMobilePhone>()
                };
                var user = new ApplicationUser()
                {
                    Id           = "1",
                    ShoppingCart = shoppingCart
                };
                dbContext.Add(user);
                await dbContext.SaveChangesAsync();

                var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
                mockHttpContextAccessor.Object.HttpContext = new DefaultHttpContext();
                var claims = new ClaimsPrincipal();
                mockHttpContextAccessor.Setup(x => x.HttpContext.User).Returns(claims);
                List <ApplicationUser> _users = new List <ApplicationUser>();
                var userManager            = MockUserManager <ApplicationUser>(_users).Object;
                var shoppingCartRepository = new ShoppingCartRepository(dbContext, userManager, mockHttpContextAccessor.Object);
                //Act
                var result = await shoppingCartRepository.CountTotal(shoppingCart);

                var sc = await shoppingCartRepository.GetShoppingCart();

                //Assert
                result.Should().Be(0);
                sc.Should().BeOfType <ShoppingCart>();
                sc.Should().NotBeNull();
                sc.Items.Should().HaveCount(0);
            }
        }
示例#12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDirectoryBrowser();

            services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <AppUser>(options =>
            {
                options.Password.RequiredLength               = 8;
                options.Password.RequireDigit                 = false;
                options.Password.RequireUppercase             = false;
                options.Password.RequiredUniqueChars          = 0;
                options.Password.RequireNonAlphanumeric       = false;
                options.User.RequireUniqueEmail               = true;
                options.SignIn.RequireConfirmedEmail          = true;
                options.SignIn.RequireConfirmedAccount        = true;
                options.Tokens.EmailConfirmationTokenProvider = "emailconfirmation";
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <EmailConfirmationTokenProvider <AppUser> >("emailconfirmation");

            //services.AddIdentityCore<IdentityUser<Guid>, IdentityRole<Guid>>().AddEntityFrameworkStores<AppDbContext>();
            services.Configure <DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(4));

            services.Configure <MailSettings>(Configuration.GetSection("MailSettings"));

            services.AddTransient <IBookRepository, BookRepository>();
            services.AddTransient <IOrderRepository, OrderRepository>();
            services.AddScoped <ShoppingCartRepository>(sp => ShoppingCartRepository.GetCart(sp));

            services.AddTransient <IEmailService, EmailService>();

            services.AddHttpContextAccessor();
            services.AddSession();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }
示例#13
0
        public void Test_GetAll_ReturnProductInCart_WhenCalled()
        {
            //Arrange
            Product Book     = new Product();
            var     expected = new List <ShoppingCart>
            {
                new ShoppingCart {
                    Title = Book
                }
            };

            var testData = new List <ShoppingCart>
            {
                new ShoppingCart {
                    Title = Book
                }
            }.AsQueryable();

            var mockSet = new Mock <IDbSet <ShoppingCart> >();

            mockSet.As <IQueryable <ShoppingCart> >().Setup(m => m.Provider).Returns(testData.Provider);
            mockSet.As <IQueryable <ShoppingCart> >().Setup(m => m.Expression).Returns(testData.Expression);
            mockSet.As <IQueryable <ShoppingCart> >().Setup(m => m.ElementType).Returns(testData.ElementType);
            mockSet.As <IQueryable <ShoppingCart> >().Setup(m => m.GetEnumerator()).Returns(testData.GetEnumerator());

            var mockContext = new Mock <BookSaleEntities>();

            mockContext.Setup(m => m.ShoppingCart).Returns(mockSet.Object);

            var testClass = new ShoppingCartRepository(mockContext.Object);

            //Act
            var actual = testClass.GetAll();

            //Assert

            CollectionAssert.AreEqual(testData, actual);
        }
示例#14
0
        public void ShoppingCartRepositoryTests_Update()
        {
            ShoppingCartRepository repository = new ShoppingCartRepository();
            var model = new Shopping_Cart()
            {
                Shopping_Cart_ID = 3,
                Account          = "Bill",
                Product_ID       = 3,
                Quantity         = 3,
                UnitPrice        = 150,
                Discount         = 0,
                size             = "s"
            };

            repository.Update(3, 5);
            var result = repository.GetAll();
            var test   = result.Where(x => x.Quantity == 3);

            foreach (var item in test)
            {
                Assert.IsTrue(item.Quantity == 3);
            }
        }
示例#15
0
        public ActionResult ColorFilter(string Colors)
        {
            Procedure.Procedure procedure = new Procedure.Procedure();
            ViewData["color"] = procedure.ColorFilters(Colors);

            var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie == null)
            {
                ViewBag.IsAuthenticated = false;
                return(View());
            }

            var ticket = FormsAuthentication.Decrypt(cookie.Value);

            ViewBag.IsAuthenticated = true;
            ViewBag.UserName        = ticket.UserData;
            var repository = new ShoppingCartRepository();
            var Data       = repository.FindByMemberID(ticket.UserData);

            ViewData["count"] = Data.Count().ToString();
            return(View());
        }
示例#16
0
        public void Create_ValidData_SaveShoppingCartToDB()
        {
            var repository = new ShoppingCartRepository(_databaseSettings);

            var target = CreateShoppingCartController(repository);

            var result = target.Create(new CreateCartDto
            {
                Customer = new CustomerDto
                {
                    Address = CreateAddress(),
                },

                Items = new[] { CreateItemDto() }
            });

            Assert.IsType <CreatedAtRouteResult>(result.Result);
            var cartId = ((CreatedAtRouteResult)result.Result).RouteValues["id"]?.ToString();

            var value = repository.FindById(cartId);

            Assert.NotNull(value);
        }
示例#17
0
        /// <summary>
        /// ResolveDependencyServices
        /// </summary>
        /// <param name="services"></param>
        private void ResolveDependencyServices(IServiceCollection services)
        {
            services.AddScoped <IRepository <Category>, EfRepository <Category> >();
            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <ISubCategoryService, SubCategoryService>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IManufacturerService, ManufacturerService>();
            services.AddTransient(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddScoped <ISalesOrderService, SalesOrderService>();

            services.AddScoped <IShoppingCartService, ShoppingCartService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IShoppingCartRepository>(sp => ShoppingCartRepository.GetCart(sp));
            services.AddScoped <IOrderRepository, OrderRepository>();
            services.AddScoped <IUserService, UserService>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
            //services.AddScoped(IDbContext, ApplicationDBContext);
            services.AddScoped <ProfileManager, ProfileManager>();
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddSingleton <IEmailSender, EmailSender>();
            services.AddSingleton <ICacheService, CacheService>();
        }
        public void HandleTest()
        {
            ShoppingCartRepository.ClearCart();
            var productCommandProxy = new ProductCommandProxy();

            var command = new AddQuantityCommand()
            {
                ProductId = 1,
                Quantity  = 5
            };

            productCommandProxy.Store(command);

            command = new AddQuantityCommand()
            {
                ProductId = 2,
                Quantity  = 16
            };

            productCommandProxy.Store(command);

            command = new AddQuantityCommand()
            {
                ProductId = 3,
                Quantity  = 3
            };

            productCommandProxy.Store(command);

            while (!productCommandProxy.Process())
            {
            }

            List <string> shoppingCartQueryResult = (List <string>) new ShoppingCartQuery().GetNamedShoppingCartElements();

            Assert.AreEqual(shoppingCartQueryResult.Count, 3);
        }
        public void AddDeveloperToShoppingCartErrorByDuplicatingDevelopers()
        {
            HttpContext.Current = new HttpContext(new HttpRequest(null, "http://localhost", null), new HttpResponse(null));

            var newDeveloper = new ShoppingCartDeveloper()
            {
                Username = "******",
                Price    = 200
            };

            var duplicatedDeveloper = new ShoppingCartDeveloper()
            {
                Username = "******",
                Price    = 200
            };

            ShoppingCartRepository repository = new ShoppingCartRepository();

            bool firsDevloperAdded    = repository.AddDeveloperToShoppingCart(newDeveloper);
            bool secondDeveloperAdded = repository.AddDeveloperToShoppingCart(duplicatedDeveloper);

            Assert.IsTrue(firsDevloperAdded);
            Assert.IsFalse(secondDeveloperAdded);
        }
        public async Task CartItemUpdatedEventRaised_WhenItemRemoved()
        {
            var shoppingCartItemUpdatedRaised = false;
            var shoppingCartService = new MockShoppingCartService()
                {
                    RemoveShoppingCartItemDelegate = (s, s1) =>
                        {
                            Assert.AreEqual("TestShoppingCartItemId", s1);
                            return Task.FromResult(string.Empty);
                        }
                };
            var shoppingCartItemUpdatedEvent = new ShoppingCartItemUpdatedEvent();
            shoppingCartItemUpdatedEvent.Subscribe((a) => shoppingCartItemUpdatedRaised = true);

            var eventAggregator = new MockEventAggregator()
                {
                    GetEventDelegate = (a) => shoppingCartItemUpdatedEvent
                };

            var target = new ShoppingCartRepository(shoppingCartService, new MockAccountService(), eventAggregator, new MockSessionStateService());
            await target.RemoveShoppingCartItemAsync("TestShoppingCartItemId");

            Assert.IsTrue(shoppingCartItemUpdatedRaised);
        }
示例#21
0
 public HomeController(ShoppingCartRepository shoppingCart)
 {
     this.shoppingCart = shoppingCart;
 }
示例#22
0
 public OrderController(IOrderRepository orderRepository, ShoppingCartRepository shoppingCart)
 {
     _orderRepository = orderRepository;
     _shoppingCart    = shoppingCart;
 }
 public ShoppingCartAdapter()
 {
     _shoppingCartRepository = new ShoppingCartRepository();
 }
 public ShoppingCartController(ShoppingCartRepository shopppingCartRepository)
 {
     _shopppingCartRepository = shopppingCartRepository;
 }
示例#25
0
 public void Handle(ClearShoppingCartEvent eventData)
 {
     ShoppingCartRepository.ClearCart();
 }
        public async Task GetShoppingCartAsync_CachesCart()
        {

            var shoppingCart = new ShoppingCart(new Collection<ShoppingCartItem>());
            var shoppingCartService = new MockShoppingCartService()
                {
                    GetShoppingCartAsyncDelegate = s => Task.FromResult(shoppingCart)
                };

            var target = new ShoppingCartRepository(shoppingCartService, null, null, new MockSessionStateService());
            var firstCartReturned = await target.GetShoppingCartAsync();
            shoppingCartService.GetShoppingCartAsyncDelegate = s =>
            {
                Assert.Fail("Should not have called proxy second time.");
                return Task.FromResult((ShoppingCart)null);
            };

            var secondCartReturned = await target.GetShoppingCartAsync();
            Assert.AreSame(shoppingCart, firstCartReturned);
            Assert.AreSame(shoppingCart, secondCartReturned);
        }
 public LineItemsController()
 {
     shoppingCartRepository = new ShoppingCartRepository();
 }
        public async Task Remove_InvalidatesCachedCart()
        {
            var shoppingCartService = new MockShoppingCartService
                {
                    RemoveShoppingCartItemDelegate = (s, s1) => Task.FromResult(string.Empty),
                    GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) {Id = "first"})
                };
            var eventAggregator = new MockEventAggregator
                {
                    GetEventDelegate = type => new ShoppingCartItemUpdatedEvent()
                };
            var target = new ShoppingCartRepository(shoppingCartService, null, eventAggregator, new MockSessionStateService());
            var firstCartReturned = await target.GetShoppingCartAsync();

            await target.RemoveShoppingCartItemAsync("TestShoppingCartItemId");

            shoppingCartService.GetShoppingCartAsyncDelegate = s => Task.FromResult(new ShoppingCart(new Collection<ShoppingCartItem>()) { Id = "second" });
            var secondCartReturned = await target.GetShoppingCartAsync();

            Assert.IsNotNull(firstCartReturned);
            Assert.IsNotNull(secondCartReturned);
            Assert.AreNotSame(firstCartReturned, secondCartReturned);
        }
示例#29
0
    static async Task Start()
    {
        Log.Logger = new LoggerConfiguration()
                     .MinimumLevel.Information()
                     .Enrich.With(new ExceptionMessageEnricher())
                     .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{ExceptionMessage}{NewLine}")
                     .CreateLogger();

        LogManager.Use <SerilogFactory>();

        Console.Title = "Frontend";

        var endpointUri = "https://localhost:8081";
        //TODO: Update key
        var primaryKey   = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
        var cosmosClient = new CosmosClient(endpointUri, primaryKey);

        var repository = new ShoppingCartRepository(cosmosClient, "Ex14");
        var tokenStore = new TokenStore(cosmosClient, "Ex14");

        await repository.Initialize();

        await tokenStore.Initialize();

        var config = new EndpointConfiguration("Frontend");

        config.Pipeline.Register(new DuplicateMessagesBehavior(), "Duplicates outgoing messages");
        config.SendFailedMessagesTo("error");
        var routing = config.UseTransport <LearningTransport>().Routing();

        routing.RouteToEndpoint(typeof(SubmitOrder).Assembly, "Orders");
        config.Pipeline.Register(b => new OutboxBehavior <ShoppingCart>(repository, b.Build <IDispatchMessages>(), tokenStore,
                                                                        m =>
        {
            if (m is SendSubmitOrder sendSubmit)
            {
                return(sendSubmit.OrderId);
            }

            return(null);
        }), "Deduplicates incoming messages");


        config.EnableInstallers();

        var endpoint = await Endpoint.Start(config).ConfigureAwait(false);

        var appServices = new ApplicationServices(repository, endpoint);

        Console.WriteLine("'create <order-id>' to create a new order.");
        Console.WriteLine("'submit <order-id>' to submit an order.");
        Console.WriteLine($"'add ({string.Join("|", Enum.GetNames(typeof(Filling)))}) to <order-id>' to add item with selected filling.");

        while (true)
        {
            var command = Console.ReadLine();

            if (string.IsNullOrEmpty(command))
            {
                break;
            }

            var match = submitExpr.Match(command);
            if (match.Success)
            {
                var orderId = match.Groups[1].Value;
                await appServices.SubmitOrder(orderId);

                continue;
            }
            match = createExpr.Match(command);
            if (match.Success)
            {
                var orderId = match.Groups[1].Value;
                await appServices.CreateOrder(orderId);

                continue;
            }
            match = addExpr.Match(command);
            if (match.Success)
            {
                var filling = match.Groups[1].Value;
                var orderId = match.Groups[2].Value;

                await appServices.AddItem(orderId, (Filling)Enum.Parse(typeof(Filling), filling));

                continue;
            }
            match = removeExpr.Match(command);
            if (match.Success)
            {
                var filling = match.Groups[1].Value;
                var orderId = match.Groups[2].Value;
                await appServices.RemoveItem(orderId, (Filling)Enum.Parse(typeof(Filling), filling));

                continue;
            }
            Console.WriteLine("Unrecognized command.");
        }

        await endpoint.Stop().ConfigureAwait(false);
    }
示例#30
0
        public async Task CountTotal_TwoDiffrentItemsAndDiffrentQuantity()
        {
            var serviceProvider = BuildInMemoryDBProvider();

            using (var dbContext = serviceProvider.GetService <DatabaseContext>())
            {
                //Arrange
                var shoppingCart = new ShoppingCart()
                {
                    Id    = "1",
                    Items = new List <ShoppingCartMobilePhone>()
                };
                var user = new ApplicationUser()
                {
                    Id           = "1",
                    ShoppingCart = shoppingCart
                };
                var mobilePhone = new MobilePhone()
                {
                    Id    = 1,
                    Price = 2000
                };
                var mobilePhone2 = new MobilePhone()
                {
                    Id    = 2,
                    Price = 3000
                };
                var item = new ShoppingCartMobilePhone()
                {
                    MobilePhoneId  = 1,
                    ShoppingCartId = "1",
                    Quantity       = 5
                };
                var item2 = new ShoppingCartMobilePhone()
                {
                    MobilePhoneId  = 2,
                    ShoppingCartId = "1",
                    Quantity       = 2
                };
                shoppingCart.Items.Add(item);
                shoppingCart.Items.Add(item2);
                dbContext.Add(mobilePhone);
                dbContext.Add(mobilePhone2);
                dbContext.Add(user);
                await dbContext.SaveChangesAsync();

                var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
                mockHttpContextAccessor.Object.HttpContext = new DefaultHttpContext();
                var claims = new ClaimsPrincipal();
                mockHttpContextAccessor.Setup(x => x.HttpContext.User).Returns(claims);
                List <ApplicationUser> _users = new List <ApplicationUser>();
                var userManager            = MockUserManager <ApplicationUser>(_users).Object;
                var shoppingCartRepository = new ShoppingCartRepository(dbContext, userManager, mockHttpContextAccessor.Object);
                //Act
                var result = await shoppingCartRepository.CountTotal(shoppingCart);

                var sc = await shoppingCartRepository.GetShoppingCart();

                //Assert
                result.Should().Be(16000);
                sc.Should().BeOfType <ShoppingCart>();
                sc.Should().NotBeNull();
                sc.Items.Should().HaveCount(2);
                sc.Items.ToList()[0].Quantity.Should().Be(5);
                sc.Items.ToList()[1].Quantity.Should().Be(2);
            }
        }
        public void CartUpdatedEventRaised_WhenUserChanged()
        {
            var shoppingCartUpdatedRaised = false;
            var accountService = new MockAccountService();
            var shoppingCartUpdatedEvent = new MockShoppingCartUpdatedEvent()
                {
                    PublishDelegate = () => shoppingCartUpdatedRaised = true
                };
            var eventAggregator = new MockEventAggregator()
                {
                    GetEventDelegate = (a) => shoppingCartUpdatedEvent
                };
            var shoppingCartService = new MockShoppingCartService()
                {
                    MergeShoppingCartsAsyncDelegate = (s, s1) => Task.FromResult(false)
                };

            var target = new ShoppingCartRepository(shoppingCartService, accountService, eventAggregator, new MockSessionStateService());
            accountService.RaiseUserChanged(new UserInfo { UserName = "******" }, null);

            Assert.IsTrue(shoppingCartUpdatedRaised);
        }
示例#32
0
 public ShoppingCartFacade(ShoppingCartRepository repository)
 {
     Repository = repository;
 }
        public void ShoppingCartMerged_WhenAnonymousUserLogsIn()
        {
            bool mergeShoppingCartsCalled  = false;
            bool alertMessageServiceCalled = false;
            var  anonymousCartItems        = new List <ShoppingCartItem>
            {
                new ShoppingCartItem
                {
                    Quantity = 1, Product = new Product {
                        ProductNumber = "123"
                    }
                }
            };
            var testUserCartItems = new List <ShoppingCartItem>
            {
                new ShoppingCartItem
                {
                    Quantity = 2, Product = new Product {
                        ProductNumber = "123"
                    }
                }
            };

            var shoppingCartService = new MockShoppingCartService()
            {
                GetShoppingCartAsyncDelegate = s =>
                {
                    switch (s)
                    {
                    case "AnonymousId":
                        return(Task.FromResult(new ShoppingCart(anonymousCartItems)));

                    default:
                        return(Task.FromResult(new ShoppingCart(testUserCartItems)));
                    }
                },
                MergeShoppingCartsAsyncDelegate = (s, s1) =>
                {
                    mergeShoppingCartsCalled = true;
                    Assert.AreEqual("AnonymousId", s);
                    Assert.AreEqual("TestUserName", s1);
                    return(Task.FromResult(true));
                }
            };
            var accountService           = new MockAccountService();
            var shoppingCartUpdatedEvent = new MockShoppingCartUpdatedEvent
            {
                PublishDelegate = () => { }
            };

            var eventAggregator = new MockEventAggregator()
            {
                GetEventDelegate = (a) => shoppingCartUpdatedEvent
            };
            var sessionStateService = new MockSessionStateService();

            sessionStateService.SessionState[ShoppingCartRepository.ShoppingCartIdKey] = "AnonymousId";

            var target = new ShoppingCartRepository(shoppingCartService, accountService, eventAggregator, sessionStateService);

            accountService.RaiseUserChanged(new UserInfo {
                UserName = "******"
            }, null);

            Assert.IsTrue(mergeShoppingCartsCalled);
        }
 public ShoppingCartSummary(ShoppingCartRepository shoppingCart)
 {
     _shoppingCart = shoppingCart;
 }
        public void ShoppingCartMerged_WhenAnonymousUserLogsIn()
        {
            bool mergeShoppingCartsCalled = false;
            bool alertMessageServiceCalled = false;
            var anonymousCartItems = new List<ShoppingCartItem>
                                         {
                                             new ShoppingCartItem
                                                 {Quantity = 1, Product = new Product {ProductNumber = "123"}}
                                         };
            var testUserCartItems = new List<ShoppingCartItem>
                                         {
                                             new ShoppingCartItem
                                                 {Quantity = 2, Product = new Product {ProductNumber = "123"}}
                                         };

            var shoppingCartService = new MockShoppingCartService()
                {
                    GetShoppingCartAsyncDelegate = s =>
                        {
                            switch (s)
                            {
                                case "AnonymousId": 
                                    return Task.FromResult(new ShoppingCart(anonymousCartItems));
                                default:
                                    return Task.FromResult(new ShoppingCart(testUserCartItems));
                            }
                        },
                    MergeShoppingCartsAsyncDelegate = (s, s1) =>
                        {
                            mergeShoppingCartsCalled = true;
                            Assert.AreEqual("AnonymousId", s);
                            Assert.AreEqual("TestUserName", s1);
                            return Task.FromResult(true);
                        }
                };
            var accountService = new MockAccountService();
            var shoppingCartUpdatedEvent = new MockShoppingCartUpdatedEvent
                {
                    PublishDelegate = () => { }
                };
            
            var eventAggregator = new MockEventAggregator()
                {
                    GetEventDelegate = (a) => shoppingCartUpdatedEvent
                };
            var sessionStateService = new MockSessionStateService();
            sessionStateService.SessionState[ShoppingCartRepository.ShoppingCartIdKey] = "AnonymousId";

            var target = new ShoppingCartRepository(shoppingCartService, accountService, eventAggregator, sessionStateService);
            accountService.RaiseUserChanged(new UserInfo { UserName = "******" }, null);

            Assert.IsTrue(mergeShoppingCartsCalled);
        }
 public void Initialize()
 {
     ShoppingCartRepository.Reset();
 }
示例#37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string salt = "ChCcXzeW";

            string[] merc_hash_vars_seq;
            string   merc_hash_string = string.Empty;
            string   merc_hash        = string.Empty;
            string   order_id         = string.Empty;
            string   hash_seq         = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";

            if (Request.Form["status"].ToString() == "success")
            {
                merc_hash_vars_seq = hash_seq.Split('|');
                Array.Reverse(merc_hash_vars_seq);
                merc_hash_string = salt + "|" + Request.Form["status"].ToString();

                order_id = Request.Form["txnid"];

                foreach (string merc_hash_var in merc_hash_vars_seq)
                {
                    merc_hash_string += "|";
                    merc_hash_string  = merc_hash_string + (Request.Form[merc_hash_var] != null ? Request.Form[merc_hash_var] : "");
                }
                //Response.Write(merc_hash_string);
                merc_hash = Generatehash512(merc_hash_string).ToLower();

                StringBuilder txnDetails = new StringBuilder();
                foreach (string key in Request.Form.Keys)
                {
                    txnDetails.Append("  ").Append(key).Append("|").AppendLine(Request.Form[key]);
                }

                if (merc_hash != Request.Form["hash"])
                {
                    //Response.Write("Hash value did not matched");
                    ShoppingCartRepository cartRepository = new ShoppingCartRepository(new ShoppingCartDatContext());
                    var order = cartRepository.GetOrderProductUsingTransaction(order_id);
                    if (order != null)
                    {
                        order.TransactionResult        = Request.Form["status"].ToString();
                        order.TransactionResultDetails = "Hash value did not matched.  " + hash_seq + txnDetails.ToString();
                        order.OrderStatusId            = (int)VSOnline.VSECommerce.Utilities.Enums.PaymentStatus.PaymentInProgress;
                        order.PaymentStatusId          = (int)VSOnline.VSECommerce.Utilities.Enums.OrderStatus.VerficationInProgress;
                        cartRepository.UpdateAndSave(order);
                        cartRepository.UpdateOrderProductItemStatus(order.Id, order.OrderStatusId);
                    }
                    Response.Redirect("http://vbuy.in/confirmOrder/" + order.Id, false);
                    Response.End();
                }
                else
                {
                    order_id = Request.Form["txnid"];


                    ShoppingCartRepository cartRepository = new ShoppingCartRepository(new ShoppingCartDatContext());
                    var order = cartRepository.GetOrderProductUsingTransaction(order_id);

                    if (order != null)
                    {
                        order.TransactionResult        = Request.Form["status"].ToString();
                        order.TransactionResultDetails = "Status is successful. Hash value is matched" + hash_seq + txnDetails.ToString();
                        order.OrderStatusId            = (int)VSOnline.VSECommerce.Utilities.Enums.OrderStatus.Verified;
                        order.PaymentStatusId          = (int)VSOnline.VSECommerce.Utilities.Enums.PaymentStatus.PaymentCompleted;
                        cartRepository.UpdateAndSave(order);
                        cartRepository.UpdateOrderProductItemStatus(order.Id, order.OrderStatusId);
                    }
                    Response.Redirect("http://vbuy.in/confirmOrder/" + order.Id, true);
                    //  ViewData["Message"] = "Status is successful. Hash value is matched";
                    //  Response.Write("<br/>Hash value matched");

                    //Hash value did not matched
                }
            }

            else
            {
                ShoppingCartRepository cartRepository = new ShoppingCartRepository(new ShoppingCartDatContext());
                //var order = cartRepository.GetOrderProduct(intOrderId);
                //order.TransactionResult = form["status"].ToString();
                //      order.TransactionResultDetails = "Failure" +  hash_seq;
                var           order      = cartRepository.GetOrderProductUsingTransaction(order_id);
                StringBuilder txnDetails = new StringBuilder();
                foreach (string key in Request.Form.Keys)
                {
                    txnDetails.Append("  ").Append(key).Append(" | ").AppendLine(Request.Form[key]);
                }
                if (order != null)
                {
                    order.TransactionResult        = Request.Form["status"].ToString();
                    order.TransactionResultDetails = "Failure" + hash_seq + txnDetails.ToString();;
                    order.OrderStatusId            = (int)VSOnline.VSECommerce.Utilities.Enums.OrderStatus.VerficationInProgress;
                    order.PaymentStatusId          = (int)VSOnline.VSECommerce.Utilities.Enums.PaymentStatus.PaymentInProgress;
                    cartRepository.UpdateAndSave(order);
                    cartRepository.UpdateOrderProductItemStatus(order.Id, order.OrderStatusId);
                }
                Response.Redirect("http://www.vbuy.in/failedTransactionOrder/" + order.Id, true);
            }
        }
        catch (ThreadAbortException exc)
        {
            // This should be first catch block i.e. before generic Exception
            // This Catch block is to absorb exception thrown by Response.End
        }
        catch (Exception ex)
        {
            Response.Write("<span style='color:red'>" + ex.Message + "</span>");
            try
            {
                var txnId = Request.Form["txnid"];
                ShoppingCartRepository cartRepository = new ShoppingCartRepository(new ShoppingCartDatContext());
                var forder = cartRepository.GetOrderProductUsingTransaction(txnId);
                if (forder != null)
                {
                    forder.TransactionResult        = Request.Form["status"].ToString();
                    forder.TransactionResultDetails = "Failure";
                    forder.OrderStatusId            = (int)VSOnline.VSECommerce.Utilities.Enums.OrderStatus.VerficationInProgress;
                    forder.PaymentStatusId          = (int)VSOnline.VSECommerce.Utilities.Enums.PaymentStatus.PaymentInProgress;
                    cartRepository.UpdateAndSave(forder);
                    cartRepository.UpdateOrderProductItemStatus(forder.Id, forder.OrderStatusId);
                }
                Response.Redirect("http://www.vbuy.in/failedTransactionOrder/" + forder.Id, true);
            }
            catch (ThreadAbortException exc)
            {
                // This should be first catch block i.e. before generic Exception
                // This Catch block is to absorb exception thrown by Response.End
            }
            catch
            {
                Response.Redirect("http://vbuy.in/failedTransactionOrder/" + 0, true);
            }
        }
    }
示例#38
0
 public CartAdapter()
 {
     _cartItems = ShoppingCartRepository.GetAllShoppingCartItems();
 }