コード例 #1
0
        public ActionResult Create([Bind(Include = "Id,GameTitle,Publisher,ReleaseDate,Platform,Genre,Description,InStockAmount,Price")] Game game)
        {
            if (ModelState.IsValid)
            {
                db.Games.Add(game);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(game));
        }
コード例 #2
0
        //PUT REMOVED
        // Ajax.htmlForm does not support put and delete, only supports get and post.
        public HttpResponseMessage Post([FromBody] CategoryViewModel value)
        {
            if (value == null || String.IsNullOrEmpty(value.CategoryName))
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Category Name can't be empty!"));
            }

            using (GameStoreDBContext context = new GameStoreDBContext())
            {
                bool exist = context.Categories.Any(c => c.CategoryId == value.CategoryId);
                if (!exist)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Category [" + value.CategoryId + "] does not exist!"));
                }

                exist = context.Categories.Where(c => c.CategoryId != value.CategoryId).Any(c => c.CategoryName.Equals(value.CategoryName, StringComparison.OrdinalIgnoreCase));
                if (exist)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Category [" + value.CategoryName + "] is already existed, please try another name!"));
                }
                var category = context.Categories.Find(value.CategoryId);
                category.CategoryName = value.CategoryName;
                context.SaveChanges();
                HttpContext.Current.Cache.Remove("CategoryList");
                HttpContext.Current.Cache.Remove("Category" + value.CategoryId);
                return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
            }
        }
コード例 #3
0
        public HttpResponseMessage Post([FromBody] ProductViewModel value)
        {
            if (ModelState.IsValid)
            {
                if (value == null || String.IsNullOrEmpty(value.ProductName))
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Product Name can't be empty!"));
                }

                if (value.Discount < 0 || value.Discount > 100)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Discount must between 0 ~ 100."));
                }

                using (GameStoreDBContext context = new GameStoreDBContext())
                {
                    bool exist = context.Products.Any(c => c.ProductId == value.ProductId);
                    if (!exist)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "Product [" + value.ProductId + "] does not exist!"));
                    }

                    exist = context.Products.Where(c => c.ProductId != value.ProductId).Any(c => c.ProductName.Equals(value.ProductName, StringComparison.OrdinalIgnoreCase));
                    if (exist)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "Product [" + value.ProductName + "] is already existed, please try another name!"));
                    }
                    var product = context.Products.Find(value.ProductId);
                    if (product == null)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "No such product!"));
                    }

                    bool isAdvanced = HttpContext.Current.User.IsInRole("Advanced");
                    if (isAdvanced && product.UserId != HttpContext.Current.User.Identity.GetUserId())
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "You have no authorization to update this product!"));
                    }

                    HttpContext.Current.Cache.Remove("ProductList" + product.CategoryId);
                    product.ProductName = value.ProductName;
                    product.CategoryId  = value.CategoryId;
                    product.Price       = value.Price;
                    product.Image       = value.Image;
                    product.Condition   = value.Condition;
                    product.Discount    = value.Discount;
                    context.SaveChanges();
                    //context.Entry(product).CurrentValues.SetValues(value);
                    //context.SaveChanges();
                    HttpContext.Current.Cache.Remove("ProductList");
                    HttpContext.Current.Cache.Remove("ProductList" + value.CategoryId);
                    HttpContext.Current.Cache.Remove("Product" + product.ProductId);
                    return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "ModelState.IsValid=false"));
            }
        }
コード例 #4
0
 public static void AddImageToGameByID(int id, byte[] image)
 {
     using (var db = new GameStoreDBContext())
     {
         var selectedGame = (from game in db.Game
                             where game.ID == id
                             select game).First();
         selectedGame.Image = image;
         db.SaveChanges();
     }
 }
コード例 #5
0
        public IActionResult AddToCart(int id)
        {
            String userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

            var gameStoreUser = _context.Users.Include(user => user.Cart).Include(user => user.Cart.CartItems)
                                .Where(x => x.Id == userId).SingleOrDefault();

            if (gameStoreUser.Cart == null)
            {
                gameStoreUser.Cart = new Cart()
                {
                    CartItems = new List <CartItem>()
                };
                _context.Carts.Add(gameStoreUser.Cart);
                _context.Update(gameStoreUser);

                _context.SaveChanges();
                _context.Update(gameStoreUser);
            }

            List <CartItem> items = gameStoreUser.Cart.CartItems;

            if (items.Exists(x => x.GameId == id))
            {
                items.Where(x => x.GameId == id).SingleOrDefault().Qty++;
            }
            else
            {
                CartItem ci = new CartItem()
                {
                    GameId = id,
                    CartId = gameStoreUser.Cart.Id,
                    Qty    = 1
                };
                //_context.Add(ci);
                items.Add(ci);
            }
            _context.Update(gameStoreUser.Cart);
            _context.SaveChanges();
            return(PartialView());
        }
