Ejemplo n.º 1
0
        public void TestParseCreatesValidObjectWithNoQuotesAroundProductionTitle()
        {
            var productionDefinition = @"# Guitar Hero 5 (2009) (VG)";
            var expected = new VideoGame
            {
                Title = "Guitar Hero 5",
                Year = 2009
            };

            var logger = new Mock<ILog>();
            var actual = new ProductionParser(logger.Object).Parse(productionDefinition);
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            //Strategy
            VideoGame snes = new VideoGame(new InserirJogoSuperNintendo());

            snes.InserirJogo();

            Console.WriteLine();

            VideoGame play = new VideoGame(new InserirJogoPlaystation());

            play.InserirJogo();


            Console.ReadKey();

            Console.Clear();

            //Proxy
            PadraoProxy();

            Console.ReadKey();
        }
        private bool VideoGameFilter(object item)
        {
            VideoGame videoGame = item as VideoGame;

            bool match = true;;

            // Search
            match = videoGame.Name.ToUpper().Contains(_searchInput.ToUpper());
            // Currently Playing - only checjk if match is still true
            if (ShowCurrentlyPlaying && match)
            {
                match = videoGame.CurrentlyPlaying == ShowCurrentlyPlaying;
            }

            // Hide DLC - only checjk if match is still true
            if (HideDLC && match)
            {
                match = videoGame.MediaType.Name != "DLC";
            }


            return(match);
        }
        public bool CreateVideoGame(VideoGameCreate model)
        {
            var entity =
                new VideoGame()//Creating an instance of a new VideoGame
            {
                GameName           = model.GameName,
                AgeRating          = model.AgeRating,
                MaxNumberOfPlayers = model.MaxNumberOfPlayers,
                MinNumberOfPlayers = model.MinNumberOfPlayers,
                PublishYear        = model.PublishYear,
                TeamGame           = model.TeamGame,
                ConsoleType        = model.ConsoleType,
                OnlineGamePlay     = model.OnlineGamePlay,
                Genre     = model.Genre,
                StorageId = model.StorageId,
            };

            using (var ctx = new ApplicationDbContext()) //Saving the created game to the database
            {
                ctx.VideoGames.Add(entity);              //Adding game to DataBase
                return(ctx.SaveChanges() == 1);
            }
        }//End public CreateVideoGame
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Livro l1 = new Livro("Harry Potter", 40, 50, "J.K Rowling", "fantasia", 300);
            Livro l2 = new Livro("Senhor dos Aneis", 60, 30, "J. R. R. Tolkien", "fantasia", 500);
            Livro l3 = new Livro("Java POO", 20, 50, "GFT", "educativo", 500);

            VideoGame ps4      = new VideoGame("PS4", 1800, 100, "Sony", "Slim", false);
            VideoGame ps4Usado = new VideoGame("PS4", 1000, 7, "Sony", "Slim", true);
            VideoGame xbox     = new VideoGame("Xbox one", 1500, 500, "Microsoft", "Slim", false);


            List <Livro> livros = new List <Livro>();

            livros.Add(l1);
            livros.Add(l2);
            livros.Add(l3);


            List <VideoGame> games = new List <VideoGame>();

            games.Add(ps4);
            games.Add(xbox);
            games.Add(ps4Usado);

            Loja americanas = new Loja("Americanas", "124546546", livros, games);

            l2.CalculaImposto();
            l3.CalculaImposto();

            ps4Usado.CalculaImposto();
            ps4.CalculaImposto();


            americanas.listaLivros();
            americanas.listaVideoGames();
            americanas.CalculaPatrimonio();
        }
        public ActionResult UpdateVideoGame(VideoGame videoGame)
        {
            var allCategory = _categoryService.GetAllByMainCategoryId(3); // 1 = Movie 2= Series 3= VideoGames 4=Book
            List <SelectListItem> category = (from i in allCategory
                                              select new SelectListItem
            {
                Value = i.Id.ToString(),
                Text = i.Name
            }).ToList();

            ViewBag.Category = category;

            VideoGame updatedVideoGame = new VideoGame();

            updatedVideoGame.Id                   = videoGame.Id;
            updatedVideoGame.VideoGameName        = videoGame.VideoGameName;
            updatedVideoGame.VideoGameDescription = videoGame.VideoGameDescription;
            updatedVideoGame.CategoryId           = videoGame.CategoryId;
            updatedVideoGame.IMDBScore            = videoGame.IMDBScore;

            updatedVideoGame.ReleaseDate = videoGame.ReleaseDate;
            updatedVideoGame.VideoURL    = videoGame.VideoURL;
            updatedVideoGame.CreatedDate = videoGame.CreatedDate;


            if (Request.Files[0].ContentLength > 0)
            {
                updatedVideoGame.ImageURL = FileHelper.Add(Request.Files[0], "VideoGame");
            }
            else
            {
                updatedVideoGame.ImageURL = TempData["ImageURL"].ToString();
            }
            _videoGameService.Update(updatedVideoGame);
            TempData["UpdatedMessage"] = "Kayıt Güncellendi";
            return(RedirectToAction("VideoGameList"));
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            Livro l1 = new Livro("Harry Potter", 40, 50, "J.K.Rowlling", "fantasia", 300);
            Livro l2 = new Livro("Senhor dos Anéis", 60, 30, "J. R. R. Tolkien", "fantasia", 500);
            Livro l3 = new Livro("Java POO", 20, 50, "GFT", "educativo", 500);

            VideoGame ps4      = new VideoGame("PS4", 1800, 100, "Sony", "Slim", false);
            VideoGame ps4Usado = new VideoGame("PS4", 1000, 7, "Sony", "Slim", true);
            VideoGame xbox     = new VideoGame("XBOX", 1500, 500, "Microsoft", "One", false);

            List <Livro> livros = new List <Livro>
            {
                l1,
                l2,
                l3
            };

            List <VideoGame> videoGames = new List <VideoGame>
            {
                ps4,
                ps4Usado,
                xbox
            };

            Loja americanas = new Loja("Americanas", "12345678", livros, videoGames);

            l2.CalculaImposto();
            l3.CalculaImposto();

            ps4Usado.CalculaImposto();
            ps4.CalculaImposto();

            americanas.ListaLivros();
            americanas.ListaVideoGames();
            americanas.CalculaPatrimonio();
        }
