public AuthenticateResponse Authenticate(AuthenticateRequest model, string ipAddress)
        {
            var login = _context.Logins.Include(l => l.Role).SingleOrDefault(x => x.Email == model.Email);

            // return null if user not found
            if (login == null)
            {
                return(null);
            }

            if (!BCrypt.Net.BCrypt.Verify(model.Password, login.Password))
            {
                return(null);
            }
            // authentication successful so generate jwt and refresh tokens
            var jwtToken     = generateJwtToken(login);
            var refreshToken = generateRefreshToken(ipAddress);

            // save refresh token
            login.RefreshTokens.Add(refreshToken);
            _context.Update(login);
            _context.SaveChanges();

            return(new AuthenticateResponse(login, jwtToken, refreshToken.Token));
        }
        public ActionResult Overzicht(OrderViewModel ovm)
        {
            Klant klant = db.Klanten.Add(ovm.Klant);

            db.SaveChanges();

            Order order = new Order();

            order.Klant       = klant;
            order.OrderRegels = new List <OrderRegel>();

            db.Orders.Add(order);
            db.SaveChanges();

            foreach (var kvp in (Dictionary <int, int>)Session["Cart"])
            {
                Product product = db.Producten.Find(kvp.Key);
                int     amount  = kvp.Value;

                OrderRegel orderRegel = new OrderRegel();
                orderRegel.Order   = order;
                orderRegel.Product = product;
                orderRegel.Aantal  = amount;

                order.OrderRegels.Add(orderRegel);
            }

            db.SaveChanges();

            return(RedirectToAction("Success"));
        }
Пример #3
0
        public void CreateCategory(dynamic Categorydetails)
        {
            dynamic CategorydetailsJSON = JsonConvert.DeserializeObject(Categorydetails.ToString());

            Console.WriteLine(CategorydetailsJSON);

            Category Category = new Category()
            {
                CategoryName = CategorydetailsJSON.CategoryName,
                Id           = CategorydetailsJSON.CategoryId
            };

            _context.Categories.Add(Category);

            _Type Type = new _Type()
            {
                _TypeName = CategorydetailsJSON.TypeName,
                Id        = CategorydetailsJSON.TypeId
            };

            _context.Types.Add(Type);

            Category_Type CT = new Category_Type()
            {
                CategoryId = Category.Id,
                _TypeId    = Type.Id
            };

            _context.CategoryType.Add(CT);
            _context.SaveChanges();
        }
Пример #4
0
        public void FillinAdress([FromBody] Address address)
        {
            var userid           = (_caller.Claims.Single(claim => claim.Type == "id"));
            var filled_in_adress = new Address
            {
                Street      = address.Street,
                City        = address.City,
                ZipCode     = address.ZipCode,
                HouseNumber = address.HouseNumber,
            };

            _context.Addresses.Add(filled_in_adress);
            // _context.SaveChanges();

            // var find_adress_id = (from entries in _context.Addresses
            //                       where entries.Street == address.Street && entries.City == address.City && entries.ZipCode == address.ZipCode && entries.HouseNumber == address.HouseNumber
            //                       select entries.Id).ToArray();

            var user_adress = new UserAddress
            {
                AddressId = filled_in_adress.Id,
                UserId    = Int32.Parse(userid.Value)
            };

            ;
            _context.UserAddress.Add(user_adress);

            _context.SaveChanges();
        }
Пример #5
0
        public void MakeOrder(dynamic Orderdetails)
        {
            dynamic     OrderdetailsJSON = JsonConvert.DeserializeObject(Orderdetails.ToString());
            OrderStatus Status           = new OrderStatus()
            {
                OrderDescription = "Pending"
            };

            _context.OrderStatus.Add(Status);

            Order Order = new Order()
            {
                UserId        = OrderdetailsJSON.userID,
                AddressId     = OrderdetailsJSON.AddressID,
                OrderStatusId = Status.Id
            };

            _context.Orders.Add(Order);

            foreach (var item in OrderdetailsJSON.productIDs)
            {
                OrderProduct product = new OrderProduct()
                {
                    OrderId   = Order.Id,
                    ProductId = item
                };
                _context.OrderProduct.Add(product);
            }
            _context.SaveChanges();
        }