コード例 #6
0
        public static int AddAuthorToDB(string author)
        {
            var newAuthor = new Author {
                Manufacturer = author
            };

            using (var db = new GameStoreDBContext())
            {
                db.Author.Add(newAuthor);
                db.SaveChanges();
                return(newAuthor.ID);
            }
        }
コード例 #7
0
 public static void ChangeGameAuthor(int gameID, string newAuthorName)
 {
     using (var db = new GameStoreDBContext())
     {
         var currentAuthor = (from author in db.Author
                              where author.ID == (from game in db.Game
                                                  where game.ID == gameID
                                                  select game).FirstOrDefault().Author_ID
                              select author).First();
         currentAuthor.Manufacturer = newAuthorName;
         db.SaveChanges();
     }
 }
コード例 #8
0
        public HttpResponseMessage Create([FromBody] ProductViewModel value)
        {
            if (ModelState.IsValid)
            {
                if (value.Discount < 0 || value.Discount > 100)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Discount must between 0 ~ 100."));
                }
                using (GameStoreDBContext context = new GameStoreDBContext())
                {
                    bool exist = context.Products.Any(c => c.ProductName.Equals(value.ProductName, StringComparison.OrdinalIgnoreCase));
                    if (exist)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, "Product [" + value.ProductName + "] is already existed, please try another name!"));
                    }
                    //if (file != null)
                    //{
                    //    string[] formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...

                    //    // linq from Henrik Stenbæk
                    //    bool isimage = formats.Any(item => file.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));

                    //    if (!isimage)
                    //    {
                    //        return Request.CreateResponse(HttpStatusCode.OK, "The image format is not valid, must be .jpg, .png, .gif, or .jpeg");
                    //    }
                    //}
                    Product newProduct = context.Products.Create();
                    newProduct.ProductName = value.ProductName;
                    newProduct.CategoryId  = value.CategoryId;
                    newProduct.Price       = value.Price;
                    newProduct.Image       = value.Image;
                    newProduct.Condition   = value.Condition;
                    newProduct.Discount    = value.Discount;
                    newProduct.UserId      = User.Identity.GetUserId();
                    //string root = System.Web.Hosting.HostingEnvironment.MapPath("~/images/");
                    //string filename = string.Format(@"{0}.{1}", DateTime.Now.Ticks, System.IO.Path.GetExtension(file.FileName));
                    //file.SaveAs(System.IO.Path.Combine(root, filename));
                    //newProduct.Image = filename;
                    context.Products.Add(newProduct);
                    context.SaveChanges();
                    HttpContext.Current.Cache.Remove("ProductList");
                    HttpContext.Current.Cache.Remove("ProductList" + newProduct.CategoryId);
                    return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "ModelState.IsValid=false"));
            }
        }
コード例 #9
0
 public static void ChangeGameType(int gameID, string gameType, string description)
 {
     using (var db = new GameStoreDBContext())
     {
         var currentGameType = (from type in db.Type
                                where type.ID == (from game in db.Game
                                                  where game.ID == gameID
                                                  select game).FirstOrDefault().Type_ID
                                select type).First();
         currentGameType.Name        = gameType;
         currentGameType.Description = description;
         db.SaveChanges();
     }
 }
コード例 #10
0
 public static void ChangeGameGenre(int gameID, string genreName, string description)
 {
     using (var db = new GameStoreDBContext())
     {
         var currentGameGenre = (from genre in db.Genre
                                 where genre.ID == (from game in db.Game
                                                    where game.ID == gameID
                                                    select game).FirstOrDefault().Genre_ID
                                 select genre).First();
         currentGameGenre.Name        = genreName;
         currentGameGenre.Description = description;
         db.SaveChanges();
     }
 }
