public static Cart FILLTEMPDATA(WebshopDbContext context, string user, ITempDataDictionary TempData, bool filltemp) { Cart cart = context.Carts.Include(x => x.Items).ThenInclude(x => x.Product).FirstOrDefault(x => x.Buyer == user); if (cart == null) { cart = new Cart(); cart.Buyer = user; context.Carts.Add(cart); } if (filltemp) { int price = cart.Items.Sum(x => x.Count * x.Product.Price); int count = cart.Items.Sum(x => x.Count); if (TempData.ContainsKey("Count")) { TempData["Count"] = count; TempData["CartPrice"] = price; } else { TempData.Add("Count", count); TempData.Add("CartPrice", price); } } return(cart); }
public DishController(WebshopDbContext context, AdminService adminService, CategoryService categoryService, IngredientService ingredientService) { _context = context; _adminService = adminService; _categoryService = categoryService; _ingredientService = ingredientService; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, WebshopDbContext context) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } 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.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); if (context.Categories.Count() < 1) { context.Seed(); } }
public static (List <string>, string, List <float>) ProductRevenueIndividual(WebshopDbContext db, DateTime startDate, DateTime endDate, string productName) { var query = from o in db.Order.ToList() join oi in db.OrderItem.ToList() on o.OrderId equals oi.OrderId where o.Date >= startDate && o.Date <= endDate group oi.PriceBought by new { oi.InventoryId, o.Date } into g select new { InvIDdAndDate = g.Key, Amount = g.Sum() }; var datesList = new List <string>(); var inventoryIdList = new List <int>(); var amountsList = new List <float>(); foreach (var item in query) { datesList.Add(item.InvIDdAndDate.Date.ToShortDateString()); inventoryIdList.Add(item.InvIDdAndDate.InventoryId); amountsList.Add(item.Amount); } var productsList = new List <string>(); foreach (var invId in inventoryIdList) { var invModel = db.Inventory.Single(x => x.InventoryId == invId); var productIdList = new List <int> { invModel.ProductId }; foreach (var prodId in productIdList) { var productModel = db.Product.Single(x => x.ProductId == prodId); productsList.Add(productModel.Name); } } var productDatesList = new List <string>(); var productAmountsList = new List <float>(); var product = "No sales found"; for (var i = 0; i < productsList.Count; i++) { var date = datesList[i]; var amount = amountsList[i]; var name = productsList[i]; if (name == productName) { product = name; productDatesList.Add(datesList[i]); productAmountsList.Add(amountsList[i]); } } return(productDatesList, product, productAmountsList); }
public static Order[] GetOrders(Guid userId, WebshopDbContext db) { return(db.Order .Include(orderStatus => orderStatus.OrderStatus) .Include(orderItem => orderItem.OrderItems).ThenInclude(inventory => inventory.Inventory).ThenInclude(product => product.Product).ThenInclude(image => image.ProductImages) .Include(orderItem => orderItem.OrderItems).ThenInclude(inventory => inventory.Inventory).ThenInclude(platform => platform.GamePlatform) .Where(o => o.User.UserId == userId).ToArray()); }
public CheckoutController(WebshopDbContext context, SignInManager <ApplicationUser> signInManager, UserManager <ApplicationUser> userManager, AddressService addressService, CartService cartService, CheckoutService checkoutService) { _context = context; _signInManager = signInManager; _userManager = userManager; _addressService = addressService; _cartService = cartService; _checkoutService = checkoutService; }
public static List <Product> GetProducts(WebshopDbContext db) { return(db.Product.Include(inventory => inventory.Inventories) .ThenInclude(platform => platform.GamePlatform) .Include(images => images.ProductImages) .Include(features => features.ProductFeatures) .Include(publisher => publisher.Publisher) .Where(product => product.Inventories.Any(inventory => inventory.ProductId == product.ProductId)) .ToList()); }
public static ShoppingCart ShoppingCartWishList(ClaimsPrincipal user, WebshopDbContext db) { WishList wishList = WishListService.GetWishList(user, db); if (wishList == null) { return(null); } return(WishListToShoppingCart(wishList)); }
public ProcessManager( WebshopDbContext db, PaymentClient paymentClient, MailerClient mailerClient, ILogger <ProcessManager> logger) { _db = db; _paymentClient = paymentClient; _mailerClient = mailerClient; _logger = logger; }
public static WishList GetWishList(ClaimsPrincipal user, WebshopDbContext db) { string guidString = user.Claims.Where(claim => claim.Type == ClaimTypes.Sid).Select(s => s.Value).SingleOrDefault(); if (!Guid.TryParse(guidString, out Guid userId)) { return(null); } return(db.WishList.Include(wi => wi.WishListItems).ThenInclude(wi => wi.Inventory).ThenInclude(wi => wi.GamePlatform) .Include(wi => wi.WishListItems).ThenInclude(wi => wi.Inventory).ThenInclude(wi => wi.Product).ThenInclude(p => p.ProductImages). FirstOrDefault(u => u.UserId == userId)); }
public static (List <string>, List <int>) OrdersPerDateCountv1(WebshopDbContext db) { var orderDateTimeArray = db.Order.Select(x => x.Date).Distinct().ToArray(); var orderDatesToStringsList = new List <string>(); var orderCountList = new List <int>(); foreach (DateTime item in orderDateTimeArray) { orderDatesToStringsList.Add(item.ToShortDateString()); orderCountList.Add(db.Order.Count(x => x.Date == item)); } return(orderDatesToStringsList, orderCountList); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WebshopDbContext context) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseStaticFiles(); DbInitializer.Initialize(context); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, HotModuleReplacementEndpoint = "/dist/__webpack_hmr" }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.MapWhen(x => !x.Request.Path.Value.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase), builder => { builder.UseMvc(routes => { routes.MapSpaFallbackRoute( "spa-fallback", new { controller = "Home", action = "Index" }); }); }); } else { app.UseMvc(routes => { routes.MapRoute( "default", "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( "Sitemap", "sitemap.xml", new { controller = "Home", action = "SitemapXml" }); routes.MapSpaFallbackRoute( "spa-fallback", new { controller = "Home", action = "Index" }); }); app.UseExceptionHandler("/Home/Error"); } }
private static WishList CreateWishList(Guid userId, WebshopDbContext db) { // return new WishList(){ // Name="Default", // UserId = userId, // }; db.WishList.Add(new WishList() { Name = "Default", UserId = userId, }); db.SaveChanges(); return(db.WishList.FirstOrDefault(w => w.UserId == userId)); }
public static (List <string>, List <int>) ProductSalesPerRegio(WebshopDbContext db, DateTime startDate, DateTime endDate) { var orderCount = new List <int>(); var cities = (from t in db.Order select t.City).Distinct().ToList(); var orders = db.Order.ToList(); foreach (var city in cities) { orderCount.Add(orders.Count(t => t.City == city)); } return(cities, orderCount); }
public static bool ChangePassword(ClaimsPrincipal user, string password, WebshopDbContext db) { string guidString = user.Claims.Where(claim => claim.Type == ClaimTypes.Sid).Select(s => s.Value).SingleOrDefault(); if (!Guid.TryParse(guidString, out Guid userId)) { return(false); } User u = UserService.GetUser(userId, db); u.Password = Hashing.HashPassword(password); db.Update(u); db.SaveChanges(); return(true); }
public HomeController(WebshopDbContext context, ILogger <HomeController> logger) { this.context = context; _logger = logger; /* * //Product prod = context.Products.Include(x => x.Categories).AsNoTracking().FirstOrDefault(x => x.Name == "Tej"); * Product prod = context.Products.FirstOrDefault(x => x.Name == "Tej"); * //Category cat = context.Categories.FirstOrDefault(x => x.Name == "Tejtermékek"); * Category cat = context.Categories.FirstOrDefault(x => x.Name == "Tejtermékek"); * CategoryProduct tmp = new CategoryProduct(cat, prod); * prod.Categories.Add(tmp); * //context.Products.Add(prod); * int result = context.SaveChanges(); */ }
/// <summary> /// Performs a login towards the in proc session server. /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <param name="db"></param> /// <param name="claims"></param> /// <returns>returns true on succeeded or false on failed..., also puts out an SessionId that is generated by the session handler</returns> public static bool Login(string email, string password, WebshopDbContext db, out List <Claim> claims) { User user = db.User.Include(role => role.UserRole).FirstOrDefault(u => u.Email == email); if (user != null && Hashing.ValidatePassword(password, user.Password)) { claims = new List <Claim> { new Claim(ClaimTypes.Sid, user.UserId.ToString()), new Claim(ClaimTypes.Role, user.UserRole.RoleName) }; return(true); } claims = default(List <Claim>); return(false); }
public ManageController( UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, IEmailSender emailSender, ILogger <ManageController> logger, UrlEncoder urlEncoder, AddressService addressService, WebshopDbContext context) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _logger = logger; _urlEncoder = urlEncoder; _addressService = addressService; _context = context; }
public static async Task <List <Product> > GetSearchProducts(string query, WebshopDbContext db) { var products = await db.Product.Include(p => p.GameType).Include(p => p.PGRating).Include(p => p.Publisher) .Include(p => p.ProductImages).Include(p => p.Inventories).ThenInclude(i => i.GamePlatform) .Include(p => p.ProductFeatures) .Where( p => p.Name.Contains(query) || p.GameType.GenreName.Contains(query) || p.ProductFeatures.Any(f => f.Feature.Contains(query)) || p.Publisher.PublisherName.Contains(query) || p.Inventories.Any(i => i.GamePlatform.PlatformName.Contains(query)) || p.Description.Contains(query) ).ToListAsync(); products.RemoveAll(i => i.Inventories.Count < 1); return(SelectiveSearchList(query, products).ToList()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, WebshopDbContext context, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager, AddressService addressService, ILoggerFactory loggerFactory) { loggerFactory.AddAzureWebAppDiagnostics(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); if (_hostingEnvironment.IsProduction() || _hostingEnvironment.IsStaging() || _hostingEnvironment.EnvironmentName == "IntegratedDb" || _hostingEnvironment.EnvironmentName == "LocalSql") { context.Database.Migrate(); } DbInitialiser.Initialise(context, userManager, roleManager, addressService); }
/// <summary> /// Registers a new user to the database , checks if the user already exists , also hashes the password /// </summary> /// <param name="user"></param> /// <param name="db"></param> /// <returns>true if succeeded or false if failed</returns> public static bool Register(User user, WebshopDbContext db) { //if email exists then return false indicating that no user could be created if (!db.User.Any(u => user.Email == u.Email)) { //hash the password here user.Password = Hashing.HashPassword(user.Password); user.CityId = 1; user.RoleId = 1; try { db.User.Add(user); db.SaveChanges(); return(true); } catch (DbUpdateException e) { Debug.WriteLine(e.StackTrace); return(false); } } return(false); }
public static (List <string>, List <int>) ProductSalesTotal(WebshopDbContext db, DateTime startDate, DateTime endDate) { var query = from o in db.Order.ToList() join i in db.OrderItem.ToList() on o.OrderId equals i.OrderId where o.Date >= startDate && o.Date <= endDate group i.Amount by o.Date into g select new { Date = g.Key, SoldAmount = g.Sum() }; var datesList = new List <string>(); var amountsList = new List <int>(); foreach (var item in query) { datesList.Add(item.Date.ToShortDateString()); amountsList.Add(item.SoldAmount); } return(datesList, amountsList); }
public static (List <string>, List <float>) ProductRevenueTotal(WebshopDbContext db, DateTime startDate, DateTime endDate) { var query = from o in db.Order.ToList() join i in db.OrderItem.ToList() on o.OrderId equals i.OrderId where o.Date >= startDate && o.Date <= endDate group i.PriceBought by o.Date into g select new { Date = g.Key, PriceBought = g.Sum() }; var datesList = new List <string>(); var revenueList = new List <float>(); foreach (var item in query) { datesList.Add(item.Date.ToShortDateString()); revenueList.Add(item.PriceBought); } return(datesList, revenueList); }
public static bool AddInventory(int inventoryId, ClaimsPrincipal user, WebshopDbContext db) { //TODO: Check if theres a wishlist for that user. Else create a new one //TODO: Update wishlist item if there is one , else create a new one string guidString = user.Claims.Where(claim => claim.Type == ClaimTypes.Sid).Select(s => s.Value).SingleOrDefault(); if (!Guid.TryParse(guidString, out Guid userId)) { return(false); } WishList wishList = db.WishList.Include(wi => wi.WishListItems).FirstOrDefault(w => w.UserId == userId) ?? CreateWishList(userId, db); if (wishList == null) { return(false); } if (wishList.WishListItems == null || wishList.WishListItems.Count <= 0) { db.WishListItem.Add(NewWishListItem(wishList.WishListId, inventoryId)); } else { WishListItem wishListItem = wishList.WishListItems.FirstOrDefault(i => i.InventoryId == inventoryId && i.WishListId == wishList.WishListId); if (wishListItem != null) { wishListItem.Amount++; } else { db.WishListItem.Add(NewWishListItem(wishList.WishListId, inventoryId)); } } db.SaveChanges(); return(true); }
public static bool RemoveInventory(int inventoryId, ClaimsPrincipal user, WebshopDbContext db) { string guidString = user.Claims.Where(claim => claim.Type == ClaimTypes.Sid).Select(s => s.Value).SingleOrDefault(); if (!Guid.TryParse(guidString, out Guid userId)) { return(false); } WishList wishList = db.WishList.Include(wi => wi.WishListItems).FirstOrDefault(w => w.UserId == userId); if (wishList == null) { return(false); } WishListItem toBeRemoved = db.WishListItem.FirstOrDefault(wi => wi.InventoryId == inventoryId && wishList.WishListId == wi.WishListId); if (toBeRemoved == null) { return(false); } wishList.WishListItems.Remove(toBeRemoved); db.SaveChanges(); return(true); }
public UsersController(WebshopDbContext context) { _context = context; }
public IngredientController(WebshopDbContext context, IngredientService ingredientService) { _context = context; _ingredientService = ingredientService; }
public static bool ChangeAddress(ClaimsPrincipal user, ChangeAddressViewModel addressViewModel, WebshopDbContext db) { string guidString = user.Claims.Where(claim => claim.Type == ClaimTypes.Sid).Select(s => s.Value).SingleOrDefault(); if (!Guid.TryParse(guidString, out Guid userId)) { return(false); } User u = UserService.GetUser(userId, db); u.Street = addressViewModel.Street; u.PostalCode = addressViewModel.PostalCode; db.Update(u); db.SaveChanges(); return(true); }
public static bool UserExists(Guid id, WebshopDbContext db) { return(db.User.Any(e => e.UserId == id)); }
public static User GetUser(Guid userId, WebshopDbContext db) { return(db.User.FirstOrDefault(u => u.UserId == userId)); }