Ejemplo n.º 8
0
        public static List <VideoGame> GetVideoGameList(int GameID)
        {
            //create empty list to hold objects
            List <VideoGame> videogames = new List <VideoGame>();

            //get a connection from DB class
            using (SqlConnection conn = DB.GetConnection())
            {
                //Create a comnmand using the connection
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandText = "SELECT * FROM VideoGames WHERE GenreID = @GenreID;";
                    cmd.Parameters.AddWithValue("@GenreID", GameID);

                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        //generate a new object
                        // and fill it with data from reader
                        VideoGame videogame = new VideoGame();
                        videogame.GameID      = reader.GetInt32(0);
                        videogame.Title       = reader.GetString(1);
                        videogame.System      = reader.GetString(2);
                        videogame.ReleaseDate = reader.GetString(3);
                        videogame.ESRB        = reader.GetString(4);
                        videogame.Publisher   = reader.GetString(5);
                        videogame.Developer   = reader.GetString(6);
                        //add the filled category to my list
                        videogames.Add(videogame);
                    }
                }
            }
            //return the list
            return(videogames);
        }
        public ActionResult Save(VideoGame videoGame)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new VideoGamesFormViewModel
                {
                    VideoGame = videoGame
                };
                return(View("VideoGamesForm", viewModel));
            }

            if (videoGame.Id == 0)
            {
                _context.VideoGames.Add(videoGame);
            }
            else
            {
                var videoGameInDb = _context.VideoGames.Single(c => c.Id == videoGame.Id);

                videoGameInDb.Name = videoGame.Name;
            }
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 10
0
        public VideoGame PatchVideoGame(string id, VideoGame gameBody)
        {
            VideoGame gameToPatch = new VideoGame();
            int       index       = this.store.list.FindIndex(game => game.id == id);

            if (gameToPatch != null)
            {
                gameToPatch.title          = gameBody.title;
                gameToPatch.releaseYear    = gameBody.releaseYear;
                gameToPatch.recommendedAge = gameBody.recommendedAge;
                gameToPatch.company        = gameBody.company;
                gameToPatch.isEvaluated    = gameBody.isEvaluated;
                gameToPatch.rating         = gameBody.rating;
                gameToPatch.description    = gameBody.description;
                gameToPatch.characters     = gameBody.characters;

                this.store.list[index] = gameToPatch;
            }
            else
            {
                gameToPatch.error = "ERROR!! DATOS NO INSERTADOS";
            }
            return(gameToPatch);
        }
Ejemplo n.º 11
0
        public void Deve_criar_um_video_game()
        {
            var videoGame = new VideoGame(_nomeVideoGame, _precoVideoGame, _quantidadeVideoGame, _marca, _modelo, _isUsado);

            Assert.NotNull(videoGame);
        }
Ejemplo n.º 12
0
 public void addVideoGame(VideoGame videogame)
 {
     //TODO data validation on the server, never trust the client to do it.
     db.VideoGames.Add(videogame);
     db.SaveChanges();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Adds order to database
        /// </summary>
        /// <param name="cart">The cart of the user who is making the order</param>
        /// <returns>ReceiptView</returns>
        public IActionResult AddOrder(Cart cart)
        {
            // Get User
            user = HttpContext.Session.GetObject <User>("User");
            if (user == null)
            {
                Log.Error("User session was not found");
                return(RedirectToAction("Login", "Home"));
            }
            // Ensure model state
            if (ModelState.IsValid)
            {
                // Create new order object and set values
                Order order = new Order();
                order.totalCost  = cart.totalCost;
                order.locationId = user.locationId;
                order.orderDate  = DateTime.Now;
                NpgsqlDateTime npgsqlDateTime = order.orderDate; // Used for API call
                order.userId = user.id;

                // Set up API calls
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(url);

                    // Serialize order objecto to be added
                    var json = JsonConvert.SerializeObject(order);
                    var data = new StringContent(json, Encoding.UTF8, "application/json");

                    // Use POST method to add to DB
                    var response = client.PostAsync("order/add", data);
                    response.Wait();

                    while (response.Result.IsSuccessStatusCode)
                    {
                        // Added new order successfully
                        // Now get order we just added to map orderId
                        response = client.GetAsync($"order/get?dateTime={npgsqlDateTime}");
                        response.Wait();
                        var result   = response.Result.Content.ReadAsStringAsync();
                        var newOrder = JsonConvert.DeserializeObject <Order>(result.Result);

                        Log.Information($"Successfully created order: {newOrder.id}");
                        // Got order back successfully
                        order.id = newOrder.id;
                        foreach (var item in user.cart.cartItems)
                        {
                            // For each item in cart, map to LineItem object
                            VideoGame videoGame = item.videoGame;
                            LineItem  lineItem  = new LineItem();
                            lineItem.orderId     = order.id;
                            lineItem.videoGameId = item.videoGameId;
                            lineItem.cost        = videoGame.cost;
                            lineItem.quantity    = item.quantity;

                            // Serialize LineItem object and add to db using POST method
                            json     = JsonConvert.SerializeObject(lineItem);
                            data     = new StringContent(json, Encoding.UTF8, "application/json");
                            response = client.PostAsync("lineitem/add", data);
                            response.Wait();
                            Log.Information($"Successfully create lineItem: {json}");

                            // Added new line item successfully
                            // Get inventory item and update quantity
                            response = client.GetAsync($"inventoryitem/get/{user.locationId}/{item.videoGameId}");
                            response.Wait();
                            result = response.Result.Content.ReadAsStringAsync();
                            var inventoryItem = JsonConvert.DeserializeObject <InventoryItem>(result.Result);
                            inventoryItem.quantity -= item.quantity;

                            json     = JsonConvert.SerializeObject(inventoryItem);
                            data     = new StringContent(json, Encoding.UTF8, "application/json");
                            response = client.PutAsync("inventoryitem/update", data);
                            response.Wait();

                            Log.Information($"Successfully updated inventoryItem: {json}");
                        }

                        // Clear cart items and redirect to receipt view
                        user.cart.cartItems.Clear();
                        user.cart.totalCost = 0;
                        HttpContext.Session.SetObject("User", user);
                        return(RedirectToAction("Receipt", order));
                    }
                }
            }
            Log.Error("Unable to create order");
            alertService.Warning("Unable to complete order");
            return(RedirectToAction("GetInventory", "Customer"));
        }