Пример #6
0
        public IActionResult Post(Item item, string url)
        {
            item.Id = 0;

            _context.Items.Add(item);
            _context.SaveChanges();
            return(new CreatedResult($"{url}/{item.Id}", item));
        }
Пример #7
0
        //[HttpPut("ChangeQuantity")]
        public ActionResult ProductStock_GoUp(int id)
        {
            var query = (from products in _context.Products
                         where products.Id == id
                         select products.Stock).ToArray();

            query[0].ProductQuantity++;

            _context.SaveChanges();
            return(Ok(query));
        }
        public ActionResult Create([Bind(Include = "ID,Name")] ProductCategory productCategory)
        {
            if (ModelState.IsValid)
            {
                db.ProductCategories.Add(productCategory);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(productCategory));
        }
Пример #9
0
        public ActionResult Create([Bind(Include = "ID,ProductCategoryID,Name,Description,Price,OwnerName,OwnerEmail,CreatedOn,UpdatedOn")] Product product)
        {
            if (ModelState.IsValid)
            {
                product.Update();
                db.Products.Add(product);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ProductCategoryID = new SelectList(db.ProductCategories, "ID", "Name", product.ProductCategoryID);
            return(View(product));
        }
Пример #10
0
        public IActionResult Post(Order order, string url)
        {
            if (!AuthService.ActionAuthorized(AuthUser, order.UserId))
            {
                return(new ForbidResult());
            }

            order.Id      = 0;
            order.CurDate = DateTime.Now;
            _context.Orders.Add(order);
            _context.SaveChanges();
            return(new CreatedResult($"{url}/{order.Id}", order));
        }
Пример #11
0
        public IActionResult Post(CartItem cartItem, string url)
        {
            if (!AuthService.ActionAuthorized(AuthUser, cartItem.UserId))
            {
                return(new ForbidResult());
            }

            cartItem.Id = 0;
            _context.CartItems.Add(cartItem);
            _context.SaveChanges();

            return(new CreatedResult($"{url}/{cartItem.Id}", cartItem));
        }
Пример #12
0
        public ActionResult AdminEditCartItems([FromBody] CartViewModel _cartItem, int Id)
        {
            CartViewModelValidator validator = new CartViewModelValidator();
            ValidationResult       results   = validator.Validate(_cartItem);

            if (!results.IsValid)
            {
                foreach (var failure in results.Errors)
                {
                    Errors.AddErrorToModelState(failure.PropertyName, failure.ErrorMessage, ModelState);
                }
            }

            if (!ModelState.IsValid || _cartItem.CartQuantity == 0)
            {
                return(BadRequest(ModelState));
            }

            if (_context.Users.Find(Id) != null)
            {
                var cartItem = _context.CartProducts
                               .Where(c => c.Cart.UserId == Id && c.ProductId == _cartItem.ProductId)
                               .Select(a => a).ToArray();

                if (cartItem.Length == 0)
                {
                    return(NotFound());
                }

                var oldQuantity = cartItem[0].CartQuantity;
                var stockid     = (_context.Stock.Where(s => s.Product.Id == _cartItem.ProductId).Select(p => p.Id)).ToArray().First();
                var stock       = _context.Stock.Find(stockid);

                if (stock.ProductQuantity + oldQuantity < _cartItem.CartQuantity)
                {
                    cartItem[0].CartQuantity = stock.ProductQuantity + oldQuantity;
                    stock.ProductQuantity    = 0;
                }

                else
                {
                    cartItem[0].CartQuantity = _cartItem.CartQuantity;
                    stock.ProductQuantity    = stock.ProductQuantity + oldQuantity - _cartItem.CartQuantity;
                }

                TotalPrice(cartItem[0].CartId);

                _context.Update(stock);
                _context.CartProducts.Update(cartItem[0]);
                _context.SaveChanges();

                return(Ok());
            }
            return(NotFound());
        }
Пример #13
0
 public void Add(Product newProduct)
 {
     _context.Add(newProduct);
     _context.Database.OpenConnection();
     try
     {
         _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Products ON");
         _context.SaveChanges();
         _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Products OFF");
     }
     finally
     {
         _context.Database.CloseConnection();
     }
 }
Пример #14
0
        public User Create(User t)
        {
            var user = _ctx.Users.Add(t).Entity;

            _ctx.SaveChanges();
            return(user);
        }
        public IHttpActionResult PostProduct(Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            product.Plaatje = "http://placehold.it/300x300";

            product.Categorieen = new List <Categorie>();
            product.Categorieen.Add(db.Categorieen.Find(6));

            db.Producten.Add(product);
            db.SaveChanges();

            //return CreatedAtRoute("DefaultApi", new { id = product.ID }, product);
            return(Ok());
        }
Пример #16
0
        public IActionResult Post(User user, string url)
        {
            string hashedPassword = AuthService.HashPassword(user.Password);

            user.Password = hashedPassword;

            user.Id = 0;
            if (!AuthService.IsAdmin(AuthUser))
            {
                user.IsAdmin = false;
            }

            _context.Users.Add(user);
            _context.SaveChanges();

            DtoUser dtoUser = new DtoUser(user.Id, user.Email, user.IsAdmin);

            return(new CreatedResult($"{url}/{dtoUser.Id}", dtoUser));
        }
        public IActionResult Move(int userid, int productid)
        {
            var find_cartId = (from entries in _context.Users
                               where entries.Id == userid
                               select entries.Cart.Id).ToArray();

            if (find_cartId == null)
            {
                return(NotFound());
            }
            AddItemToCart(find_cartId[0], productid);
            var find_wishlist_product = (from entries in _context.WishlistProduct
                                         where entries.Wishlist.UserId == userid && entries.ProductId == productid
                                         select entries).ToArray();

            _context.WishlistProduct.Remove(find_wishlist_product[0]);
            _context.SaveChanges();
            return(Ok());
        }
Пример #18
0
        // Register user
        public user_frontend register(user_register user)
        {
            var query = from u in _context.Users
                        where u.E_mail == user.E_mail
                        select(u.ID);

            int           counter      = 0;
            user_frontend userFrontend = new user_frontend(false, user.Name, user.Surname, user.E_mail, -1);

            foreach (var item in query)
            {
                counter = counter + 1;
            }

            if (counter > 0)
            {
                userFrontend.autorized = false;
                return(userFrontend);
            }
            else
            {
                string randomString = randomstring.RandomString();

                Users newUsers = new Users
                {
                    E_mail          = user.E_mail,
                    Password        = SHA.GenerateSHA512String(randomString + user.Password),
                    Salt            = randomString,
                    Name            = user.Name,
                    Surname         = user.Surname,
                    City            = user.City,
                    Zip_code        = user.Zip_code,
                    Country         = user.Country,
                    Date_of_birth   = user.Date_of_birth,
                    Street          = user.Street,
                    Building_nummer = user.Building_nummer
                };

                _context.Users.Add(newUsers);
                _context.SaveChanges();

                var query2 = from u in _context.Users
                             where u.E_mail == user.E_mail
                             select(u.ID);

                foreach (int item in query2)
                {
                    userFrontend.ID = item;
                }


                userFrontend.autorized = true;
                return(userFrontend);
            }
        }
Пример #19
0
 /// <summary>
 /// Saves this instance.
 /// </summary>
 public void Save()
 {
     if (_loggingContext != null)
     {
         _loggingContext.SaveChanges();
     }
     if (_webshopContext != null)
     {
         _webshopContext.SaveChanges();
     }
 }
Пример #20
0
        public ActionResult Post([FromBody] NewWish newWish)
        {
            User user          = GetClaimUser();
            bool productExists = db.Product.Any(x => x.Id == newWish.id);
            bool wishExists    = db.Wishlists.Any(x => x.UserId == user.Id && x.ProductId == newWish.id);

            if (productExists && !wishExists)
            {
                Wishlist wish = new Wishlist()
                {
                    UserId    = user.Id,
                    ProductId = newWish.id
                };
                db.Add(wish);
                db.SaveChanges();
                return(StatusCode(201));
            }
            else
            {
                return(NotFound());
            }
        }
Пример #21
0
        static void Main(string[] args)
        {
            using WebshopContext db = new WebshopContext();

            User zvone = new User()
            {
                Name      = "Zvonimir Matic",
                Email     = "*****@*****.**",
                Addresses = new List <Address>()
                {
                    new Address()
                    {
                        Country      = "Croatia",
                        City         = "Rijeka",
                        PostalCode   = "51000",
                        StreetName   = "Petra Jurcica",
                        StreetNumber = "16"
                    }
                }
            };

            User john = new User()
            {
                Name  = "John Smith",
                Email = "*****@*****.**"
            };

            db.Users.Add(zvone);
            db.Users.Add(john);
            db.SaveChanges();

            IEnumerable <User> queryUsers = db.Users.Where(x => x.Name.ToLower().Contains("john"));

            foreach (User user in queryUsers)
            {
                user.Name = "Zvonimir Matic";
            }
            db.SaveChanges();
        }
Пример #22
0
        public void FillinAdress([FromBody] Address address)
        {
            var userid           = (_caller.Claims.Single(claim => claim.Type == "id"));
            var filled_in_adress = new Address
            {
                Street      = address.Street,
                City        = address.City,
                ZipCode     = address.ZipCode,
                HouseNumber = address.HouseNumber,
            };

            _context.Addresses.Add(filled_in_adress);
            var user_adress = new UserAddress
            {
                AddressId = filled_in_adress.Id,
                UserId    = Int32.Parse(userid.Value)
            };

            ;
            _context.UserAddress.Add(user_adress);

            _context.SaveChanges();
        }
        public async Task <IActionResult> index(IFormFile files)
        {
            string content = files.ContentType;

            // full path to file in temp location
            var filePath = Path.GetTempFileName();


            if (files.Length > 0)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await files.CopyToAsync(stream);
                }
            }

            // process uploaded files
            // Don't rely on or trust the FileName property without validation.
            string     output     = "done";
            FileStream fileStream = new FileStream(filePath, FileMode.Open);

            using (StreamReader reader = new StreamReader(fileStream))
            {
                string line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = reader.ReadLine()) != null)
                {
                    string[] record = line.Split(';');
                    Products m      = new Products
                    {
                        Title = record[0],
                        Price = Convert.ToDouble(record[1])
                    };
                    _context.Products.Add(m);
                }
                _context.SaveChanges();
            }

            ViewData["Message"] = output;
            return(View());
        }