コード例 #11
0
        public static bool AddGameToDB(GameParams game)
        {
            using (var db = new GameStoreDBContext())
            {
                var currentGenreIds = (from genre in db.Genre
                                       where genre.Name == game.Genre
                                       select genre.ID);
                if (currentGenreIds.Count() < 1)
                {
                    return(false);
                }
                var currentGenreID = currentGenreIds.First();

                var currentTypeIds = (from type in db.Type
                                      where type.Name == game.Type
                                      select type.ID);
                if (currentTypeIds.Count() < 1)
                {
                    return(false);
                }
                var currentTypeID = currentTypeIds.First();

                var currentAuthorIds = (from author in db.Author
                                        where author.Manufacturer == game.Author
                                        select author.ID);
                if (currentAuthorIds.Count() < 1)
                {
                    return(false);
                }
                var currentAuthorID = currentAuthorIds.First();
                var currentGame     = new Game
                {
                    Name         = game.Name,
                    Max_Duration = game.maxDuration,
                    Min_Duration = game.minDuration,
                    Max_Players  = game.maxPlayers,
                    Min_Players  = game.minPlayers,
                    Genre_ID     = currentGenreID,
                    Type_ID      = currentTypeID,
                    Price        = game.Price,
                    Description  = game.Description,
                    Quantity     = game.Quantity,
                    Author_ID    = currentAuthorID,
                    Difficulty   = game.Difficulty
                };
                db.Game.Add(currentGame);
                db.SaveChanges();
                return(true);
            }
        }
コード例 #12
0
 public HttpResponseMessage Delete(int id)
 {
     using (GameStoreDBContext context = new GameStoreDBContext())
     {
         var order = context.Orders.Find(id);
         if (order == null)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, "No such order [" + id + "]."));
         }
         context.Orders.Remove(order);
         context.SaveChanges();
         return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
     }
 }
コード例 #13
0
 // DELETE api/<controller>/5
 public HttpResponseMessage Delete(int id)
 {
     using (GameStoreDBContext context = new GameStoreDBContext())
     {
         bool exist = context.Products.Any(p => p.CategoryId == id);
         if (exist)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, "There are products belong to Category [" + id + "], delete them first!"));
         }
         var category = context.Categories.Find(id);
         context.Categories.Remove(category);
         context.SaveChanges();
         HttpContext.Current.Cache.Remove("CategoryList");
         HttpContext.Current.Cache.Remove("Category" + id);
         return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
     }
 }
コード例 #14
0
 public static bool RemoveGameByID(int id)
 {
     using (var db = new GameStoreDBContext())
     {
         var gamesToDelete = (from game in db.Game
                              where game.ID == id
                              select game);
         if (gamesToDelete.Count() != 1)
         {
             return(false);
         }
         var gameToDelete = gamesToDelete.First();
         db.Game.Remove(gameToDelete);
         db.SaveChanges();
         return(true);
     }
 }
コード例 #15
0
        public static int AddGameTypeToDB(string gameType, string description)
        {
            var newType = new DB.Type {
                Name = gameType, Description = description
            };

            using (var db = new GameStoreDBContext())
            {
                if ((from currentType in db.Type where currentType.Name == gameType select currentType).Count() > 0)
                {
                    return(-1);
                }
                db.Type.Add(newType);
                db.SaveChanges();
                return(newType.ID);
            }
        }
コード例 #16
0
        public static int AddGenreToDB(string genre, string description)
        {
            var newGenre = new Genre {
                Name = genre, Description = description
            };

            using (var db = new GameStoreDBContext())
            {
                if ((from currentGenre in db.Genre where currentGenre.Name == genre select currentGenre).Count() > 0)
                {
                    return(-1);
                }
                db.Genre.Add(newGenre);
                db.SaveChanges();
                return(newGenre.ID);
            }
        }
コード例 #17
0
 public static OrderParams AddOrderToDB(OrderToDB order)
 {
     using (var db = new GameStoreDBContext())
     {
         var gameIDs_Count = new List <Tuple <int, int> >();
         foreach (var game in order.games)
         {
             gameIDs_Count.Add(new Tuple <int, int>(GetGameIDByName(game.Item1), game.Item2));
         }
         var currentClient = new Client()
         {
             Email = order.ClientMail,
             Name  = order.ClientName
         };
         db.Client.Add(currentClient);
         var currentOrder = new Order
         {
             Client_ID = currentClient.ID,
             Date      = order.Date
         };
         db.Order.Add(currentOrder);
         foreach (var gameID in gameIDs_Count)
         {
             var currentConnection = new Orders_Games()
             {
                 Game_ID      = gameID.Item1,
                 Order_ID     = currentOrder.ID,
                 Games_number = gameID.Item2
             };
             db.Orders_Games.Add(currentConnection);
             var gameToReduceQuantity = (from game in db.Game
                                         where game.ID == gameID.Item1
                                         select game).First();
             gameToReduceQuantity.Quantity -= gameID.Item2;
         }
         db.SaveChanges();
         var orderParams = new OrderParams()
         {
             Date  = currentOrder.Date,
             ID    = currentOrder.ID,
             games = ExtractGamesFromOrder(currentOrder)
         };
         return(orderParams);
     }
 }