Ejemplo n.º 14
0
 protected VideoGameDecorator(VideoGame game)
 {
     _videoGame = game;
 }
 public void Add(VideoGame videoGame)
 {
     _context.VideoGames.Add(videoGame);
     _context.SaveChanges();
 }
Ejemplo n.º 16
0
        public void TestParseCreatesValidVideoGameObjectWithNonWordCharacters()
        {
            var videoGameString = @"# .hack//G.U. Vol. 1: Saitan (2006) (VG)";
            var expected = new VideoGame
            {
                Title = ".hack//G.U. Vol. 1: Saitan",
                Year = 2006
            };

            var logger = new Mock<ILog>();
            var actual = new ProductionParser(logger.Object).Parse(videoGameString);
            Assert.AreEqual(expected, actual);
        }
        //public List<UsersGamesRelation> GetUserGamesStats(int userid)
        //{
        //    return _db.UsersGamesRelations
        //        .Where(u => u.UserId == userid)
        //        .Include(g => g.Game)
        //        .Include(ga => ga.GameAccount)
        //        .Include(gs => gs.GameAccount.GameAccountStats).ToList();
        //}
        //public Dictionary<string, GameAccountStats> GetGamesTitlesDict(List<UsersGamesRelation> usergamelist, int userid)
        //{
        //    return usergamelist
        //        .Where(u => u.UserId == userid)
        //        .Select(ga => ga.GameAccount.GameAccountStats)
        //        .ToDictionary(g => g.GameAccount.UserGame.Game.Title);
        //}

        public async Task <IEnumerable <int> > GetGamesIdFocus(VideoGame game)
        {
            return(await _db.UsersGamesRelations
                   .Where(g => g.Game.Title == game.Title && g.IsFavoriteGame == true)
                   .Select(g => g.GameId).ToListAsync());
        }
 public void Add(VideoGame videoGame)
 {
     _videoGameDal.Add(videoGame);
 }