Пример #24
0
        public void CreateOrder(dynamic UserAddress)
        {
            dynamic AddressJson = JsonConvert.DeserializeObject(UserAddress.ToString());
            var     userId      = _caller.Claims.Single(c => c.Type == "id");

            var cart_given_id = (from cart in _context.Carts
                                 where cart.UserId == int.Parse(userId.Value)
                                 select cart.Id).ToArray().First();

            var returnprice = (from entries in _context.Carts
                               where entries.Id == cart_given_id
                               select entries.CartTotalPrice).ToArray().First();

            var o = new Order
            {
                UserId          = int.Parse(userId.Value),
                AddressId       = AddressJson.AddressId,
                OrderStatusId   = 1,
                OrderTotalPrice = returnprice,
                OrderDate       = DateTime.Now
            };

            _context.Orders.Add(o);

            var query = (from entries in _context.CartProducts
                         where entries.CartId == cart_given_id
                         select entries).ToArray();

            foreach (var item in query)
            {
                var orderproduct = new OrderProduct
                {
                    OrderId       = o.Id,
                    ProductId     = item.ProductId,
                    OrderQuantity = item.CartQuantity
                };
                _context.OrderProduct.Add(orderproduct);
            }

            foreach (var item in query)
            {
                _context.CartProducts.Remove(item);
            }
            _context.SaveChanges();
        }