コード例 #18
0
        public ActionResult CancelOrder(int id)
        {
            using (GameStoreDBContext context = new GameStoreDBContext())
            {
                var order = context.Orders.Find(id);
                if (order == null)
                {
                    ViewBag.Message = string.Format("No such order [{0}] found.", id);
                }
                else
                {
                    context.Orders.Remove(order);
                    context.SaveChanges();
                    ViewBag.Message = string.Format("Order [{0}] has been deleted!", id);
                }
            }

            return(RedirectToAction("Index"));
        }
コード例 #19
0
 public HttpResponseMessage Delete(int id)
 {
     using (GameStoreDBContext context = new GameStoreDBContext())
     {
         var product = context.Products.Find(id);
         if (product == null)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, "No such product!"));
         }
         bool isAdvanced = HttpContext.Current.User.IsInRole("Advanced");
         if (isAdvanced && product.UserId != HttpContext.Current.User.Identity.GetUserId())
         {
             return(Request.CreateResponse(HttpStatusCode.OK, "You have no authorization to delete this product!"));
         }
         context.Products.Remove(product);
         context.SaveChanges();
         HttpContext.Current.Cache.Remove("ProductList");
         HttpContext.Current.Cache.Remove("ProductList" + product.CategoryId);
         HttpContext.Current.Cache.Remove("Product" + id);
         return(Request.CreateResponse(HttpStatusCode.OK, "Okay"));
     }
 }
コード例 #20
0
        public static GameStoreDBContext CreateMockDb()
        {
            var options = new DbContextOptionsBuilder <GameStoreDBContext>().
                          UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            using (var context = new GameStoreDBContext(options))
            {
                context.Users.Add(new GameStoreUser {
                    Email = "*****@*****.**", Id = "*****@*****.**"
                });
                context.Developer.Add(new Developer {
                    Name = "Dev 1", City = "Toronto", DeveloperId = 1, StreetAddress = "123 Yonge", Telephone = "4164164164"
                });
                context.Genre.Add(new Genre {
                    Name = "Genre", Description = "Desc", GenreId = 1
                });
                context.Game.Add(new Game {
                    Id = 1, Name = "Game 1", Description = "Desc 1", DeveloperId = 1, GenreId = 1, ImageUrl = "", MinimumRequirements = "REQ", Price = 20.0m
                });
                context.SaveChanges();
            }
            return(new GameStoreDBContext(options));
        }
コード例 #21
0
        public override Task <IdentityResult> CreateAsync(AppUser user, string password)
        {
            try
            {
                if (!user.Membership.Equals("Regular") && !user.Membership.Equals("Advanced"))
                {
                    return(Task.FromResult(IdentityResult.Failed("Invalid membership!")));
                }
                AppUser existUser = _store.Users.Where(u => u.Email == user.Email).FirstOrDefault();
                if (existUser != null)
                {
                    return(Task.FromResult(IdentityResult.Failed("User with email [" + user.Email + "] already exists!")));
                }

                GameStoreDBContext context = (GameStoreDBContext)_store.Context;
                var newUser = context.Users.Create();
                newUser.Email        = user.Email;
                newUser.UserName     = user.UserName;
                newUser.PasswordHash = PasswordHasher.HashPassword(password);
                newUser.PhoneNumber  = user.PhoneNumber;
                newUser.Membership   = user.Membership;

                var role = context.Roles.Where(r => r.Name == user.Membership).First();
                newUser.Roles.Add(new IdentityUserRole {
                    RoleId = role.Id, UserId = newUser.Id
                });
                context.Users.Add(newUser);

                context.SaveChanges();

                return(Task.FromResult(IdentityResult.Success));
            }
            catch (Exception ex)
            {
                return(Task.FromResult(IdentityResult.Failed("DB Error")));
            }
        }