Ejemplo n.º 19
0
        public List <VideoGame> SeedFrom(IList <VideoGameViewModel> videoGames)
        {
            foreach (var game in videoGames)
            {
                var entity = new VideoGame()
                {
                    Title = game.Title,
                    AvailableForPurchase = true,
                    Description          = game.Description,
                    Price = new Random().Next(4000, 6000) / 1000.00m
                };

                var existingGame = _unitOfWork.videoGameRepository.All.FirstOrDefault(g => g.Title == entity.Title);

                if (existingGame == null)
                {
                    _unitOfWork.videoGameRepository.Create(entity);
                }

                foreach (var developer in game.Developers)
                {
                    var developerEntity = new Company()
                    {
                        Name          = developer.Name,
                        CompanyTypeId = developer.CompanyTypeId,
                    };

                    var existingDev = _unitOfWork.companyRepository.All.FirstOrDefault(company => company.Name == developer.Name);

                    if (existingDev == null)
                    {
                        _unitOfWork.companyRepository.Create(developerEntity);
                    }

                    var relationship = new CompanyVideoGame()
                    {
                        Company   = developerEntity,
                        VideoGame = entity
                    };

                    _unitOfWork.companyVideoGameRepository.Create(relationship);
                }

                foreach (var publisher in game.Publishers)
                {
                    var publisherEntity = new Company()
                    {
                        Name          = publisher.Name,
                        CompanyTypeId = publisher.CompanyTypeId,
                    };

                    var existingPublisher = _unitOfWork.companyRepository.All.FirstOrDefault(company => company.Name == publisher.Name);

                    if (existingPublisher == null)
                    {
                        _unitOfWork.companyRepository.Create(publisherEntity);
                    }

                    var relationship = new CompanyVideoGame()
                    {
                        Company   = publisherEntity,
                        VideoGame = entity
                    };

                    _unitOfWork.companyVideoGameRepository.Create(relationship);
                }

                _unitOfWork.Commit();
            }

            var games = _unitOfWork.videoGameRepository.All.ToList();

            return(games);
        }
Ejemplo n.º 20
0
 private IProduction ParseVideoGame(Match regexMatch)
 {
     var videoGame = new VideoGame();
     videoGame.Title = ParseTitle(regexMatch);
     videoGame.Year = ParseYear(regexMatch);
     return videoGame;
 }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            // string[] videoGameTitles = new string[0];
            // string[] videoGamePublishers = new string[0];

            // int[] prices = new int[0];
            // int[] yearReleased = new int[0];
            VideoGame[] games = new VideoGame[0];

            VideoGame game;

            while (true)
            {
                // game = new VideoGame();
                Console.Write("Please enter the title of the video game: ");
                string gameTitle = Console.ReadLine();
                Console.Write("Please enter the publisher of the title: ");
                string gamePublisher = Console.ReadLine();
                Console.Write("Please enter the price of the game: ");
                int gamePrice = int.Parse(Console.ReadLine());
                Console.Write("Please enter the year the game was released: ");
                int gameReleaseYear = int.Parse(Console.ReadLine());

                game = new VideoGame(gameTitle, gamePublisher, gamePrice, gameReleaseYear);

                // game.SetTitle(gameTitle);
                // game.SetPublisher(gamePublisher);
                // game.SetPrice(gamePrice);
                // game.SetReleasedYear(gameReleaseYear);

                // Array.Resize(ref videoGameTitles, videoGameTitles.Length + 1);
                // Array.Resize(ref videoGamePublishers, videoGamePublishers.Length + 1);
                // Array.Resize(ref prices, prices.Length + 1);
                // Array.Resize(ref yearReleased, yearReleased.Length + 1);

                // videoGameTitles[videoGameTitles.Length - 1] = gameTitle;
                // videoGamePublishers[videoGamePublishers.Length - 1]  = gamePublisher;
                // prices[prices.Length - 1] = gamePrice;
                // yearReleased[yearReleased.Length - 1] = gameReleaseYear;

                Array.Resize(ref games, games.Length + 1);
                games[games.Length - 1] = game;

                Console.Write("Would like to enter another? (y/n): ");
                string response = Console.ReadLine().ToUpper();
                if (response == "Y")
                {
                    continue;
                }
                else if (response == "N")
                {
                    break;
                }
            }


            for (int i = 0; i < games.Length; i++)
            {
                Console.WriteLine($"{games[i].GetTitle()} {games[i].GetPublisher()} {games[i].GetPrice()} {games[i].GetReleasedYear()}");
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to the Video Game library!");
            while (true)
            {
                Console.Write(GetMenu());
                string menuResponse = Console.ReadLine();

                switch (menuResponse)
                {
                case "1":
                    VideoGame game = EnterGameInfo();

                    Array.Resize(ref games, games.Length + 1);
                    games[games.Length - 1] = EnterGameInfo();

                    break;

                case "2":
                    Console.Write("Enter the title that you are searching for: ");
                    string titleSearch = Console.ReadLine();

                    DisplayByTitle(titleSearch);
                    break;

                case "3":
                    Console.Write("Enter the publisher that you want to filter by: ");
                    string    publisherFilter = Console.ReadLine();
                    VideoGame game1           = DisplayPublisher(publisherFilter);
                    if (game1 == null)
                    {
                        Console.WriteLine($"No results for {publisherFilter}");
                    }
                    else
                    {
                    }
                    break;

                case "4":
                    Console.WriteLine("Thank you for using this program!");
                    System.Threading.Thread.Sleep(1000);
                    Environment.Exit(0);
                    break;

                default:
                    Console.WriteLine("Error: Invalid input");
                    continue;
                }

                Array.Resize(ref games, games.Length + 1);
                games[games.Length - 1] = EnterGameInfo();

                Console.Write("Would like to enter another? (y/n): ");
                string response = Console.ReadLine().ToUpper();
                if (response == "Y")
                {
                    continue;
                }
                else if (response == "N")
                {
                    break;
                }
            }


            for (int i = 0; i < games.Length; i++)
            {
                Console.WriteLine($"{games[i].ToString()}");
            }
        }