Пример #25
0
        public void CreateProduct(dynamic ProductDetails)
        {
            dynamic ProductDetailsJSON = JsonConvert.DeserializeObject(ProductDetails.ToString());

            int _categoryId;
            int _brandId;
            int _collectionId;
            int _typeid;

            ///////////////CATEGORY////////////////
            dynamic c = 1;

            if (ProductDetailsJSON.CategoryId != null)
            {
                int category = ProductDetailsJSON.CategoryId;
                c = _context.Categories.Find(category);
            }
            if (c == null || ProductDetailsJSON.CategoryId == null)
            {
                Category _Category = new Category()
                {
                    Id           = _context.Categories.Select(a => a.Id).Max() + 1,
                    CategoryName = ProductDetailsJSON.CategoryName
                };
                _context.Categories.Add(_Category);
                _categoryId = _Category.Id;
                //_context.SaveChanges();
            }
            else
            {
                _categoryId = ProductDetailsJSON.CategoryId;
            }

            ///////////////TYPE////////////////
            dynamic t = 1;

            if (ProductDetailsJSON.TypeId != null)
            {
                int type = ProductDetailsJSON.TypeId;
                t = _context.Types.Find(type);
            }
            if (t == null || ProductDetailsJSON.TypeId == null)
            {
                _Type _Type = new _Type()
                {
                    Id        = _context.Types.Select(a => a.Id).Max() + 1,
                    _TypeName = ProductDetailsJSON.TypeName
                };
                _context.Types.Add(_Type);
                _typeid = _Type.Id;

                Category_Type CT = new Category_Type()
                {
                    CategoryId = _categoryId,
                    _TypeId    = _typeid
                };
                _context.CategoryType.Add(CT);
            }
            else
            {
                _typeid = ProductDetailsJSON.TypeId;
            }

            ///////////////BRAND////////////////
            dynamic b = 1;

            if (ProductDetailsJSON.BrandId != null)
            {
                int brand = ProductDetailsJSON.BrandId;
                b = _context.Brands.Find(brand);
            }
            if (b == null || ProductDetailsJSON.BrandId == null)
            {
                Brand Brand = new Brand()
                {
                    Id        = _context.Brands.Select(a => a.Id).Max() + 1,
                    BrandName = ProductDetailsJSON.BrandName
                };
                _context.Brands.Add(Brand);
                _brandId = Brand.Id;
                //_context.SaveChanges();
            }
            else
            {
                _brandId = ProductDetailsJSON.BrandId;
            }

            ///////////////Collection////////////////
            dynamic co = 1;

            if (ProductDetailsJSON.CollectionId != null)
            {
                int coll = ProductDetailsJSON.CollectionId;
                co = _context.Collections.Find(coll);
            }
            if (co == null || ProductDetailsJSON.CollectionId == null)
            {
                Collection Collection = new Collection()
                {
                    Id             = _context.Collections.Select(a => a.Id).Max() + 1,
                    BrandId        = _brandId,
                    CollectionName = ProductDetailsJSON.CollectionName
                };
                _context.Collections.Add(Collection);
                _collectionId = Collection.Id;
            }
            else
            {
                _collectionId = ProductDetailsJSON.CollectionId;
            }

            ///////////////STOCK////////////////
            Stock Stock = new Stock()
            {
                //Id = ProductDetailsJSON.StockId,
                Id = _context.Stock.Select(a => a.Id).Max() + 1,
                ProductQuantity = ProductDetailsJSON.Stock
            };

            _context.Stock.Add(Stock);

            ///////////////PRODUCT////////////////
            Product Product = new Product()
            {
                ProductName          = ProductDetailsJSON.ProductName,
                _TypeId              = _typeid,       //ProductDetailsJSON.TypeId,
                CategoryId           = _categoryId,   //ProductDetailsJSON.CategoryId,
                CollectionId         = _collectionId, //ProductDetailsJSON.CollectionId,
                BrandId              = _brandId,      //ProductDetailsJSON.BrandId,
                StockId              = Stock.Id,      //ProductDetailsJSON.StockId,
                Id                   = _context.Products.Select(a => a.Id).Max() + 1,
                ProductNumber        = ProductDetailsJSON.ProductNumber,
                ProductEAN           = ProductDetailsJSON.ProductEAN,
                ProductInfo          = ProductDetailsJSON.ProductInfo,
                ProductDescription   = ProductDetailsJSON.ProductDescription,
                ProductSpecification = ProductDetailsJSON.ProductSpecification,
                ProductPrice         = ProductDetailsJSON.ProductPrice,
                ProductColor         = ProductDetailsJSON.ProductColor,
            };

            _context.Products.Add(Product);

            ///////////////IMAGE////////////////
            // ProductImage ProductImage = new ProductImage()
            // {
            //     ProductId = Product.Id,
            //     ImageURL = ProductDetailsJSON.ImageURL,
            //     //Id = ProductDetailsJSON.ImageId
            //     Id = _context.ProductImages.Select(a => a.Id).Max() + 1,
            // };
            // _context.ProductImages.Add(ProductImage);

            _context.SaveChanges();
        }
