public IHttpResponse AddToCart(IHttpRequest req) { var id = int.Parse(req.UrlParameters["id"]); Product cake = default(Product); using (var db = new ByTheCakeContext()) { cake = db.Products.FirstOrDefault(x => x.Id == id); } if (cake == null) { return(new NotFoundResponse()); } var shoppingCart = req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey); shoppingCart.Orders.Add(cake); var redirectUrl = "/search"; const string searchTermKey = "searchTerm"; if (req.UrlParameters.ContainsKey(searchTermKey)) { redirectUrl = $"{redirectUrl}?{searchTermKey}={req.UrlParameters[searchTermKey]}"; } return(new RedirectResponse(redirectUrl)); }
public IHttpResponse CakeDetails(IHttpRequest req) { var id = int.Parse(req.UrlParameters["id"]); Product productToView = default(Product); using (ByTheCakeContext context = new ByTheCakeContext()) { productToView = context.Products.FirstOrDefault(x => x.Id == (id)); } if (productToView == default(Product)) { this.ViewData["error"] = "No such product."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"cakes\search")); } this.ViewData["name"] = productToView.Name; this.ViewData["price"] = productToView.Price.ToString("F2"); this.ViewData["imageUrl"] = productToView.ImageURL; return(this.FileViewResponse(@"/cakes/cake-details")); }
public IHttpResponse ShowCart(IHttpRequest req) { int userId = req.Session.Get <int>(SessionStore.CurrentUserKey); using (var context = new ByTheCakeContext()) { var orders = context .Orders .Where(o => o.UserId == userId) .ToList(); if (!orders.Any()) { this.ViewData["cartItems"] = "No items in your cart."; this.ViewData["totalCost"] = "0.00"; } else { var products = context.ProductOrders .Where(po => orders.Any(o => o.Id == po.OrderId)) .Select(p => new { p.Product.Name, p.Product.Price }) .ToList(); var htmlString = products .Select(po => $"<div>{po.Name} - ${po.Price:F2}</div>"); var totalPrice = products.Sum(p => p.Price); this.ViewData["cartItems"] = string.Join(string.Empty, htmlString); this.ViewData["totalCost"] = totalPrice.ToString("F2"); } } return(this.FileViewResponse(@"shopping\cart")); }
public void InitializeDatabase() { using (var db = new ByTheCakeContext()) { db.Database.Migrate(); } }
public IHttpResponse Orders(IHttpRequest req) { var currentUserId = req.Session.Get <int>(SessionStore.CurrentUserKey); string result = "No Orders Created"; using (var context = new ByTheCakeContext()) { var orders = context .Orders.Where(o => o.UserId == currentUserId) .OrderByDescending(o => o.DateOfCreation) .ToList(); if (orders.Any()) { result = ""; } foreach (var order in orders) { List <Product> orderProducts = context.ProductOrders .Where(po => po.ProductId == order.Id) .Select(po => po.Product) .ToList(); decimal sum = orderProducts.Sum(op => op.Price); result += $@"<tr><td><a href=""/orderDetails/{order.Id}"">{order.Id}</a></td><td>{order.DateOfCreation.ToString("dd-MM-yyyy")}</td><td>${sum}</td></tr>"; } } this.ViewData["result"] = result; return(this.FileViewResponse(@"home\orders")); }
public void InitalizeDatabase() { using (var context = new ByTheCakeContext()) { context.Database.Migrate(); } }
public IHttpResponse Add(IHttpRequest req) { string name = req.FormData["name"]; decimal price = decimal.Parse(req.FormData["price"]); string imageUrl = req.FormData["imageUrl"]; var product = new Product { Name = name, Price = price, ImageUrl = imageUrl }; using (var context = new ByTheCakeContext()) { context.Products.Add(product); context.SaveChanges(); } this.ViewData["name"] = name; this.ViewData["price"] = price.ToString("f2"); this.ViewData["imageUrl"] = imageUrl; this.ViewData["showResult"] = "block"; return(this.FileViewResponse(@"cakes\add")); }
public IHttpResponse OrderDetails(IHttpRequest req) { int orderId = int.Parse(req.UrlParameters["id"]); using (var context = new ByTheCakeContext()) { const string productLine = "<tr>" + "<td><a href=\"/cakes/details/{0}\">{1}</a></td>" + "<td>${2:F2}</td>" + "</tr>"; var products = context .ProductOrders .Where(po => po.OrderId == orderId) .Select(p => string.Format( productLine, p.Product.Id, p.Product.Name, p.Product.Price )) .ToList(); this.ViewData["orderId"] = orderId.ToString(); this.ViewData["products"] = string.Join("", products); } return(this.FileViewResponse(@"cakes\orderDetails")); }
public IHttpResponse Profile(IHttpRequest req) { int userId = req.Session.Get <int>(SessionStore.CurrentUserKey); User profileToView = default(User); using (ByTheCakeContext context = new ByTheCakeContext()) { profileToView = context.Users.FirstOrDefault(x => x.Id.Equals(userId)); } if (profileToView == default(User)) { this.ViewData["error"] = "Nice try to hack me."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\register")); } this.ViewData["name"] = profileToView.Name; this.ViewData["registerDate"] = profileToView.RegistrationDate.ToString(string.Format("MM-dd-yyyy")); this.ViewData["ordersCount"] = profileToView.Orders.Count().ToString(); return(this.FileViewResponse(@"account\profile")); }
public IHttpResponse Orders(IHttpRequest req) { const string tableContentKey = "tableContent"; var userId = req.Session.Get <int>(SessionStore.CurrentUserKey); string tableData = ""; using (var db = new ByTheCakeContext()) { var orders = db.Orders .Include(x => x.Products) .ThenInclude(x => x.Product) .Where(o => o.UserId == userId) .ToList(); tableData = string.Join("", orders.Select(o => $"<tr><td><a href=\"/orderDetails/{o.Id}\">{ o.Id}</a></td><td>{ o.CreationDate.ToString("dd-MM-yyyy")}</td><td>${ o.Products.Sum(x => x.Product.Price).ToString("F2")}</td></tr >")); } if (string.IsNullOrEmpty(tableData)) { this.ViewData["error"] = "<h2>You have no orders</h2>"; this.ViewData["showResult"] = "none"; this.ViewData["showError"] = "block"; } else { this.ViewData[tableContentKey] = tableData; this.ViewData["showResult"] = "block"; this.ViewData["showError"] = "none"; } return(this.FileViewResponse(@"account\my-orders")); }
public bool Exists(int id) { using (var db = new ByTheCakeContext()) { return(db.Products.Any(pr => pr.Id == id)); } }
public IHttpResponse Register(IHttpRequest req) { const string formNameKey = "name"; const string formUsernameKey = "username"; const string formPasswordKey = "password"; const string formConfirmPasswordKey = "confirmpassword"; if (!req.FormData.ContainsKey(formNameKey) || !req.FormData.ContainsKey(formUsernameKey) || !req.FormData.ContainsKey(formPasswordKey) || !req.FormData.ContainsKey(formConfirmPasswordKey)) { RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } var name = req.FormData[formNameKey]; var username = req.FormData[formUsernameKey]; var password = req.FormData[formPasswordKey]; var confirmpassword = req.FormData[formConfirmPasswordKey]; if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(confirmpassword)) { RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } if (name.Length < 3 || username.Length < 3) { RejectLoginAttempt(NAME_AND_USERNAME_VALIDATION_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } if (password != confirmpassword) { RejectLoginAttempt(PASSWORD_MATCH_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } User user = new User() { Name = name, Username = username, PasswordHash = PasswordUtilities.GenerateHash256(password), DateOfRegistration = DateTime.UtcNow }; using (var context = new ByTheCakeContext()) { context.Users.Add(user); context.SaveChanges(); } return(LoginUser(req, user)); }
public IHttpResponse Search(IHttpRequest req) { var urlParameters = req.UrlParameters; var results = string.Empty; this.ViewData["showCart"] = "none"; this.ViewData["showResult"] = "none"; this.ViewData["searchTerm"] = string.Empty; if (urlParameters.ContainsKey("searchTerm")) { var searchTerm = urlParameters["searchTerm"]; this.ViewData["searchTerm"] = searchTerm; List <string> cakeResults = null; using (var context = new ByTheCakeContext()) { cakeResults = context.Products .Where(p => p.Name.ToLower().Contains(searchTerm.ToLower())) .Select(c => $"<div><a href=\"/cakes/details/{c.Id}\">{c.Name}</a> - ${c.Price:F2} <a href=\"/shopping/add/{c.Id}?searchTerm={searchTerm}\">Order</a></div>") .ToList(); } results = "No cakes found!"; if (cakeResults.Any()) { results = string.Join(Environment.NewLine, cakeResults); } this.ViewData["results"] = results; } using (var context = new ByTheCakeContext()) { var id = req.Session.Get <int>(SessionStore.CurrentUserKey); var user = context.Users.Include(u => u.Orders).FirstOrDefault(u => u.Id == id); var orders = user.Orders; if (orders.Any()) { var totalProducts = orders.Count; var totalProductsText = totalProducts != 1 ? "products" : "product"; this.ViewData["showCart"] = "block"; this.ViewData["products"] = $"{totalProducts} {totalProductsText}"; } } if (!string.IsNullOrEmpty(results)) { this.ViewData["showResult"] = "block"; } return(this.FileViewResponse(@"cakes\search")); }
public IHttpResponse FinishOrder(IHttpRequest req) { //Register order in the database var currentUserId = req.Session.Get <int>(SessionStore.CurrentUserKey); //purvo slagame ordera using (var context = new ByTheCakeContext()) { User currentUser = context.Users.Find(currentUserId); var shoppingCart = req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey); List <int> itemsIds = shoppingCart .Orders .Select(i => i.Id).ToList(); List <Product> productItems = new List <Product>(); foreach (var id in itemsIds) { Product product = context.Products.Find(id); productItems.Add(product); } //Suzdavam nov order Order order = new Order { DateOfCreation = DateTime.UtcNow, UserId = currentUserId }; context.Orders.Add(order); //za vseki produkt v karta suzdavam nov ProductOrder foreach (int id in itemsIds) { Product item = context.Products.Find(id); ProductOrder productOrder = new ProductOrder { Order = order, Product = item }; context.ProductOrders.Add(productOrder); } context.SaveChanges(); } req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey).Orders.Clear(); return(this.FileViewResponse(@"shopping\finish-order")); }
private static void ConfigureDatabase() { //INICIALIZIRAME SI BAZATA TUK ZA DA Q POLZVAME var context = new ByTheCakeContext(); //Taka Pravim migraciqta Obache trqbva da q napravim smo vednuj a ne vseki put context.Database.Migrate(); }
private static void ConfigureDatabase() { using (var context = new ByTheCakeContext()) { context.Database.EnsureDeleted(); context.Database.Migrate(); } }
public IHttpResponse FinishOrder(IHttpRequest req) { var shoppingCart = req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey); int userId = req.Session.Get <int>(SessionStore.CurrentUserKey); User user = default(User); int orderId = -10; HashSet <Product> products = shoppingCart.Orders.ToHashSet(); HashSet <ProductOrder> mappingTable = new HashSet <ProductOrder>(); using (var db = new ByTheCakeContext()) { user = db.Users.FirstOrDefault(x => x.Id == userId); if (user == default(User)) { this.ViewData["error"] = "Nice try to hack me."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\register")); } DateTime exactTime = DateTime.UtcNow; Order order = new Order() { UserId = user.Id, User = user, CreationDate = exactTime }; db.Orders.Add(order); db.SaveChanges(); orderId = order.Id; foreach (var product in products) { int productId = product.Id; Product productDb = db.Products.FirstOrDefault(x => x.Id == productId); ProductOrder productOrder = new ProductOrder() { OrderId = orderId, ProductId = productId }; order.Products.Add(productOrder); productDb.Orders.Add(productOrder); db.SaveChanges(); } } req.Session.Get <ShoppingCart>(ShoppingCart.SessionKey).Orders.Clear(); return(this.FileViewResponse(@"shopping\finish-order")); }
public void Configure(IAppRouteConfig appRouteConfig) { var context = new ByTheCakeContext(); context.Database.Migrate(); appRouteConfig .Get("/", req => new HomeController().Index()); appRouteConfig .Get("/about", req => new HomeController().About()); appRouteConfig .Get("/add", req => new CakesController().Add()); appRouteConfig .Post( "/add", req => new CakesController().Add(req.FormData["name"], req.FormData["price"])); appRouteConfig .Get( "/search", req => new CakesController().Search(req)); appRouteConfig .Get( "/login", req => new AccountController().Login()); appRouteConfig .Post( "/login", req => new AccountController().Login(req)); appRouteConfig .Get("/register", req => new HomeController().Register()); appRouteConfig .Post( "/logout", req => new AccountController().Logout(req)); appRouteConfig .Get( "/shopping/add/{(?<id>[0-9]+)}", req => new ShoppingController().AddToCart(req)); appRouteConfig .Get( "/cart", req => new ShoppingController().ShowCart(req)); appRouteConfig .Post( "/shopping/finish-order", req => new ShoppingController().FinishOrder(req)); }
public bool Find(string username, string password) { using (var db = new ByTheCakeContext()) { return(db .Users .Any(u => u.Username == username && u.Password == password)); } }
public Order GetOrder(int id) { using (var db = new ByTheCakeContext()) { var order = db.Orders .FirstOrDefault(o => o.Id == id); return(order); } }
// Post public IHttpResponse Register(IHttpRequest request) { const string formNameKey = "name"; const string formUsernameKey = "username"; const string formPasswordKey = "password"; const string formConfirmPasswordKey = "confirm-password"; if (!request.FormData.ContainsKey(formNameKey) || !request.FormData.ContainsKey(formUsernameKey) || !request.FormData.ContainsKey(formPasswordKey) || !request.FormData.ContainsKey(formConfirmPasswordKey)) { return(new BadRequestResponse()); } string name = request.FormData[formNameKey]; string username = request.FormData[formUsernameKey]; string password = request.FormData[formPasswordKey]; string confirmPassword = request.FormData[formConfirmPasswordKey]; if ((string.IsNullOrEmpty(name) || name.Length < 3) || (string.IsNullOrEmpty(username) || username.Length < 3) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(confirmPassword) || password != confirmPassword) { return(new RedirectResponse("/register")); } User user = null; using (var context = new ByTheCakeContext()) { if (context.Users.Any(u => u.Username == username)) { return(new RedirectResponse("/register")); } user = new User() { Name = name, Username = username, PasswordHash = PasswordUtilities.ComputeHash(password), RegistrationDate = DateTime.UtcNow }; context.Users.Add(user); context.SaveChanges(); } return(CompleteLogin(request, user.Id)); }
public IHttpResponse AddToCart(IHttpRequest req) { if (!req.UrlParameters.ContainsKey("id")) { return(new NotFoundResponse()); } var id = int.Parse(req.UrlParameters["id"]); using (var context = new ByTheCakeContext()) { Product cake = context.Products.Find(id); if (cake == null) { return(new NotFoundResponse()); } var userId = req.Session.Get <int>(SessionStore.CurrentUserKey); var user = context.Users.Find(userId); var order = new Order() { User = user, DateOfCreation = DateTime.UtcNow }; var productOrder = new ProductOrder() { Order = order, Product = cake }; order.Products.Add(productOrder); cake.Orders.Add(productOrder); user.Orders.Add(order); context.SaveChanges(); } var redirectUrl = "/search"; const string searchTermKey = "searchTerm"; if (req.UrlParameters.ContainsKey(searchTermKey)) { redirectUrl = $"{redirectUrl}?{searchTermKey}={req.UrlParameters[searchTermKey]}"; } return(new RedirectResponse(redirectUrl)); }
public int?GetUserId(string username) { using (var db = new ByTheCakeContext()) { var id = db .Users .Where(u => u.Username == username) .Select(u => u.Id) .FirstOrDefault(); return(id != 0 ? (int?)id : null); } }
public IEnumerable <ProductInCartViewModel> FindProductsInCart(IEnumerable <int> ids) { using (var db = new ByTheCakeContext()) { return(db.Products .Where(pr => ids.Contains(pr.Id)) .Select(pr => new ProductInCartViewModel { Name = pr.Name, Price = pr.Price }) .ToList()); } }
public void Create(string name, decimal price, string imageUrl) { using (var db = new ByTheCakeContext()) { var product = new Product { Name = name, Price = price, ImageUrl = imageUrl }; db.Add(product); db.SaveChanges(); } }
public ProductDetailsViewModel Find(int id) { using (var db = new ByTheCakeContext()) { return(db.Products .Where(pr => pr.Id == id) .Select(pr => new ProductDetailsViewModel { Name = pr.Name, Price = pr.Price, ImageUrl = pr.ImageUrl }) .FirstOrDefault()); } }
public IHttpResponse About(IHttpRequest req) { var currentUserId = req.Session.Get <int>(SessionStore.CurrentUserKey); using (var context = new ByTheCakeContext()) { User currentUser = context.Users.Find(currentUserId); if (currentUser != null) { this.ViewData["name"] = currentUser.Name; } } return(this.FileViewResponse(@"home\about")); }
public ProfileViewModel Profile(string username) { using (var db = new ByTheCakeContext()) { return(db .Users .Where(u => u.Username == username) .Select(u => new ProfileViewModel { Username = u.Username, RegistrationDate = u.RegistrationDate, TotalOrders = u.Orders.Count() }) .FirstOrDefault()); } }
public IHttpResponse OrderDetails(IHttpRequest req) { int orderId = int.Parse(req.UrlParameters["id"]); decimal orderSum = 0; string result = ""; Order order = null; using (var context = new ByTheCakeContext()) { order = context.Orders .FirstOrDefault(c => c.Id == orderId); if (order == null) { return(new BadRequestResponse()); } //Selektirame idtata na productite ot tozi order List <int> productIds = context.ProductOrders .Where(p => p.ProductId == orderId) .Select(p => p.OrderId).ToList(); //vzimame vsichki produkti List <Product> products = context.Products .Where(p => productIds.Contains(p.Id)) .ToList(); for (int i = 0; i < products.Count; i++) { var product = products[i]; orderSum += product.Price; int count = i + 1; result += $@"<tr><th scope=""row"">{count}</th><td><a href=""/cakeDetails/{product.Id}"">{product.Name}</a></td><td>${product.Price.ToString("F2")}</td></tr>"; } } this.ViewData["id"] = order.Id.ToString(); this.ViewData["result"] = result; this.ViewData["orderSum"] = orderSum.ToString("F2"); this.ViewData["creationDate"] = order.DateOfCreation.ToString("dd-MM-yyyy"); return(this.FileViewResponse(@"cakes\orderDetails")); }
// GET public IHttpResponse Orders(IHttpRequest req) { const string table = "<table class=\"table\" border=\"1\">" + "<thead class=\"thead-dark\">" + "<tr>" + "<th>Order Id</th>" + "<th>Created On</th>" + "<th>Sum</th>" + "</tr>" + "{0}" + "</thead>" + "</table>"; const string orderLine = "<tr>" + "<td><a href=\"cakes/orderDatails/{0}\">{0}</a></td>" + "<td>{1}</td>" + "<td>${2:F2}</td>" + "</tr>"; int id = req.Session.Get <int>(SessionStore.CurrentUserKey); using (var context = new ByTheCakeContext()) { var orderLines = context .Orders .Where(o => o.UserId == id) .Select(o => string.Format(orderLine, o.Id, o.DateOfCreation.ToShortDateString(), o.Products.Sum(p => p.Product.Price) )) .ToList(); if (orderLines.Count == 0) { this.ViewData["orders"] = "<h3>No orders found.</h3>"; } else { this.ViewData["orders"] = string.Format(table, string.Join("", orderLines)); } } return(this.FileViewResponse("cakes/orders")); }