public FakeUnitOfWork(DbContextOptions options)
 {
     _context = new WebShopContext(options);;
     Category = new CategoryRepo(_context);
     Product  = new FakeProductRepo(_context);
     Order    = new FakeOrderRepo(_context);
 }
Esempio n. 2
0
        /// <summary>
        /// Tar bort en bok.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden tar fram boken genom Id och kollar så att boken inte är null. Bokens antal/amount minskas med 1.
        /// Om antalet av boken därefter är 0 eller mindre så tas boken bort helt från databasen.
        /// </summary>
        /// <param name="adminId">Användarens/Administratörens Id</param>
        /// <param name="bookId">Användarens/Administratörens Id</param>
        /// <returns>Returnerar true om boken inte är null och om antalet/amount är mindre eller lika med 0, annars false</returns>
        public bool DeleteBook(int adminId, int bookId)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var book = db.Books.FirstOrDefault(b => b.Id == bookId);
                    if (book != null)
                    {
                        book.Amount -= 1;
                        if (book.Amount <= 0)
                        {
                            db.Remove(book);
                            db.Update(book);
                            db.SaveChanges();
                            return(true);
                        }
                        return(true);
                    }
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 3
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new WebShopContext())
            {
                //get comment
                var comment = db.Comments
                              .Where(c => c.Id == id)
                              .First();

                if (!IsAuthor(comment))
                {
                    if (!IsAdmin(comment))
                    {
                        return(RedirectToAction("List", "Product"));
                    }
                }

                //check if exists
                if (comment == null)
                {
                    return(HttpNotFound());
                }
                //pass to the view
                return(View(comment));
            }
        }
Esempio n. 4
0
        public ActionResult GetProducts(int categoryId, int?page, string search, string orderBy)
        {
            //ViewBag.OrderName = string.IsNullOrEmpty(orderBy) ? "NameDesc" : "";
            // ViewBag.OrderPrice = orderBy == "Price" ? "PriceDesc" : "Price";
            WebShopContext db       = new WebShopContext();
            var            products = db.Products.Where(x => x.CategoryId == categoryId).AsQueryable();

            if (string.IsNullOrEmpty(search) == false)
            {
                products = products.Where(p => p.Name.ToUpper().StartsWith(search.ToUpper()));
            }
            switch (orderBy)
            {
            case "NameDesc":
                products = products.OrderByDescending(p => p.Name);
                break;

            case "Price":
                products = products.OrderBy(p => p.Price);
                break;

            case "PriceDesc":
                products = products.OrderByDescending(p => p.Price);
                break;

            default:
                products = products.OrderBy(p => p.Name);
                break;
            }
            return(View(products.ToList().ToPagedList(page ?? 1, 3)));
        }
Esempio n. 5
0
 public ProductController(WebShopContext context, IProduct productService, ICart cartService, UserManager <ShopUser> userManager)
 {
     _context        = context;
     _productService = productService;
     _cartService    = cartService;
     _userManager    = userManager;
 }
Esempio n. 6
0
        public ActionResult Edit(CommentViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new WebShopContext())
                {
                    //get comment
                    var comment = db.Comments
                                  .FirstOrDefault(p => p.Id == model.Id);

                    var productId = comment.ProductId;

                    //set the same props
                    comment.Id      = model.Id;
                    comment.Content = model.Content;

                    //save in db
                    db.Entry(comment).State = EntityState.Modified;
                    db.SaveChanges();

                    //redirect to /product/details/productID
                    return(RedirectToAction("Details", "Product", new { id = productId }));
                }
            }

            return(View(model));
        }
Esempio n. 7
0
 public UsersApiController(WebShopContext context)
 {
     _userStore = new UserStore <ApplicationUser>(context)
     {
         AutoSaveChanges = true
     };
 }
Esempio n. 8
0
        /// <summary>
        /// Lägger till ett kategori-Id till en bok.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden kollar om boken och kategorin existerar i databasen genom Id.
        /// Om både boken och kategorin inte är null så läggs categoryId till i bokens property categoryId och sparas.
        /// </summary>
        /// <param name="adminId">Admins Id</param>
        /// <param name="bookId">Bokens Id</param>
        /// <param name="categoryId">Kategorins Id</param>
        /// <returns>Returnerar true om boken och kategorin inte är null, annars false</returns>
        public bool AddBookToCategory(int adminId, int bookId, int categoryId)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var book     = db.Books.FirstOrDefault(b => b.Id == bookId);
                    var category = db.Categories.FirstOrDefault(c => c.Id == categoryId);
                    if (book != null && category != null)
                    {
                        book.CategoryId = category.Id;
                        db.Update(book);
                        db.SaveChanges();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                using (IServiceScope scope = app.ApplicationServices.CreateScope())
                {
                    WebShopContext ctx = scope.ServiceProvider.GetService <WebShopContext>();
                    DBInitializer.SeedDB(ctx);
                }
                app.UseDeveloperExceptionPage();
            }
            else
            {
                using (IServiceScope scope = app.ApplicationServices.CreateScope())
                {
                    WebShopContext ctx = scope.ServiceProvider.GetService <WebShopContext>();
                    ctx.Database.EnsureCreated();
                }

                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseAuthentication();

            //app.UseCors(builder => builder.WithOrigins("https://ipcsmmd-webshop-group16.azurewebsites.net").AllowAnyMethod().AllowAnyHeader());
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseMvc();
        }
 public HomeController(WebShopContext _db, IShoppingCart _shoppingcart, ShoppingCart _shop, IStringLocalizer <Globalization> localizer) : base(_db)
 {
     _webc      = _db;
     shoppingc  = _shoppingcart;
     shop       = _shop;
     _localizer = localizer;
 }
        public AccountService(WebShopContext context,
                              IHttpContextAccessor httpContextAccessor)
        {
            _context     = context;
            _httpContext = httpContextAccessor.HttpContext;
            //_httpContext.Response.Cookies.Delete("user_challenge");

            // ha a felhasználónak van sütije, de még nincs bejelentkezve, bejelentkeztetjük
            if (_httpContext.Request.Cookies.ContainsKey("user_challenge") &&
                !_httpContext.Session.Keys.Contains("user"))
            {
                Basket user = _context.Baskets.FirstOrDefault(
                    g => g.UserName == _httpContext.Request.Cookies["user_challenge"]);

                // kikeressük a felhasználót
                if (user != null)
                {
                    _httpContext.Session.SetString("user", user.UserName);
                }
            }
            else if (!_httpContext.Session.Keys.Contains("user"))
            {
                Create();
            }
        }
 public CartController(WebShopContext _db, IShoppingCart _shoppingcart, ShoppingCart _shop)
     : base(_db)
 {
     _webc     = _db;
     shoppingc = _shoppingcart;
     shop      = _shop;
 }
Esempio n. 13
0
        public ActionResult DeleteConfirmed(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new WebShopContext())
            {
                //get products
                var product = db.Products
                              .Where(p => p.Id == id)
                              .First();

                if (!IsUserAuthorizedToEdit(product))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
                }

                //check if exists
                if (product == null)
                {
                    return(HttpNotFound());
                }

                //remove product
                db.Products.Remove(product);
                db.SaveChanges();

                //redirect to /product/list
                return(RedirectToAction("List"));
            }
        }
Esempio n. 14
0
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new WebShopContext())
            {
                //get products
                var product = db.Products
                              .Where(p => p.Id == id)
                              .First();

                if (!IsUserAuthorizedToEdit(product))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
                }

                //check if exists
                if (product == null)
                {
                    return(HttpNotFound());
                }
                //pass to the view
                return(View(product));
            }
        }
        public ActionResult AddProductConfirmed(int?id)
        {
            using (var db = new WebShopContext())
            {
                ApplicationUser user = CurrentUser();

                if (id == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                var product = db.Products.FirstOrDefault(p => p.Id == id);

                if (product == null)
                {
                    return(HttpNotFound());
                }

                db.Users.Attach(user);
                if (user.Cart == null)
                {
                    Cart cart = new Cart();
                    db.Carts.Add(cart);
                    db.SaveChanges();
                    user.Cart   = cart;
                    cart.User   = user;
                    cart.UserId = user.Id;
                }
                user.Cart.Products.Add(product);
                db.SaveChanges();

                return(RedirectToAction("List"));
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Lägger in en eller flera böcker i databasen.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden kollar om boken existerar i databasen genom Titel.
        /// Om boken inte är null så plussas bokens property Amount med det amount/antal som lagts till och sparas.
        /// Om boken är null så läggs boken till i databasen och sparas.
        /// </summary>
        /// <param name="adminId">Admins Id</param>
        /// <param name="title">Bokens titel</param>
        /// <param name="author">Författare av boken</param>
        /// <param name="price">Bokens pris</param>
        /// <param name="amount">Antalet böcker</param>
        /// <returns>Returnerar false om användarens property IsAdmin är false, annars true</returns>
        public bool AddBook(int adminId, string title, string author, int price, int amount)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var book = db.Books.FirstOrDefault(b => b.Title == title);
                    if (book != null)
                    {
                        book.Amount += amount;
                        db.Update(book);
                        db.SaveChanges();
                        return(true);
                    }
                    else
                    {
                        db.Books.Add(new Book {
                            Title = title, Author = author, Price = price, Amount = amount
                        });
                        db.Update(book);
                        db.SaveChanges();
                        return(true);
                    }
                }
            }
            else
            {
                return(false);
            }
        }
 public ApplicationUser CurrentUser()
 {
     using (var db = new WebShopContext())
     {
         return(db.Users.FirstOrDefault(u => u.Email == this.User.Identity.Name));
     }
 }
Esempio n. 18
0
        public IActionResult GetCart()
        {
            string        username = HttpContext.Session.GetString("Username");
            IActionResult result   = null;

            if (!string.IsNullOrWhiteSpace(username))
            {
                using (var context = new WebShopContext())
                {
                    result = Json(new
                    {
                        Authenticated = true,
                        ShoppingCart  = context.ShoppingCarts
                                        .Where(c => c.User.Username == username)
                                        .Select(c => new
                        {
                            Number  = c.Number,
                            Product = new
                            {
                                Id    = c.ProductId,
                                Name  = c.Product.Name,
                                Price = c.Product.Price
                            }
                        }).ToList()
                    });
                }
            }
            return(result ?? Json(new
            {
                Authenticated = false
            }));
        }
Esempio n. 19
0
        private void CreateUser(WebShopContext context, string email, string password)
        {
            //user manager
            var userManager = new UserManager <ApplicationUser>(
                new UserStore <ApplicationUser>(context));

            //set user manager pass validator
            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 1,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireNonLetterOrDigit = false,
                RequireUppercase        = false
            };

            //create user object
            var admin = new ApplicationUser
            {
                UserName = email,
                Email    = email
            };

            //create user
            var result = userManager.Create(admin, password);

            //validate result
            if (!result.Succeeded)
            {
                throw new Exception(string.Join(";", result.Errors));
            }
        }
Esempio n. 20
0
        public ActionResult DeleteConfirmation(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new WebShopContext())
            {
                //get comment
                var comment = db.Comments
                              .Where(c => c.Id == id)
                              .First();

                var productId = comment.ProductId;

                //check if exists
                if (comment == null)
                {
                    return(HttpNotFound());
                }

                //remove product
                db.Comments.Remove(comment);
                db.SaveChanges();

                //redirect to /product/list
                return(RedirectToAction("Details", "Product", new { id = productId }));
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Lägger till en kategori i databasen.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden kollar om kategorin existerar i databasen genom namn.
        /// Om kategorin är null så läggs kategorin till i databasen och sparas.
        /// </summary>
        /// <param name="adminId">Admins Id</param>
        /// <param name="name">Namnet på kategorin</param>
        /// <returns>Returnerar true om kategorin är null, annars false</returns>
        public bool AddCategory(int adminId, string name)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var category = db.Categories.FirstOrDefault(c => c.Name == name);
                    if (category == null)
                    {
                        db.Categories.Add(new Category {
                            Name = name
                        });
                        db.SaveChanges();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Esempio n. 22
0
        public ActionResult Create(Comment comment, int?id)
        {
            if (ModelState.IsValid)
            {
                //insert in DB
                using (var db = new WebShopContext())
                {
                    var authorId  = db.Users.Where(u => u.UserName == this.User.Identity.Name).First().Id;
                    var productId = db.Products.FirstOrDefault(p => p.Id == id).Id;
                    var addedOn   = DateTime.Now;
                    var email     = db.Users.FirstOrDefault(e => e.Email == this.User.Identity.Name).Email;

                    comment.Email     = email;
                    comment.AddedOn   = addedOn;
                    comment.AuthorId  = authorId;
                    comment.ProductId = productId;

                    db.Comments.Add(comment);
                    db.SaveChanges();

                    return(RedirectToAction("Details", "Product", new { @id = productId }));
                }
            }

            return(View(comment));
        }
Esempio n. 23
0
        /// <summary>
        /// Lägger till en användare i databasen.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden kollar om användaren existerar i databasen genom namn.
        /// Om användaren är null så läggs användaren till i databasen och sparas.
        /// Är lösenordet är tomt så läggs "Codic2021" till som default-lösenord. Propertyn IsActive sätts till true och IsAdmin till false.
        /// </summary>
        /// <param name="adminId">Admins Id</param>
        /// <param name="name">Användarens namn</param>
        /// /// <param name="password">Användarens lösenord</param>
        /// <returns>Returnerar true om användaren är null, annars false</returns>
        public bool AddUser(int adminId, string name, string password)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var user = db.Users.FirstOrDefault(u => u.Name == name);
                    if (user == null)
                    {
                        if (password == string.Empty)
                        {
                            password = "******";
                        }
                        db.Users.Add(new User {
                            Name = name, Password = password, IsActive = true, IsAdmin = false
                        });
                        db.SaveChanges();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Esempio n. 24
0
        public ActionResult GetCategories()
        {
            WebShopContext db         = new WebShopContext();
            var            categories = db.Categories.ToList();

            return(PartialView(categories));
        }
Esempio n. 25
0
        /// <summary>
        /// Tar fram vilken användare som köpt flest böcker.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden tar fram sålda böcker genom användar-Id och skapar en temporär "form/tabell" i variabeln OrderCounts där användar-Id och antalet köpta böcker läggs in.
        /// Därefter tar man fram vilken av antalet köpta böcker som är högst(Max) ur tabellen och tar fram Id som tillhör det högsta antalet.
        /// Namnet på den användaren hämtas därefter genom Id:t.
        /// </summary>
        /// <param name="adminId">Admins Id</param>
        /// <returns>Returnerar namnet på användaren, annars en tom sträng</returns>
        public string BestCustomer(int adminId)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var OrderCounts = db.SoldBooks.GroupBy(
                        o => o.UserId).
                                      Select(g => new
                    {
                        UserId      = g.Key,
                        TotalOrders = g.Count()
                    });

                    var maxNumOfOrders = OrderCounts.Max(x => x.TotalOrders);
                    var bestInGroup    = OrderCounts.FirstOrDefault(x => x.TotalOrders == maxNumOfOrders);
                    var user           = db.Users.FirstOrDefault(c => c.Id == bestInGroup.UserId);

                    return($"{user.Name}");
                }
            }
            return("");
        }