Ejemplo n.º 23
0
 public IActionResult Edit(VideoGame obj)
 {
     _db.VideoGame.Update(obj);
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
        public async Task <IActionResult> Delete(int id)
        {
            VideoGame game = await VideoGameDB.GetGameById(id, _context);

            return(View(game));
        }
Ejemplo n.º 25
0
        /// <summary>Creates the project.</summary>
        /// <param name="name">name project</param>
        /// <param name="directory">directory project</param>
        /// <param name="mode">mode project</param>
        private void CreateProject(string name, string directory, string mode)
        {
            if (!Directory.Exists(directory + "/" + name))
            {
                string dir        = directory + "/" + name;
                string assetPath  = directory + "/" + name + "/Assets";
                string configPath = directory + "/" + name + "/Config";
                string dataPath   = directory + "/" + name + "/Data";
                string libPath    = directory + "/" + name + "/Lib";

                Project project = new Project(name, dir);
                Logger.Log("Create project " + " name: " + name + " directory: " + dir);


                projects.Add(project);
                LocalData.Save <List <Project> >("Projects", projects);
                Logger.Log("Saves the project in file");



                Directory.CreateDirectory(dir);
                Directory.CreateDirectory(assetPath);
                Directory.CreateDirectory(configPath);
                Directory.CreateDirectory(dataPath);
                Directory.CreateDirectory(libPath);

                Logger.Log("Create directorys of project.");

                string projectFile = File.ReadAllText(Application.ProjectFolder + "/Resources/DefaultPr.txt", Encoding.UTF8);
                File.WriteAllText(dir + "/" + name + ".csproj", projectFile, Encoding.UTF8);
                Logger.Log("Created .csproj");

                string solutionFile = File.ReadAllText(Application.ProjectFolder + "/Resources/DefaultSl.txt", Encoding.UTF8).Replace("Example", name);
                File.WriteAllText(dir + "/" + name + ".sln", solutionFile, Encoding.UTF8);
                Logger.Log("Created .sln");

                string program = File.ReadAllText(Application.ProjectFolder + "/Resources/Program.txt", Encoding.UTF8);
                File.WriteAllText(dir + "/" + "Program" + ".cs", program, Encoding.UTF8);
                Logger.Log("Created Program.cs");

                File.Copy(Application.ProjectFolder + "/Resources/Core-SFML.dll", libPath + "/" + "Core-SFML" + ".dll");
                File.Copy(Application.ProjectFolder + "/Resources/Core.dll", libPath + "/" + "Core" + ".dll");
                File.Copy(Application.ProjectFolder + "/Resources/Tools.dll", libPath + "/" + "Tools" + ".dll");
                Logger.Log("Copied .DLLS");

                VideoGame game = VideoGame.Builder()
                                 .Config(Config.Builder().Name(name).Build())
                                 .SceneManager(SceneManager.Builder().Scene(new Scene("Default")).Build())
                                 .Build();

                Logger.Log("Created default game");

                LocalData.Save <VideoGame>("Data", dataPath, game);

                Logger.Log("Saved default game");

                Project.Current   = project;
                Project.VideoGame = game;

                Close();
            }
        }
Ejemplo n.º 26
0
        public ActionResult New(string typeId)
        {
            if (typeId == "Default")
            {
                return(View("ItemForm"));
            }

            if (typeId == "Desktop")
            {
                Desktop desktop = new Desktop();
                return(View("DesktopForm", desktop));
            }

            if (typeId == "Camera")
            {
                Camera camera = new Camera();
                return(View("CameraForm", camera));
            }

            if (typeId == "CarryingBag")
            {
                CarryingBag carryingBag = new CarryingBag();
                return(View("CarryingBagForm", carryingBag));
            }

            if (typeId == "GameConsole")
            {
                GameConsole gameConsole = new GameConsole();
                return(View("GameConsoleForm", gameConsole));
            }

            if (typeId == "Laptop")
            {
                Laptop laptop = new Laptop();
                return(View("LaptopForm", laptop));
            }

            if (typeId == "MajorAppliance")
            {
                MajorAppliance majorAppliance = new MajorAppliance();
                return(View("MajorApplianceForm", majorAppliance));
            }

            if (typeId == "MouseAndKeyBoard")
            {
                MouseAndKeyBoard mouseAndKeyBoard = new MouseAndKeyBoard();
                return(View("MouseAndKeyBoardForm", mouseAndKeyBoard));
            }

            if (typeId == "Movie")
            {
                Movie movie = new Movie();
                return(View("MovieForm", movie));
            }

            if (typeId == "Software")
            {
                Software software = new Software();
                return(View("SoftwareForm", software));
            }

            if (typeId == "VideoGame")
            {
                VideoGame videoGame = new VideoGame();
                return(View("VideoGameForm", videoGame));
            }


            return(View("ItemForm"));
        }
Ejemplo n.º 27
0
        public IActionResult AddInventoryItem(InventoryItemViewModel model)
        {
            user = HttpContext.Session.GetObject <User>("User");
            if (user == null)
            {
                Log.Error("User session was not found");
                return(RedirectToAction("Login", "Home"));
            }
            // Create Video game
            VideoGame newVideoGame = new VideoGame();

            newVideoGame.name        = model.name;
            newVideoGame.platform    = model.platform;
            newVideoGame.esrb        = model.esrb;
            newVideoGame.cost        = model.cost;
            newVideoGame.description = model.description;
            newVideoGame.apiId       = model.apiId;
            newVideoGame.imageURL    = model.imageURL;

            // Add video game to database
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                var json     = JsonConvert.SerializeObject(newVideoGame);
                var data     = new StringContent(json, Encoding.UTF8, "application/json");
                var response = client.PostAsync("videogame/add", data);
                response.Wait();
                var result = response.Result;
                if (result.IsSuccessStatusCode)
                {
                    // Successfully added new video game
                    // Get videogame back from db to get id value
                    response = client.GetAsync($"videogame/get/name?name={newVideoGame.name}");
                    response.Wait();
                    result = response.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        var jsonString = result.Content.ReadAsStringAsync();
                        jsonString.Wait();
                        newVideoGame = JsonConvert.DeserializeObject <VideoGame>(jsonString.Result);

                        // Create new inventory item and add to DB
                        InventoryItem newItem = new InventoryItem();
                        newItem.locationId  = model.locationId;
                        newItem.quantity    = model.quantity;
                        newItem.videoGameId = newVideoGame.id;

                        json     = JsonConvert.SerializeObject(newItem);
                        data     = new StringContent(json, Encoding.UTF8, "application/json");
                        response = client.PostAsync("inventoryitem/add", data);
                        response.Wait();
                        result = response.Result;
                        if (result.IsSuccessStatusCode)
                        {
                            // Successfully added inventory item
                            alertService.Success($"Successfully added {newVideoGame.name} to inventory");
                            return(RedirectToAction("GetInventory", "Manager", new { locationId = user.locationId }));
                        }
                    }
                }
                // Failed
                alertService.Danger("Something went wrong");
                return(RedirectToAction("GetInventory", "Manager", user.locationId));
            }
        }
 public void Update(VideoGame videoGame)
 {
     _videoGameDal.Update(videoGame);
 }
Ejemplo n.º 29
0
        public ActionResult Post([FromBody] VideoGame game)
        {
            var createdGame = gameService.AddVideoGame(game);

            return(Created("api/games", createdGame));
        }
 public void Update(VideoGame videoGame)
 {
     _context.VideoGames.AddOrUpdate(videoGame);
     _context.SaveChanges();
 }
Ejemplo n.º 31
0
 public IHttpActionResult PutVideoGame(VideoGame videoGame)
 {
     return(StatusCode(HttpStatusCode.NotImplemented));
 }
Ejemplo n.º 32
0
 private void OnEditVideoGame(VideoGame videoGame)
 {
     EditVideoGameRequested(videoGame);
 }
Ejemplo n.º 33
0
        public static void Initialize(this Context context)
        {
            context.Database.EnsureCreated();

            var platform1 = new Platform()
            {
                Id = 1, Name = "N64"
            };
            var platform2 = new Platform()
            {
                Id = 2, Name = "GameCube"
            };
            var platform3 = new Platform()
            {
                Id = 3, Name = "Wii"
            };
            var platform4 = new Platform()
            {
                Id = 4, Name = "Wii U"
            };
            var platform5 = new Platform()
            {
                Id = 5, Name = "Switch"
            };
            var platform6 = new Platform()
            {
                Id = 6, Name = "PlayStation"
            };
            var platform7 = new Platform()
            {
                Id = 7, Name = "PlayStation 2"
            };
            var platform8 = new Platform()
            {
                Id = 8, Name = "PlayStation 3"
            };
            var platform9 = new Platform()
            {
                Id = 9, Name = "PlayStation 4"
            };
            var platform10 = new Platform()
            {
                Id = 10, Name = "Xbox"
            };
            var platform11 = new Platform()
            {
                Id = 11, Name = "Xbox 360"
            };
            var platform12 = new Platform()
            {
                Id = 12, Name = "Xbox One"
            };

            AddPlatforms(context,
                         platform1,
                         platform2,
                         platform3,
                         platform4,
                         platform5,
                         platform6,
                         platform7,
                         platform8,
                         platform9,
                         platform10,
                         platform11,
                         platform12
                         );

            var videoGame1 = new VideoGame()
            {
                Id          = 1,
                Title       = "Super Mario 64",
                PublishedOn = new DateTime(1996, 1, 1),
                PlatformId  = 1
            };
            var videoGame2 = new VideoGame()
            {
                Id          = 2,
                Title       = "Resident Evil",
                PublishedOn = new DateTime(1994, 1, 1),
                PlatformId  = 6
            };
            var videoGame3 = new VideoGame()
            {
                Id          = 3,
                Title       = "Halo",
                PublishedOn = new DateTime(2000, 1, 1),
                PlatformId  = 10
            };

            AddVideoGames(context,
                          videoGame1,
                          videoGame2,
                          videoGame3
                          );
        }