Пример #26
0
        public ActionResult EditUserInfo([FromBody] UserDetailsViewModel userDetails)
        {
            UserDetailsViewModelValidator validator = new UserDetailsViewModelValidator();

            FluentValidation.Results.ValidationResult results = validator.Validate(userDetails);

            foreach (var failure in results.Errors)
            {
                Errors.AddErrorToModelState(failure.PropertyName, failure.ErrorMessage, ModelState);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var         userId   = _caller.Claims.Single(c => c.Type == "id");
            var         userInfo = _context.Users.Find(int.Parse(userId.Value));
            Type        type     = typeof(UserDetailsViewModel);
            Task <bool> isvalid;
            int         count = 0;

            for (var element = 0; element < type.GetProperties().Count() - 1; element++)
            {
                string propertyName = type.GetProperties().ElementAt(element).Name;

                if (userDetails[propertyName] != null)
                {
                    if (userDetails[propertyName].ToString() != "")
                    {
                        bool isnull = _context.Users.Where(b => int.Parse(userId.Value) == b.Id && b[propertyName] == null).Select(a => a).ToArray().Length == 1 ? true : false;
                        if (isnull || userDetails[propertyName].ToString() != _context.Users.Where(b => int.Parse(userId.Value) == b.Id).Select(a => a[propertyName]).ToArray()[0].ToString())
                        {
                            if (propertyName == "EmailAddress")
                            {
                                isvalid = Utils.IsValidAsync(userDetails[propertyName].ToString());

                                if (isvalid.Result)
                                {
                                    userInfo[propertyName] = userDetails[propertyName];
                                    //Console.WriteLine("\nPropery Value: {0}", userInfo[propertyName]);
                                }
                            }

                            else
                            {
                                userInfo[propertyName] = userDetails[propertyName];
                                //Console.WriteLine("\nPropery Value: {0}", userInfo[propertyName]);
                            }

                            count++;
                            //Console.WriteLine("Count: {0}", count);
                            _context.Users.Update(userInfo);
                        }
                    }
                }
            }
            ;
            _context.SaveChanges();
            return(Ok());
        }
Пример #27
0
 public Order CreateOrder(Order order)
 {
     _ctx.Attach(order).State = EntityState.Added;
     _ctx.SaveChanges();
     return(order);
 }
 public Product CreateProduct(Product product)
 {
     _ctx.Attach(product).State = EntityState.Added;
     _ctx.SaveChanges();
     return(product);
 }
Пример #29
0
 public void Save()
 {
     context.SaveChanges();
 }