Exemplo n.º 1
0
        public ActionResult Create(CommentViewModel viewModel)
        {
            var model = new Comment()
            {
                Alias           = viewModel.Alias,
                CreatorDateTime = DateTime.Now,
                Email           = viewModel.Email,
                QuestionId      = viewModel.Id,
                Text            = viewModel.Text
            };

            dbContext.Comments.Add(model);
            dbContext.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> OnGet(int id, int?choice)
        {
            Game = await _context.Games.FirstOrDefaultAsync(m => m.GameId == id);

            if (choice == 1)
            {
                if (!BLL.ShipPlacement.RndPlacement(Game, false))
                {
                    Message = "You have set too small board for those ship sizes!";
                    return(Page());
                }
                _context.Update(Game);
                _context.SaveChanges();
                return(RedirectToPage("PlayGame", new { id = Game.GameId }));
            }
            return(Page());
        }
Exemplo n.º 3
0
        /***************************************/
        /*  START ProductProcess Data Utilities */

        /// <summary>
        /// Generates the default standards.
        /// Runs each time a product or process is created
        /// Reconciles any missing pair of product and process
        /// Defaults to 0 standard duration and quantity
        /// </summary>
        public void GenerateDefaultStandards()
        {
            // Get a list of all products and processes
            // We want both Active and Inactive to not orphan any that may potentially be activated

            List <Product> products  = GetProducts();
            List <Process> processes = GetProcesses();

            // Get all existing ProductsProcessses
            List <ProductProcess> product_processes = GetProductProcesses();


            // Create a dictionary using each product as a key and a list of all processes as value
            // i.e. prodprocdict['Woom 1'][List<Process>]

            var prodprocdict = products.Distinct().ToDictionary(x => x, x => processes);

            // Iterate through dictionary keys
            // i.e. 'Woom 1'
            foreach (var i in prodprocdict)
            {
                // Iterate through each value for this key
                // i.e. 'Pre-Assembly'
                foreach (var p in i.Value)
                {
                    // if the combination of key and value results in less than 1 record found in ProductProcess table
                    // i.e. 'Woom 1' 'Pre-Assembly'
                    if (product_processes.Where(x => x.Product == i.Key).Where(x => x.Process == p).ToList().Count() < 1)
                    {
                        // Add new combination to ProductProcess table
                        // Set Default values = 0

                        ProductProcess pp = new ProductProcess();

                        pp.Process          = p;
                        pp.Product          = i.Key;
                        pp.Quantity         = 0;
                        pp.StandardDuration = 0;

                        db.ProductProcesses.Add(pp);
                    }
                }
            }
            // Save changes to database
            db.SaveChanges();
        }
Exemplo n.º 4
0
        public ActionResult CreateProduction([Bind(Include = "ProductionID")] Production productionToAdd, Int32 EmployeeID, Int32 ProcessID, Int32 ProductID, Int32 BatchID, Decimal Duration, Int32 Quantity, String StartTime, String EndTime, String[] Issues)
        {
            if (ModelState.IsValid)
            {
                // Convert StartTime and EndTime strings into DateTime objects
                DateTime STime = DateTime.ParseExact(StartTime, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                DateTime ETime = DateTime.ParseExact(EndTime, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

                // Temp dates until Start and Stop time are working w/ js
                productionToAdd.StartTime = STime;
                productionToAdd.EndTime   = ETime;

                productionToAdd.Duration = Duration;
                productionToAdd.Quantity = Quantity;

                //Add Employee
                Employee employeeToAdd = db.Employees.Find(EmployeeID);
                productionToAdd.Employee = employeeToAdd;

                //Add Product
                Product productToAdd = db.Products.Find(ProductID);
                productionToAdd.Product = productToAdd;

                //Add Process
                Process processToAdd = db.Processes.Find(ProcessID);
                productionToAdd.Process = processToAdd;

                //Add Batch
                Batch batchToAdd = db.Batches.Find(BatchID);
                productionToAdd.Batch = batchToAdd;

                //Add Issues
                if (Issues != null && Issues.Count() > 0)
                {
                    // Insert a list of Issues as the production Issues where the ID is found within the Issues array
                    productionToAdd.Issues = db.Issues.Where(o => Issues.Contains(o.IssueID.ToString())).ToList();
                }
                db.Productions.Add(productionToAdd);
                db.SaveChanges();
            }
            return(null);
        }
Exemplo n.º 5
0
        public async Task <IActionResult> OnGet(int id, int?shipNo, int?row, int?col, int?vert)
        {
            Game = await _context.Games.FirstOrDefaultAsync(m => m.GameId == id);

            if (shipNo != null && row != null && col != null && vert != null)
            {
                var ship = Game.GameShips[shipNo.Value];
                ShipNo = shipNo.Value;
                if (vert.Value == 1)
                {
                    ship.ShipLayout = ShipLayout.Vertical;
                }

                if (ship.ShipLayout == ShipLayout.Vertical && row.Value + ship.ShipLength <= Game.Rows ||
                    ship.ShipLayout == ShipLayout.Horizontal && col.Value + ship.ShipLength <= Game.Cols)
                {
                    if (BLL.ShipPlacement.CanPlaceShip(Game, ship, row.Value, col.Value))
                    {
                        BLL.InitBoard.PlaceShip(Game, ship, row.Value, col.Value);
                        _context.Update(Game);
                        _context.SaveChanges();
                        ShipNo--;
                        if (ShipNo < 0)
                        {
                            if (Game.PlayerOneTurn)
                            {
                                Game.PlayerOneTurn = false;
                                if (Game.Ai)
                                {
                                    if (!BLL.ShipPlacement.RndPlacement(Game, true))
                                    {
                                        Message = "You have set too small board for those ship sizes!";
                                        return(Page());
                                    }

                                    Game.PlayerOneTurn = true;
                                    _context.Update(Game);
                                    _context.SaveChanges();
                                    return(RedirectToPage("PlayGame", new { id = Game.GameId }));
                                }

                                _context.Update(Game);
                                _context.SaveChanges();
                                return(RedirectToPage("CustomPlacement", new { id = Game.GameId }));
                            }

                            Game.PlayerOneTurn = true;
                            _context.Update(Game);
                            _context.SaveChanges();
                            return(RedirectToPage("PlayGame", new { id = Game.GameId }));
                        }
                    }
                    else
                    {
                        Message = "Other ship at coordinates";
                    }
                }
                else
                {
                    var layOut = vert == 1 ? "vertically" : "horizontally";
                    Message = $"Ship cannot be placed on coordinates ({row}, {col}) {layOut}";
                }
            }
            else
            {
                ShipNo = Game.NumberOfShips - 1;
            }

            if (ShipNo >= 0)
            {
                CurrentShip = Game.GameShips[ShipNo].ShipLength;
            }

            if (Game.PlayerOneTurn)
            {
                Player = Game.PlayerOne;
                Board  = Game.PlayerOneBoard;
            }
            else
            {
                Player = Game.PlayerTwo;
                Board  = Game.PlayerTwoBoard;
            }

            return(Page());
        }
Exemplo n.º 6
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync(string?languagePick,
                                                      string?publisherPick, string?deleteLanguage, string?deletePublisher,
                                                      string?deleteAuthor, string?authorPick, List <int>?hiddenAuthorsList,
                                                      string?final, string?picturePick, string?deletePicture)
        {
            if (!string.IsNullOrEmpty(languagePick) && "pick".Equals(languagePick))
            {
                LanguageIsSet   = true;
                Book.LanguageId = PickLanguageModel.LanguageId;
                Book.Language   = _context.Languages.Find(Book.LanguageId);
            }
            else if (!string.IsNullOrEmpty(languagePick) && "add".Equals(languagePick) &&
                     !string.IsNullOrEmpty(PickLanguageModel.NewLanguageName))
            {
                LanguageIsSet = true;
                var language = new Language(PickLanguageModel.NewLanguageName, "EE");
                if (!_context.Languages.Any(l => l.LanguageName == language.LanguageName))
                {
                    _context.Languages.Add(language);
                    _context.SaveChanges();
                    Book.LanguageId = language.LanguageId;
                }
                else
                {
                    Book.LanguageId = _context.Languages
                                      .First(l => l.LanguageName == language.LanguageName).LanguageId;
                }

                Book.Language = _context.Languages.Find(Book.LanguageId);
            }

            if (!string.IsNullOrEmpty(deleteLanguage))
            {
                Book.LanguageId = 0;
                LanguageIsSet   = false;
            }

            if (!string.IsNullOrEmpty(publisherPick) && "pick".Equals(publisherPick) &&
                PickPublisherModel.PublisherId != null)
            {
                PublisherIsSet   = true;
                Book.PublisherId = (int)PickPublisherModel.PublisherId;
                Book.Publisher   = _context.Publishers.Find(Book.PublisherId);
            }
            else if (!string.IsNullOrEmpty(publisherPick) && "add".Equals(publisherPick) &&
                     !string.IsNullOrEmpty(PickPublisherModel.NewPublisherName))
            {
                PublisherIsSet = true;
                var publisher = new Publisher(PickPublisherModel.NewPublisherName);
                if (!_context.Publishers.Any(a => a.PublisherName == publisher.PublisherName))
                {
                    _context.Publishers.Add(publisher);
                    _context.SaveChanges();
                    Book.PublisherId = publisher.PublisherId;
                }
                else
                {
                    Book.PublisherId = _context.Publishers
                                       .First(p => p.PublisherName == publisher.PublisherName).PublisherId;
                }

                Book.Publisher = _context.Publishers.Find(Book.PublisherId);
            }

            if (!string.IsNullOrEmpty(deletePublisher))
            {
                Book.PublisherId = 0;
                PublisherIsSet   = false;
            }

            if (LanguageIsSet)
            {
                Book.Language = _context.Languages.Find(Book.LanguageId);
            }
            else
            {
                PickLanguageModel.LanguagesSelectlist = new SelectList(_context.Languages,
                                                                       nameof(Language.LanguageId), nameof(Language.LanguageName));
            }

            if (PublisherIsSet)
            {
                Book.Publisher = _context.Publishers.Find(Book.PublisherId);
            }
            else
            {
                PickPublisherModel.PublishersSelectlist = new SelectList(_context.Publishers,
                                                                         nameof(Publisher.PublisherId), nameof(Publisher.PublisherName));
            }

            AuthorIds = hiddenAuthorsList;
            if (!string.IsNullOrEmpty(authorPick) && "pick".Equals(authorPick))
            {
                Console.WriteLine("Got to Pick!" + SelectedAuthorIds.Count +
                                  PickAuthorPartialModel.SelectedAuthorIds.Count);
                foreach (var selectedAuthorId in PickAuthorPartialModel.SelectedAuthorIds)
                {
                    if (!AuthorIds.Contains(selectedAuthorId))
                    {
                        AuthorIds.Add(selectedAuthorId);
                    }
                }
            }

            var author = PickAuthorPartialModel.Author;

            if (!string.IsNullOrEmpty(authorPick) && "add".Equals(authorPick) &&
                !string.IsNullOrEmpty(author.FirstName) && !string.IsNullOrEmpty(author.LastName))
            {
                Console.WriteLine(author);
                if (!_context.Authors.Any(a => a.FirstName == author.FirstName &&
                                          a.LastName == author.LastName &&
                                          a.BirthYear == author.BirthYear &&
                                          a.DeathYear == author.DeathYear &&
                                          a.Description == author.Description))
                {
                    Console.WriteLine("Got to add author!");
                    _context.Authors.Add(author);
                    _context.SaveChanges();
                    AuthorIds.Add(author.AuthorId);
                }
                else
                {
                    AuthorIds.Add(_context.Authors.FirstOrDefault(a => a.FirstName == author.FirstName &&
                                                                  a.LastName == author.LastName &&
                                                                  a.BirthYear == author.BirthYear &&
                                                                  a.DeathYear == author.DeathYear &&
                                                                  a.Description == author.Description).AuthorId);
                }
            }


            if (!string.IsNullOrEmpty(deleteAuthor) && int.TryParse(deleteAuthor, out var authorId))
            {
                Console.WriteLine("AuhorInt: " + authorId);
                AuthorIds.Remove(authorId);
            }

            BookAuthorsSelectList = new SelectList(_context.Authors, nameof(Author.AuthorId), nameof(Author.FirstName));
            PickAuthorPartialModel.BookAuthorsSelectList =
                new SelectList(_context.Authors, nameof(Author.AuthorId), nameof(Author.FirstName));

            Authors = _context.Authors.Where(a => AuthorIds.Contains(a.AuthorId))
                      .Select(a => new AuthorDto()
            {
                Author        = a,
                BooksAuthored = a.AuthoredBooks.Count
            }).ToList();
            Console.WriteLine("Before picturepick!");
            if (!string.IsNullOrEmpty(picturePick) && "add".Equals(picturePick) &&
                FormFile != null)
            {
                Console.WriteLine("Inside picturePick! " + FormFile.FileName);
                var file = Path.Combine(_env.WebRootPath, "resources", FormFile.FileName);
                using (var fileStream = new FileStream(file, FileMode.Create))
                {
                    await FormFile.CopyToAsync(fileStream);
                }

                UploadImagePath  = FormFile.FileName;
                Book.PicturePath = UploadImagePath;
            }

            if (!string.IsNullOrEmpty(deletePicture) && "remove".Equals(deletePicture))
            {
                UploadImagePath  = null;
                Book.PicturePath = null;
            }

            Book.PicturePath = UploadImagePath;

            if (!string.IsNullOrEmpty(final) && "Create".Equals(final) &&
                !string.IsNullOrEmpty(Book.Title) &&
                Book.Language != null &&
                Book.Publisher != null &&
                AuthorIds.Count > 0 &&
                !string.IsNullOrEmpty(Book.PicturePath))
            {
                _context.Books.Add(Book);
                _context.SaveChanges();
                Book.BookAuthors = new List <BookAuthor>();
                foreach (var id in AuthorIds)
                {
                    _context.BookAuthors.Add(new BookAuthor()
                    {
                        BookId   = Book.BookId,
                        AuthorId = id,
                        Author   = _context.Authors.Find(id)
                    });
                    _context.SaveChanges();
                }


                return(Redirect("./Index"));
            }

            return(Page());
        }
Exemplo n.º 7
0
        public async Task <IActionResult> OnGet(int id, int?row, int?col)
        {
            Game = await _context.Games.FirstOrDefaultAsync(m => m.GameId == id);

            Me         = Game.PlayerTwo;
            Enemy      = Game.PlayerOne;
            EnemyBoard = Game.PlayerOneBoard;
            MyBoard    = Game.PlayerTwoBoard;
            if (Game.PlayerOneTurn)
            {
                Me         = Game.PlayerOne;
                Enemy      = Game.PlayerTwo;
                EnemyBoard = Game.PlayerTwoBoard;
                MyBoard    = Game.PlayerOneBoard;
            }
            if (row != null && col != null)
            {
                switch (EnemyBoard[row.Value][col.Value])
                {
                case CellState.Hit:
                    Message = "You have already bombed this coordinate!";
                    break;

                case CellState.Empty:
                    EnemyBoard[row.Value][col.Value] = CellState.Miss;
                    if (Game.Ai)
                    {
                        BLL.Ai.MakeMove(Game);
                    }
                    else
                    {
                        Game.PlayerOneTurn = !Game.PlayerOneTurn;
                    }
                    break;

                case CellState.Miss:
                    Message = "You have already bombed this coordinate!";
                    break;

                case CellState.Ship:
                    EnemyBoard[row.Value][col.Value] = CellState.Hit;
                    BLL.GameState.IsShipWrecked(Game, row.Value, col.Value);
                    if (Game.Ai)
                    {
                        BLL.Ai.MakeMove(Game);
                    }
                    else
                    {
                        Game.PlayerOneTurn = !Game.PlayerOneTurn;
                    }
                    var msg = BLL.GameState.HasPlayerWon(Game);
                    if (msg != "No")
                    {
                        Message       = $"{msg} has won the game!";
                        Game.GameOver = true;
                    }
                    break;

                case CellState.Wreck:
                    Message = "You have already bombed this coordinate!";
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                Me         = Game.PlayerTwo;
                Enemy      = Game.PlayerOne;
                EnemyBoard = Game.PlayerOneBoard;
                MyBoard    = Game.PlayerTwoBoard;
                if (Game.PlayerOneTurn)
                {
                    Me         = Game.PlayerOne;
                    Enemy      = Game.PlayerTwo;
                    EnemyBoard = Game.PlayerTwoBoard;
                    MyBoard    = Game.PlayerOneBoard;
                }
                _context.Update(Game);
                _context.SaveChanges();
            }

            if (Game == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemplo n.º 8
0
 public static void DeleteSave(int saveid, DAL.AppDbContext ctx)
 {
     ctx.States.Remove(ctx.Saves.Where(s => s.SaveId == saveid).First().LastState);
     ctx.Saves.RemoveRange(ctx.Saves.Where(s => s.SaveId == saveid));
     ctx.SaveChanges();
 }
Exemplo n.º 9
0
        public ActionResult Log(LogDataViewModel Model)
        {
            // Create an instance of the data utility
            var d = new Data();


            if (Model.StartTime == null || Model.StartTime == "" || Model.StartTime.Count() != 10 || Model.StartTime.Length != 10)
            {
                TempData["Error"]  = "Please enter a valid Date.";
                Model.EmployeeList = d.GetActiveEmployees();
                Model.ProductList  = d.GetActiveProducts();
                Model.ProcessList  = d.GetActiveProcesses();
                Model.BatchList    = d.GetActiveBatches();
                Model.IssueList    = d.GetActiveIssues();

                Model.SelectedIssues = Model.SelectedIssues;



                return(View(Model));
            }


            if (!ModelState.IsValid)
            {
                // Production log entry was invalid
                // Kick them back to the view and try again
                // But we have to rebuild the view model first
                Model.EmployeeList = d.GetActiveEmployees();
                Model.ProductList  = d.GetActiveProducts();
                Model.ProcessList  = d.GetActiveProcesses();
                Model.BatchList    = d.GetActiveBatches();
                Model.IssueList    = d.GetActiveIssues();

                Model.SelectedIssues = Model.SelectedIssues;



                return(View(Model));
            }

            // If we find that production indeed exists
            if (Model != null)
            {
                // Initialize a new Production object
                var production = new Production();

                // Grab each property based on the selected value and add it to the new Production object
                production.Employee = db.Employees.Find(Model.EmployeeID);
                production.Product  = db.Products.Find(Model.ProductID);
                production.Process  = db.Processes.Find(Model.ProcessID);
                production.Batch    = db.Batches.Find(Model.BatchID);

                production.Quantity = Model.Quantity;

                // Duration from manual logging is in HOURS
                // Measures are calcualted as MINUTES
                production.Duration = Model.Duration * 60;

                // Convert user-entered times to DateTimes for model and DB
                production.StartTime = Convert.ToDateTime(Model.StartTime);
                // DateRecorded is only not null if an Admin enters the production manually
                production.DateRecorded = Model.DateRecorded;
                production.EndTime      = Convert.ToDateTime(Model.StartTime);

                // If any issue is selected
                if (Model.SelectedIssues != null && Model.SelectedIssues.Count() > 0)
                {
                    // Insert a list of Issues as the production Issues where the ID is found within the Issues array
                    production.Issues = db.Issues.Where(x => Model.SelectedIssues.Contains(x.IssueID.ToString())).ToList();
                }

                System.Diagnostics.Debug.WriteLine("**********************************");
                System.Diagnostics.Debug.WriteLine(Model.StartTime + " " + Model.StartTime.Length + " " + Model.StartTime.Count());
                System.Diagnostics.Debug.WriteLine("**********************************");

                db.Productions.Add(production);
                db.SaveChanges();
                var ReturnModel = new LogDataViewModel();
                // Inform the user that their data was successfully entered
                TempData["Success"] = "Production Logged";

                // Rebuild the view model and send them back to the update view
                ReturnModel.EmployeeList = d.GetActiveEmployees();
                ReturnModel.ProductList  = d.GetActiveProducts();
                ReturnModel.ProcessList  = d.GetActiveProcesses();
                ReturnModel.BatchList    = d.GetActiveBatches();
                ReturnModel.IssueList    = d.GetActiveIssues();

                return(View(ReturnModel));
            }

            // Fillout the lists if we need to return to the update view
            Model.EmployeeList = d.GetActiveEmployees();
            Model.ProductList  = d.GetActiveProducts();
            Model.ProcessList  = d.GetActiveProcesses();
            Model.BatchList    = d.GetActiveBatches();
            Model.IssueList    = d.GetActiveIssues();

            Model.SelectedIssues = Model.SelectedIssues;
            // Inform the user that the data was not entered successfully
            TempData["Error"] = "Production not updated";
            return(View(Model));
        }