public ActionResult EditAppSetting(int id) { TempData["AppSettingEditId"] = id; using (var context = new ShoppingCartContext()) { var appSetting = new AppSettingViewModel(); if (id == -1) { appSetting.Value = ""; appSetting.Code = ""; appSetting.Description = "AppSetting description"; appSetting.ValueType = "decimal"; } else { var oCat = context.AppSettings.Single(c => c.Id == id); if (oCat != null) { appSetting.Value = oCat.Value; appSetting.Code = oCat.Code; appSetting.Description = oCat.Description; appSetting.ValueType = oCat.ValueType; } } return(View(appSetting)); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Mapper.Initialize(item => { item.CreateMap<Cart, CartViewModel>(); item.CreateMap<CartItem, CartItemViewModel>(); item.CreateMap<Book, BookViewModel>(); item.CreateMap<Author, AuthorViewModel>(); item.CreateMap<Category, CategoryViewModel>(); item.CreateMap<CartItemViewModel, CartItem> (); item.CreateMap< BookViewModel, Book > (); item.CreateMap<AuthorViewModel ,Author> (); item.CreateMap<CategoryViewModel, Category> (); }); var dbContext=new ShoppingCartContext(); Database.SetInitializer(new DataInitialization()); dbContext.Database.Initialize(true); }
// GET api/<controller>/5 public ProductViewModel Get(int id) { var ret = new ProductViewModel(); using (var context = new ShoppingCartContext()) { var product = context.Products.SingleOrDefault(p => p.Code == id.ToString()); if (product != null) { ret.Code = product.Code; ret.Description = product.Description; ret.Image = product.Image; ret.Id = product.Id; ret.Active = product.Active; ret.QuantityOnHand = product.QuantityOnHand; } else { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("No product with Code = {0}", id)), ReasonPhrase = "Product code Not Found" }; throw new HttpResponseException(resp); } } return(ret); }
public List <Product> GetAll() { using (_context = new ShoppingCartContext()) { return(_context.Product.ToList()); } }
public ShoppingCartController(IShoppingCartRepository repository, IPaymentProvider paymentProvider, INotificationProvider notificationProvider, ShoppingCartContext shoppingCartContext) { _repository = repository; _paymentProvider = paymentProvider; _notificationProvider = notificationProvider; _shoppingCartContext = shoppingCartContext; }
//public static async Task<int> Send(OrderSummaryViewModel order) //{ // var body = "<p>Order number: {0} from customer {1} </p><p>Order Total:</p><p>{2}</p>"; // var message = new MailMessage(); // var email1 = ""; // var email2 = ""; // using (var context = new ShoppingCartContext()) // { // email1 = context.AppSettings.Single(a => a.Code == "NotificationEmail1").Value; // email2 = context.AppSettings.Single(a => a.Code == "NotificationEmail2").Value; // } // message.To.Add(new MailAddress(email1)); //send to company email // message.To.Add(new MailAddress(email2)); //send to company email // message.Subject = "An order has placed !!"; // message.Body = string.Format(body, order.OrderNumber, order.FullName, order.Total.ToString("N0")); // message.IsBodyHtml = true; // using (var smtp = new SmtpClient()) // { // await smtp.SendMailAsync(message); // } // //send to customer email // if (!string.IsNullOrEmpty(order.Email)) // { // body = CreateEmailTemplate(order); // message = new MailMessage(); // message.To.Add(new MailAddress(order.Email)); // message.Subject = "Cảm ơn bạn đã đặt hàng ở H.A Shop !"; // message.Body = body; // message.IsBodyHtml = true; // using (var smtp = new SmtpClient()) // { // await smtp.SendMailAsync(message); // } // } // return 1; //} public static string CreateEmailTemplate(OrderConfirmViewModel order, string orderNumber) { //var text = "Tin nhắn từ: {0}. Nội dung: {1}. {2}"; var contact = ""; var rootUrl = ""; using (var context = new ShoppingCartContext()) { var contactInfo = context.Contents.SingleOrDefault(c => c.TextLocation == "Order.Email.ContactInfo"); if (contactInfo != null) { contact = contactInfo.TextValue; } rootUrl = context.AppSettings.Single(a => a.Code == "RootUrl").Value; } var ret = "Thank you for shopping at J.A Shop. Your order number is: " + orderNumber; ret += "<p> ================================================================= </p>"; ret += "<p><b> ORDER RECEIPT " + orderNumber + "</b></p>"; foreach (var p in order.CartViewModel.CartItems) { ret += "<p> #" + p.Product.Code + " . <b>Product name:</b> " + p.Product.Description + " <b>Price/Per unit:</b>" + p.OriginalPrice.ToString("N0") + "usd . <b>Quantity:</b> " + p.Quantity + " </p>"; } ret += "<p><b>Shipping fee:</b> " + order.CartViewModel.CartTotalShippingCost.ToString("N0") + "usd </p>"; ret += "<p><b>Total amount:</b>" + order.CartViewModel.CartTotal.ToString("N0") + "usd </p>"; ret += string.Format("<p> <a href=\"{0}/OrderSummary?orderNumber={1}&guid={2}&firstTime=False\">Track order status</a></p>", rootUrl, orderNumber, order.OrderGuid); ret += "<p> ================================================================= </p>"; ret += contact; return(ret); }
public ProductTests() { var option = new DbContextOptionsBuilder <ShoppingCartContext>().UseSqlite(("Data Source=shoppingcart_core.db")).Options; _context = new ShoppingCartContext(option); repository = new ProductRepository(_context); }
public ActionResult ViewShipment(string code) { using (var context = new ShoppingCartContext()) { var shipment = context.Shipments.SingleOrDefault(s => s.Code.Equals(code)); var ret = new ShipmentViewModel(); ret.Orders = new List <ShipmentOrderViewModel>(); ret.ShipDate = ""; ret.Recipient = ""; if (shipment != null) { ret.ShipDate = shipment.ShipDate.ToShortDateString(); ret.Recipient = shipment.Recipient; ret.Code = shipment.Code; context.Orders.Where(o => o.ShipmentId == shipment.Id).ForEach(or => ret.Orders.Add(new ShipmentOrderViewModel() { CustomerName = or.FullName, OrderNumber = or.OrderNumber, OrderTotal = or.Total, Id = or.Id })); } return(View(ret)); } }
public async Task <ActionResult> EditShipment(ShipmentViewModel model) { using (var context = new ShoppingCartContext()) { //new item if (model.Id == 0) { var shipment = new Shipment { Code = model.Code, Recipient = model.Recipient, ShipDate = DateTime.Parse(model.ShipDate), }; context.Shipments.Add(shipment); await context.SaveChangesAsync(); var orderLists = model.OrderIdsString.Split(','); context.Orders.Where(o => orderLists.Contains(o.OrderNumber.ToString())).ForEach(order => { order.ShipmentId = shipment.Id; }); } await context.SaveChangesAsync(); } return(View()); }
public async Task RemoveFromCart_WhenCartItemIdIsPassed_ShouldSucceed() { //arrange var options = new DbContextOptionsBuilder <ShoppingCartContext>() .UseInMemoryDatabase(databaseName: "RemoveFromCart_WhenCartItemIdIsPassed_ShouldSucceed") .Options; //act using (var context = new ShoppingCartContext(options)) { var logger = new Mock <ILogger <CartItemRepository> >(); var cir = new CartItemRepository(new ShoppingCartContext(options), logger.Object); await cir.AddToCart(new CartItem { CustomerId = 1, Quantity = 5, DateCreated = DateTime.Now, ArticleId = 1 }); await cir.AddToCart(new CartItem { CustomerId = 1, Quantity = 15, DateCreated = DateTime.Now, ArticleId = 1 }); context.SaveChanges(); await cir.RemoveFromCart(1); } //assert using (var context = new ShoppingCartContext(options)) { context.CartItem.Should().HaveCount(2); } }
public ShoppingCartServiceTests() { _context = new ShoppingCartContext(); _refContext = new ReferenceContext(); Database.SetInitializer(new DropCreateDatabaseIfModelChanges <ShoppingCartContext>()); }
public ActionResult PurchaseInstruction() { ViewBag.Message = "Hướng dẫn cách mua hàng"; var content = ""; var header = ""; using (var context = new ShoppingCartContext()) { var contentObj = context.Contents.SingleOrDefault(c => c.TextLocation == "Home.Purchase.Content"); if (contentObj != null) { content = contentObj.TextValue; } var headerObj = context.Contents.SingleOrDefault(c => c.TextLocation == "Home.Purchase.Header"); if (headerObj != null) { header = headerObj.TextValue; } } var ret = new PurchaseInstruction() { Content = content, Header = header }; return(View(ret)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ShoppingCartContext context) { // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "NSNCareers Shopping App API"); c.RoutePrefix = ""; }); app.UseForwardedHeaders(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseAuthentication(); //app.UseAuthorization(); //app.UseEndpoints(endpoints => endpoints.MapControllers()); app.UseHttpsRedirection(); app.UseMvc(); context.Database.Migrate(); }
public ArtworksController(ArtworkContext context, IWebHostEnvironment hostEnvironment, ShoppingCartContext co) { _context = context; _c = co; this._hostEnvironment = hostEnvironment; }
public Cart RemoveFromCart(int id) { using (var context = new ShoppingCartContext()) { // Get the cart var cartItem = context.Carts.Single( cart => cart.Code == ShoppingCartId && cart.Id == id); if (cartItem != null) { if (cartItem.Quantity > 1) { cartItem.Quantity--; // Save changes context.SaveChanges(); UpdateCart(); } else { context.Carts.Remove(cartItem); // Save changes context.SaveChanges(); UpdateCart(); return(null); } } return(context.Carts.Single(c => c.Code == ShoppingCartId && c.Id == id)); } }
public ShoppingCartService(ILogger <ShoppingCartService> logger, ShoppingCartContext shoppingCartContext, IMapper mapper, DiscountService discountService) { _logger = logger; _shoppingCartContext = shoppingCartContext; _mapper = mapper; _discountService = discountService; }
//public Cart GetCartLine(string cartId, int id) //{ // using (var context = new ShoppingCartContext()) // { // return context.Carts.Single(c => c.Code == cartId && c.Id == id); // } //} public Cart AddOneItemToCart(int id) { using (var context = new ShoppingCartContext()) { // Get the matching cart and product instances // Get the cart var cartItem = context.Carts.Single( cart => cart.Code == ShoppingCartId && cart.Id == id); if (cartItem != null) { //Add 1 more item cartItem.Quantity++; // Save changes context.SaveChanges(); UpdateCart(); } var ret = context.Carts.Single( cart => cart.Code == ShoppingCartId && cart.Id == id); return(ret); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var dbSection = Configuration.GetSection("MongoDBConfig"); services.Configure <MongoDbConfigurations>(dbSection); var dbOptions = dbSection.Get <MongoDbConfigurations>(); var shoppingCartContext = new ShoppingCartContext(dbOptions); services.AddSingleton <IItemRepository>(new ItemRepository(shoppingCartContext)); services.AddSingleton <ICartRepository>(new CartRepository(shoppingCartContext)); services.AddScoped <ICartService, CartService>(); services.AddSingleton <IStockCache, StockCacheInMemory>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo() { Title = "Shopping Cart API", Version = "v1", Description = "Shopping Cart API descripiton page", }); }); }
public ActionResult RemoveFromCart(int id) { // Remove the item from the cart ShoppingCart.Models.ShoppingCart shoppingCart = new ShoppingCart.Models.ShoppingCart(); var cart = shoppingCart.GetCart(HttpContext.Session.SessionID); ShoppingCartContext storeDB = shoppingCart.getDB(); // Get the name of the album to display confirmation string produdctTitle = storeDB.CartItems.Single(i => i.ProductID == id).Product.Title; // Remove from cart int itemCount = shoppingCart.RemoveFromCart(id); // Display the confirmation message var results = new ShoppingCartRemoveViewModel { Message = Server.HtmlEncode(produdctTitle) + " has been removed from your shopping cart.", CartTotal = shoppingCart.GetTotal(), CartCount = shoppingCart.GetCount(), ItemCount = itemCount, DeleteId = id }; return(Json(results)); }
public ActionResult EditCategory(int id) { TempData["CategoryEditId"] = id; using (var context = new ShoppingCartContext()) { var cat = new CategoryViewModel(); if (id == -1) { cat.Code = ""; cat.Description = "Description"; cat.Icon = null; cat.Active = true; } else { var oCat = context.Categories.Single(c => c.Id == id); if (oCat != null) { cat.Id = oCat.Id; cat.Code = oCat.Code; cat.Description = oCat.Description; cat.Icon = oCat.Icon; cat.Active = oCat.Active; } } return(View(cat)); } }
private void AddUserRoles() { ShoppingCartContext context = new ShoppingCartContext(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var UserManager = new UserManager <AppUser>(new UserStore <AppUser>(context)); if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); var passwordHash = new PasswordHasher(); string password = passwordHash.HashPassword("password123A"); var user = new AppUser(); //THIS is a serious BUG in Identity 2 username must be equal to Email user.UserName = "******"; user.Email = "*****@*****.**"; string userPWD = "password123A"; var chkUser = UserManager.Create(user, userPWD); if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } if (!roleManager.RoleExists("User")) { var urole = new IdentityRole(); urole.Name = "User"; roleManager.Create(urole); } }
// // GET: /CategoryManagment/ public ActionResult Index() { if (ModelState.IsValid) { var ret = new CategoryManagementViewModel(); using (var context = new ShoppingCartContext()) { context.Categories.ForEach(c => ret.CategoryViewModels.Add(new CategoryViewModel() { Code = c.Code, Description = c.Description, Id = c.Id, Icon = c.Icon, Active = c.Active })); } using (var context = new ShoppingCartContext()) { foreach (var cat in ret.CategoryViewModels) { cat.ProductsCount = (from p in context.Products where p.Categories.Any(c => c.Code == cat.Code) select p).Count(); } } return(View(ret)); } return(View()); }
public ActionResult EditContent(int id, string contentType) { var ret = new ContentDetailSummaryViewModel(); using (var context = new ShoppingCartContext()) { var content = context.Contents.Single(c => c.Id == id); ret.Code = content.Code; ret.Description = content.Description; ret.ContentType = contentType; if (content.Image != null) { ret.Image = content.Image; } ret.Id = id; ret.RouteTo = content.ImageUrl; //ret.ItemCode = content.ItemCode; ret.DisplayOrder = content.DisplayOrder; ret.AdText = content.AdText; ret.AdTextStyle = content.AdTextStyle; ret.TextValue = content.TextValue; ret.TextLocation = content.TextLocation; } return(View(ret)); }
public ShoppingCartService(ShoppingCartContext shoppingCartContext, DiscountService discountService, IMapper mapper, ILogger <ShoppingCartService> logger) { _shoppingCartContext = shoppingCartContext; _discountService = discountService; _mapper = mapper; _logger = logger; }
//Test // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ShoppingCartContext dbcontext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); dbcontext.Database.EnsureDeleted(); dbcontext.Database.EnsureCreated(); new DBSeeder(dbcontext); }
public List <Cart> GetAll() { using (_context = new ShoppingCartContext()) { return(_context.Cart.Include(path => path.CartItens).Include(p => p.PaymentInformation).ToList()); } }
public ShoppingCartService(ShoppingCartContext shoppingCartContext, ILogger <ShoppingCartService> logger, IMapper mapper, DiscountService discountService) { _shoppingCartContext = shoppingCartContext ?? throw new ArgumentNullException(nameof(shoppingCartContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _discountService = discountService ?? throw new ArgumentNullException(nameof(discountService)); }
public ShoppingCartIntegrationTests() { Database.SetInitializer(new DropCreateDatabaseIfModelChanges <ShoppingCartContext>()); _context = new ShoppingCartContext(); _refContext = new ReferenceContext(); _context.Database.Initialize(force: true);//get this out of the way before logging SetupLogging(); }
public ShoppingCartIntegrationTests() { Database.SetInitializer(new NullDatabaseInitializer <ShoppingCartContext>()); _context = new ShoppingCartContext(); _refContext = new ReferenceContext(); _context.Database.Initialize(true); //get this out of the way before logging SetupLogging(); }
public MockedShoppingCartIntegrationTests() { _cartsInMemory = new List <NewCart>(); _scMockingContext = new ShoppingCartContext { Carts = TestHelpers.MockDbSet(_cartsInMemory) }; _refMockingContext = new ReferenceContext(); }
protected void Application_Start() { var dbContext = new ShoppingCartContext(); Database.SetInitializer(new DataInitialization()); dbContext.Database.Initialize(true); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }