コード例 #1
0
        public ActionResult Create([Bind(Include = "ProductID,Quantity")] ProductInOrderCreateModel viewModel)
        {
            ProductInOrder productInOrder = new ProductInOrder();

            productInOrder.ProductID = viewModel.ProductID;
            productInOrder.Quantity  = viewModel.Quantity;

            string userID      = User.Identity.GetUserId();
            Order  activeOrder = db.Orders.FirstOrDefault(x => x.UserId == userID && x.OrderStatus == 0);

            if (activeOrder == null)
            {
                return(RedirectToAction("Warning", "Home", new { message = "No active order currently. Click New order below if you are a customer to proceed to an order. " }));
            }
            productInOrder.OrderID = activeOrder.OrderID;

            ProductInOrder p = db.ProductInOrders.FirstOrDefault(x => x.OrderID == activeOrder.OrderID && x.ProductID == productInOrder.ProductID);

            //If product is already in Order
            if (p != null)
            {
                p.Quantity = viewModel.Quantity;
                db.SaveChanges();
                return(RedirectToAction("Warning", "Home", new { message = "Product already in order, updated the amount order!" }));
            }


            db.ProductInOrders.Add(productInOrder);
            db.SaveChanges();

            ViewBag.Message = "Product added to order";
            return(RedirectToAction("Index", "Products"));
        }
コード例 #2
0
        public static void EnsureSeeded(this AppUsersDbContext context)
        {
            if (!context.UserRoles.Any())
            {
                var roles = JsonConvert.DeserializeObject <List <IdentityRole> >(File.ReadAllText("seed" + Path.DirectorySeparatorChar + "roles.json"));
                List <ApplicationRole> roleList = new List <ApplicationRole>();
                foreach (var role in roles)
                {
                    roleList.Add(new ApplicationRole()
                    {
                        Name = role.Name
                    });
                }
                context.Roles.AddRange(roleList);
                int i = context.SaveChanges();
            }

            if (!context.Users.Any())
            {
                List <ApplicationUser> appUserList = new List <ApplicationUser>();
                var userList = JsonConvert.DeserializeObject <List <ApplicationUser> >(File.ReadAllText("seed" + Path.DirectorySeparatorChar + "users.json"));
                foreach (var appUser in userList)
                {
                    string passwordHasher = new PasswordHasher <ApplicationUser>().HashPassword(appUser, appUser.PasswordHash);
                    appUser.PasswordHash = passwordHasher;
                    appUserList.Add(appUser);
                }
                context.Users.AddRange(appUserList);
                int j = context.SaveChanges();
            }
        }
コード例 #3
0
        public IHttpActionResult PutDocument(int id, Document document)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != document.Id)
            {
                return(BadRequest());
            }

            db.Entry(document).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DocumentExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #4
0
        public ActionResult Create([Bind(Include = "Id,Title,RequestDate,Flag,CreatedAt,UpdatedAt")] Request request)
        {
            if (ModelState.IsValid)
            {
                db.Requests.Add(request);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(request));
        }
コード例 #5
0
        public int UploadProductInDataBase(HttpPostedFileBase photoFile, HttpPostedFileBase barcodeFile, ProductVM productVM)
        {
            //creating a product variable in order to pass in it productVM's values and then store the product to database
            var product = new Product();

            //product.Id = productVM.ProductId; //Propably not needed
            product.ProductName       = productVM.ProductName;
            product.AvailableQuantity = productVM.AvailableQuantity;
            product.Description       = productVM.Description;
            product.InitialPrice      = productVM.InitialPrice;
            product.CategoryId        = productVM.CategoryId;
            product.Photo             = ConvertToBytes(photoFile);
            product.BarCode           = ConvertToBytes(barcodeFile);


            /*            var productDietary = new ProductDietary();
             *
             *          foreach (var item in productVM.DietariesIds)
             *          {
             *              productDietary.ProductId = productVM.ProductId;
             *              productDietary.DietaryId = item;
             *              _context.ProductDietaries.Add(productDietary);
             *
             *          }*/



            _context.Products.AddOrUpdate(product); //Do we need modelstate.isvalid?
            int i = _context.SaveChanges();

            foreach (var productDietaryId in productVM.DietariesIds)
            {
                _context.ProductDietaries.Add(new ProductDietary
                {
                    DietaryId = productDietaryId,
                    Dietary   = _context.Dietaries.SingleOrDefault(x => x.Id == productDietaryId),
                    Product   = product,
                    ProductId = product.Id
                });
            }

            //_context.SaveChanges();

            if (i == 1)
            {
                return(1);  // if i equals one then the product has been successfully saved and stored in db
            }
            else
            {
                return(0);
            }
        }
コード例 #6
0
        public ActionResult Create([Bind(Include = "Type,Description")] Document document)
        {
            if (ModelState.IsValid)
            {
                document.State     = "Enabled";
                document.CreatedAt = DateTime.Now;
                document.UpdatedAt = DateTime.Now;
                db.Documents.Add(document);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(document));
        }
コード例 #7
0
        public async Task <ActionResult> ChangeRole(string userId, string role)
        {
            var roleStore   = new RoleStore <IdentityRole>(new AppUsersDbContext());
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            if (!User.IsInRole("Administrator"))
            {
                return(RedirectToAction("Warning", "Home", new { message = "ACCESS DENIED - Adminstrator Only " }));
            }

            // Clear all roles from user
            await UserManager.RemoveFromRoleAsync(userId, "Unvalidated User");

            await UserManager.RemoveFromRoleAsync(userId, "Validated User");

            await UserManager.RemoveFromRoleAsync(userId, "Manager");


            await roleManager.CreateAsync(new IdentityRole(role));

            //await UserManager.AddToRoleAsync(user.Id, "Validated User");
            await HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>().AddToRoleAsync(userId, role);

            db.SaveChanges();
            ApplicationUser user = db.Users.FirstOrDefault(x => x.Id == userId);

            //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);


            return(RedirectToAction("Index", "ApplicationUsers"));
        }
コード例 #8
0
        //Jan16th New Order Edit


        public ActionResult Create()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Login", "Account"));
            }
            if (User.IsInRole("Unvalidated User"))
            {
                return(RedirectToAction("Warning", "Home", new { message = "ACCESS DENIED - Verify with a vendor first!" }));
            }
            // Makes sure older Order is cancelled
            string userID        = User.Identity.GetUserId();
            Order  previousOrder = db.Orders.FirstOrDefault(x => x.UserId == userID && x.OrderStatus == 0);

            if (previousOrder != null)
            {
                previousOrder.OrderStatus = (OrderStatus)2;
            }


            // Create new Order
            Order order = new Order();

            order.DateStarted = DateTime.Now;
            order.UserId      = User.Identity.GetUserId();
            order.OrderStatus = 0;
            db.Orders.Add(order);
            db.SaveChanges();
            return(RedirectToAction("Index", "Products"));
        }
コード例 #9
0
        private bool UpdateProducts(Order activeOrder)
        {
            // start by getting all productInOrder data
            var productInOrders = db.ProductInOrders.Where(x => x.OrderID == activeOrder.OrderID).Include(x => x.Product);


            // check if all products are available in the quantities needed
            bool allProductsAvailable = true;

            foreach (var item in productInOrders)
            {
                if (item.Quantity > item.Product.UnitsInStock)
                {
                    allProductsAvailable = false;
                }
            }

            if (!allProductsAvailable)
            {
                return(false);   //if a single product isn't available we go back to the action with a false
            }
            // Now i want to update all products with new quantities

            foreach (var item in productInOrders)
            {
                Product product = item.Product;
                product.UnitsInStock -= item.Quantity;
                if (product.UnitsInStock == 0)
                {
                    product.ProductStatus = (ProductStatus)1;
                }
            }

            db.SaveChanges();
            ProductsHub.BroadcastData();

            return(true);
        }
コード例 #10
0
        public ActionResult AdminSave(AdminVM userInfo)
        {
            if (!ModelState.IsValid)
            {
                return(View("AdminEdit", userInfo));
            }

            else
            {
                var userInDb = _context.Users.Find(userInfo.UserId);
                _ = _context.Roles;
                var roleStore   = new RoleStore <IdentityRole>(new AppUsersDbContext());
                var roleManager = new RoleManager <IdentityRole>(roleStore);;

                userInDb.Id             = userInfo.UserId;
                userInDb.FirstName      = userInfo.FirstName;
                userInDb.LastName       = userInfo.LastName;
                userInDb.DateOfBirth    = userInfo.DateOfBirth;
                userInDb.Country        = userInfo.Country;
                userInDb.Region         = userInfo.Region;
                userInDb.City           = userInfo.City;
                userInDb.Street         = userInfo.Street;
                userInDb.StreetNumber   = userInfo.StreetNumber;
                userInDb.ZipCode        = userInfo.ZipCode;
                userInDb.Email          = userInfo.Email;
                userInDb.EmailConfirmed = userInfo.EmailConfirmed;
                userInDb.UserName       = userInfo.UserName;
                userInDb.Roles.Clear();

                var role = roleManager.FindById(userInfo.RoleId);
                roleManager.Create(new IdentityRole(role.Name));
                HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>().AddToRole(userInDb.Id, role.Name);

                _context.Entry(userInDb).State = EntityState.Modified;
                _context.SaveChanges();
                return(RedirectToAction("AdminPage", "Users"));
            }
        }
コード例 #11
0
        public ActionResult Create(RequestViewModel httpRequest)
        {
            // envoie du formulaire
            Request request = new Request();

            //Select user from databse where user = user in request
            var user = db.Users.Where(x => x.Id == httpRequest.userId).FirstOrDefault();


            //Creation de liste avec les ids du documents selectionnés
            List <int> selectedDocuments = httpRequest.Documents;

            if (ModelState.IsValid)
            {
                //Select document from db where documentsIds = listDocuments ids from request
                var requestedDocuments = db.Documents.Where(x => selectedDocuments.Contains(x.Id)).ToList();
                request.Documents = requestedDocuments;

                request.Title       = httpRequest.Title;
                request.RequestDate = httpRequest.RequestDate;
                request.Flag        = httpRequest.Flag;
                request.Status      = "On Hold";
                request.CreatedAt   = DateTime.Now;
                request.UpdatedAt   = DateTime.Now;

                request.User = user;
                db.Requests.Add(request);
                db.SaveChanges();
                //envoi de l'email
                string currentUserId = User.Identity.GetUserId();
                user = db.Users.FirstOrDefault(x => x.Id == currentUserId);
                request.SendMail();
                return(RedirectToAction("Index"));
            }
            return(View(request));
        }
コード例 #12
0
        public async Task <ActionResult> ValidateVendor(string key)
        {
            //bool validate = false;
            var vendor = db.Vendors.FirstOrDefault(x => x.VendorSecretKey == key);

            if (vendor != null)
            {
                var             userId = User.Identity.GetUserId();
                ApplicationUser user   = db.Users.FirstOrDefault(x => x.Id == userId);
                user.VendorID = vendor.VendorID;


                //var roleStore = new RoleStore<IdentityRole>(new AppUsersDbContext());
                //var roleManager = new RoleManager<IdentityRole>(roleStore);
                var roleStore   = new RoleStore <IdentityRole>(new AppUsersDbContext());
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                //user.Roles.Clear();
                await UserManager.RemoveFromRoleAsync(user.Id, "Unvalidated User");

                await roleManager.CreateAsync(new IdentityRole("Validated User"));

                //await UserManager.AddToRoleAsync(user.Id, "Validated User");
                await HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>().AddToRoleAsync(user.Id, "Validated User");

                db.SaveChanges();
                await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);


                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(RedirectToAction("Warning", "Home", new { message = "Invalid Vendor Key!" }));
            }
        }
コード例 #13
0
        public ActionResult AddToBasket(ProductVM productVM)
        {
            //When a product is added in the basket, orderdetails should be updated.
            //A new orderdetails should be created in order to pass on the values in the database
            var orderDetails = new OrderDetails();
            var product      = _context.Products.Find(productVM.ProductId);
            var categories   = _context.Categories.ToList();
            var dietaries    = _context.Dietaries.ToList();
            //In order to pass on the value of orderID, it is needed to be checked whether the user has any orders ongoing or a new one must be created
            var userId = User.Identity.GetUserId();

            orderDetails.ProductId        = product.Id;
            orderDetails.Product          = _context.Products.SingleOrDefault(p => p.Id == product.Id);
            orderDetails.Price            = product.PriceIncludingVAT;
            orderDetails.SelectedQuantity = productVM.SelectedQuantity;



            var  openOrders      = _context.Orders.Where(o => o.OrderStatusId == 1).ToList();
            var  usersOpenOrder  = openOrders.SingleOrDefault(o => o.ApplicationUserId == userId);
            bool twoSameProducts = false;

            //I splitted the linq because for some reason it did not recognize the variable as a list of orders but as IQuerable
            //In this condition we test whether there are open orders in order to create them or use the already opened one.
            if (openOrders.Count() == 0)
            {
                var order = new Order();
                order.ApplicationUserId = userId;
                _context.Orders.AddOrUpdate(order);
                _context.SaveChanges();
                orderDetails.OrderId = order.Id;
                orderDetails.Order   = _context.Orders.SingleOrDefault(o => o.Id == order.Id);
            }
            else if (openOrders.Count() != 0 && usersOpenOrder == null)
            {
                var order = new Order();
                order.ApplicationUserId = userId;
                _context.Orders.AddOrUpdate(order);
                _context.SaveChanges();
                orderDetails.OrderId = order.Id;
                orderDetails.Order   = _context.Orders.SingleOrDefault(o => o.Id == order.Id);
            }
            else if (openOrders.Count() != 0 && usersOpenOrder != null)
            {
                var orderIDAlreadyExisting = openOrders.Where(o => o.ApplicationUserId == userId).Select(k => k.Id).SingleOrDefault();
                //if the order already exists then we assign the orderId already existing.
                orderDetails.OrderId = orderIDAlreadyExisting;
                //Selecting existing orderdetails
                var orderDetailsAlreadyExisting = _context.OrdersDetails.Where(o => o.OrderId == orderIDAlreadyExisting);
                var orderDetailsOfTheProductIncludedInTheSpecificOrder = orderDetailsAlreadyExisting.Where(x => x.ProductId == product.Id).SingleOrDefault();

                //if the product already exists in our order then we update its selected quantity
                if (orderDetailsOfTheProductIncludedInTheSpecificOrder != null)
                {
                    orderDetailsOfTheProductIncludedInTheSpecificOrder.SelectedQuantity += productVM.SelectedQuantity;

                    if (product.AvailableQuantity - orderDetailsOfTheProductIncludedInTheSpecificOrder.SelectedQuantity >= 0)
                    {
                        _context.OrdersDetails.AddOrUpdate(orderDetailsOfTheProductIncludedInTheSpecificOrder);
                        _context.SaveChanges();
                    }
                    else
                    {
                        TempData["message"] = $"The extra quantity you have selected exceeds the available quantity of {product.ProductName}. Remaining quantity : {product.AvailableQuantity - orderDetailsOfTheProductIncludedInTheSpecificOrder.SelectedQuantity + productVM.SelectedQuantity }";
                        return(RedirectToAction("Index", "Products"));
                    }
                    twoSameProducts = true;
                }
            }

            //If true it means that orderdetails does not exist in order
            if (!twoSameProducts)
            {
                orderDetails.ProductId        = product.Id;
                orderDetails.Product          = _context.Products.SingleOrDefault(p => p.Id == product.Id);
                orderDetails.Price            = product.PriceIncludingVAT;
                orderDetails.SelectedQuantity = productVM.SelectedQuantity;

                _context.OrdersDetails.AddOrUpdate(orderDetails);
                _context.SaveChanges();
            }
            TempData["message"] = $"{product.ProductName} has just been added in your cart!";
            return(RedirectToAction("Index", "Products"));
        }