Esempio n. 26
0
        public ActionResult Details(int Id)
        {
            WebShopContext db      = new WebShopContext();
            var            product = db.Products.Find(Id);

            return(View(product));
        }
Esempio n. 27
0
        /// <summary>
        /// Tar bort en kategori.
        /// Kollar först om adminId är en administratör genom att anropa metoden CheckIfUserIsAdmin.
        /// Metoden tar fram kategorin genom Id och kollar så att kategorin inte är null. Metoden kollar även om en bok med den kategorin existerar om inte så tas kategorin bort från databasen.
        /// </summary>
        /// <param name="adminId">Användarens/Administratörens Id</param>
        /// <param name="categoryId">Kategorins Id</param>
        /// <returns>Returnerar true om kategorin existerar och ingen bok är kopplad till kategorin, annars false</returns>
        public bool DeleteCategory(int adminId, int categoryId)
        {
            bool userIsAdmin = CheckIfUserIsAdmin(adminId);

            if (userIsAdmin)
            {
                using (var db = new WebShopContext())
                {
                    var category = db.Categories.FirstOrDefault(c => c.Id == categoryId);
                    var book     = db.Books.FirstOrDefault(b => b.CategoryId == categoryId);
                    if (category != null)
                    {
                        if (book != null)
                        {
                            return(false);
                        }
                        else
                        {
                            db.Remove(category);
                            db.Update(category);
                            db.SaveChanges();
                            return(true);
                        }
                    }
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 28
0
        public ActionResult ConfirmOrderConf(int?id)
        {
            using (var db = new WebShopContext())
            {
                var cart = db.Carts.FirstOrDefault(c => c.Id == id);

                if (cart == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }

                Order order = new Order
                {
                    Cart         = cart,
                    DeliveryDate = DateTime.Now.AddDays(10),
                };

                foreach (var product in cart.Products)
                {
                    order.Products.Add(product);
                }

                order.User = cart.User;

                db.Orders.Add(order);
                cart.Products.Clear();
                db.SaveChanges();

                return(RedirectToAction("List", "Product"));
            }
        }
Esempio n. 29
0
        private static async Task FillTables()
        {
            var dbcontext = new WebShopContext();

            var customersRepo = new BaseRepository <Customer>(dbcontext);
            var ordersRepo    = new BaseRepository <Order>(dbcontext);
            var productsRepo  = new BaseRepository <Product>(dbcontext);

            var names = new string [] { "John Doe", "Josh Brown", "Ethan Smith", "Michael Johnson", "John Davis", "Jacob Miller", "Tyler Jackson", "Ryan White", "David Harris", "Daniel Anderson" };

            for (int i = 1; i <= 10; i++)
            {
                var newCustomer = new Customer {
                    Id = i, Name = names[i - 1]
                };
                await customersRepo.Add(newCustomer);

                for (int j = 1; j <= 10; j++)
                {
                    var newOrder = new Order {
                        Id = j, Date = DateTime.Now, Customer = newCustomer
                    };
                    await ordersRepo.Add(newOrder);

                    for (int k = 1; k <= 10; k++)
                    {
                        var newProduct = new Product {
                            Id = k, Name = $"Product #{k}", Price = k, Order = newOrder
                        };
                        await productsRepo.Add(newProduct);
                    }
                }
            }
        }
Esempio n. 30
0
 public ActionResult List()
 {
     using (var db = new WebShopContext())
     {
         var orders = db.Orders.Include(c => c.Products).Include(u => u.User).ToList();
         return(View(orders));
     }
 }