コード例 #22
0
        public ActionResult ProcessCreditResponse(String TransId, String TransAmount, String StatusCode, String AppHash)
        {
            String AppId     = ConfigurationHelper.GetAppId2();
            String SharedKey = ConfigurationHelper.GetSharedKey2();

            if (CreditAuthorizationClient.VerifyServerResponseHash(AppHash, SharedKey, AppId, TransId, TransAmount, StatusCode))
            {
                switch (StatusCode)
                {
                case ("A"): ViewBag.TransactionStatus = "Transaction Approved! Your order has been created!"; break;

                case ("D"): ViewBag.TransactionStatus = "Transaction Denied!"; break;

                case ("C"): ViewBag.TransactionStatus = "Transaction Cancelled!"; break;
                }
            }
            else
            {
                ViewBag.TransactionStatus = "Hash Verification failed... something went wrong.";
            }

            OrderViewModel model = new OrderViewModel();

            if (StatusCode.Equals("A"))
            {
                ShoppingCart      cart  = (ShoppingCart)Session["ShoppingCart"];
                CheckoutViewModel value = (CheckoutViewModel)Session["Checkout"];
                if (value != null)
                {
                    try
                    {
                        using (GameStoreDBContext context = new GameStoreDBContext())
                        {
                            Order newOrder = context.Orders.Create();
                            newOrder.FullName           = value.FullName;
                            newOrder.Address            = value.Address;
                            newOrder.City               = value.City;
                            newOrder.State              = value.State;
                            newOrder.Zip                = value.Zip;
                            newOrder.DeliveryDate       = DateTime.Now.AddDays(14);
                            newOrder.ConfirmationNumber = DateTime.Now.ToString("yyyyMMddHHmmss");
                            newOrder.UserId             = User.Identity.GetUserId();
                            context.Orders.Add(newOrder);
                            cart.GetItems().ForEach(c => context.OrderItems.Add(new OrderItem {
                                OrderId = newOrder.OrderId, ProductId = c.GetItemId(), Quantity = c.Quantity
                            }));
                            context.SaveChanges();
                            System.Web.HttpContext.Current.Cache.Remove("OrderList");
                            Session["ShoppingCart"] = null;
                            Session["CartCount"]    = 0;
                            Session["OrderCount"]   = (int)Session["OrderCount"] + 1;

                            var order = from o in context.Orders
                                        join u in context.Users
                                        on o.UserId equals u.Id
                                        where o.OrderId == newOrder.OrderId
                                        select new { o.OrderId, o.UserId, u.UserName, o.FullName, o.Address, o.City, o.State, o.Zip, o.ConfirmationNumber, o.DeliveryDate };
                            var ord = order.FirstOrDefault();
                            model = new OrderViewModel {
                                OrderId = ord.OrderId, UserId = ord.UserId, UserName = ord.UserName, FullName = ord.FullName, Address = ord.Address, City = ord.City, State = ord.State, Zip = ord.Zip, ConfirmationNumber = ord.ConfirmationNumber, DeliveryDate = ord.DeliveryDate
                            };

                            var orderitems = from i in context.OrderItems
                                             join p in context.Products
                                             on i.ProductId equals p.ProductId
                                             join c in context.Categories
                                             on p.CategoryId equals c.CategoryId
                                             where i.OrderId == newOrder.OrderId
                                             select new { i.OrderItemId, i.OrderId, i.ProductId, p.ProductName, p.CategoryId, c.CategoryName, p.Price, p.Image, p.Condition, p.Discount, i.Quantity };
                            model.Items = orderitems.Select(o => new OrderItemViewModel {
                                OrderItemId = o.OrderItemId, OrderId = o.OrderId, ProductId = o.ProductId, ProductName = o.ProductName, CategoryId = o.CategoryId, CategoryName = o.CategoryName, Price = o.Price, Image = o.Image, Condition = o.Condition, Discount = o.Discount, Quantity = o.Quantity
                            }).ToList();
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "Error Occurs:" + ex.Message;
                    }
                }
            }

            return(View("PlaceOrder", model));
        }
コード例 #23
0
        public static bool ChangeGameProperty(int gameID, string propertyName, string propertyValue)
        {
            using (var db = new GameStoreDBContext())
            {
                var currentGame = (from game in db.Game
                                   where game.ID == gameID
                                   select game).First();
                switch (propertyName)
                {
                case "Name":
                    var gameNames = (from game in db.Game
                                     where game.ID != gameID
                                     select game.Name);
                    if (gameNames.Contains(propertyValue))
                    {
                        return(false);
                    }
                    currentGame.Name = propertyValue;
                    break;

                case "Description":
                    currentGame.Description = propertyValue;
                    break;

                case "Price":
                    currentGame.Price = decimal.Parse(propertyValue);
                    break;

                case "Quantity":
                    currentGame.Quantity = int.Parse(propertyValue);
                    break;

                case "Author":
                    break;

                case "minDuration":
                    currentGame.Min_Duration = int.Parse(propertyValue);
                    break;

                case "maxDuration":
                    currentGame.Max_Duration = int.Parse(propertyValue);
                    break;

                case "Genre":
                    break;

                case "minPlayers":
                    currentGame.Min_Players = int.Parse(propertyValue);
                    break;

                case "maxPlayers":
                    currentGame.Max_Players = int.Parse(propertyValue);
                    break;

                case "Type":
                    break;
                }
                db.SaveChanges();
                return(true);
            }
        }