Ejemplo n.º 1
0
        public ActionResult Create(EventCompetitorViewModel eventCompetitorViewModel)
        {
            if (ModelState.IsValid)
            {
                // Get existing competitor and event from database
                Competitor competitor = db.Competitors
                                        .Find(eventCompetitorViewModel.EventCompetitor.competitorID);
                Event @event = db.Events
                               .Find(eventCompetitorViewModel.EventCompetitor.eventID);
                // Assign the secondary propertues
                var competitorPosition = eventCompetitorViewModel.EventCompetitor.competitorPosition;
                var competitorMedal    = eventCompetitorViewModel.EventCompetitor.competitorMedal;

                if (competitor != null & @event != null)
                {
                    // Create a new object
                    EventCompetitor eventCompetitor = new EventCompetitor()
                    {
                        Event              = @event,
                        Competitor         = competitor,
                        competitorMedal    = competitorMedal,
                        competitorPosition = competitorPosition
                    };

                    // Add to the DbContext and save the changes
                    db.EventCompetitors.Add(eventCompetitor);
                    db.SaveChanges();
                    return(RedirectToAction("Index", "Events", new { id = eventCompetitor.eventID }));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid event or competitor!");
                }
            }

            // Repopulate in case of validation error
            Event eventObject = db.Events
                                .Include(e => e.Game)
                                .FirstOrDefault(e => e.eventID == eventCompetitorViewModel.EventCompetitor.eventID);
            SelectList allCompetitors = new SelectList(eventObject.Game.Competitors,
                                                       "competitorID", "competitorName");

            eventCompetitorViewModel.AllCompetitors = allCompetitors;
            ViewBag.Medals = GetMedals();

            return(View(eventCompetitorViewModel));
        }
Ejemplo n.º 2
0
        public async Task SyncNewsAsync()
        {
            var newsResponse = await _sportsRuApiService.GetNewsAsync(NewsType.HomePage, NewsPriority.Main, NewsContentOrigin.Mixed, 100).ConfigureAwait(false);

            var hotContent = await _sportsRuApiService.GetHotContentAsync().ConfigureAwait(false);

            IEnumerable <int> hotNewsIds = null;

            if (hotContent.IsSuccess)
            {
                hotNewsIds = hotContent.Content.News;
            }
            if (newsResponse.IsSuccess)
            {
                foreach (var newsArticle in newsResponse.Content)
                {
                    if (newsArticle.BodyIsEmpty ||
                        newsArticle.ContentOption?.Name == "special" ||
                        !SportsRuHelper.IsInternalUrl(newsArticle.DesktopUrl)) //usually this is not a news article but some promotion
                    {
                        continue;
                    }
                    string idString        = newsArticle.Id.ToString(CultureInfo.InvariantCulture);
                    var    existingArticle = _sportsContext.NewsArticles.FirstOrDefault(x => x.ExternalId == idString);
                    if (existingArticle == null)
                    {
                        var newArticle = new NewsArticle()
                        {
                            ExternalId = idString
                        };
                        Map(newsArticle, newArticle, hotNewsIds);
                        _sportsContext.NewsArticles.Add(newArticle);
                    }
                    else
                    {
                        Map(newsArticle, existingArticle, hotNewsIds);
                        _sportsContext.NewsArticles.Update(existingArticle);
                    }
                }
                _sportsContext.SaveChanges();
            }
        }
        public ActionResult Create([Bind(Include = "ID,Date,Place")] LocationDetail locationDetail)
        {
            if (ModelState.IsValid)
            {
                db.LocationDetails.Add(locationDetail);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(locationDetail));
        }
Ejemplo n.º 4
0
        public IActionResult CreateTest(TestsList testsList)
        {
            if (ModelState.IsValid)
            {
                Tests test = new Tests
                {
                    Date       = testsList.Date,
                    TestTypeID = testsList.TestType.TestTypeId
                };

                db.Add(test);
                db.SaveChanges();
                if (test.TestId > 0)
                {
                    return(RedirectToAction("Details", new { id = test.TestId }));
                }
            }
            ViewBag.ListOfTests = db.TestTypes.ToList();
            ModelState.AddModelError("", "some thing went wrong");
            return(View());
        }
Ejemplo n.º 5
0
        public ActionResult Create([Bind(Include = "ID,Name,Gender,TID")] Athlete athlete)
        {
            if (ModelState.IsValid)
            {
                db.Athletes.Add(athlete);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.TID = new SelectList(db.Teams, "ID", "Name", athlete.TID);
            return(View(athlete));
        }
Ejemplo n.º 6
0
        // Validate the submission and add the Wedding to the DB
        public IActionResult CreatePlayDate(Sport wed)
        {
            // Check whether User is logged in, and if so get session variables (User Id/Name)
            int?userId = HttpContext.Session.GetInt32("CurrentUserId");

            if (userId == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (ModelState.IsValid)
            {
                // Set current User as Wedding creator and add to DB
                wed.UserId = (int)userId;
                _Context.Add(wed);
                _Context.SaveChanges();
                System.Console.WriteLine("Congratulations !!");
                return(RedirectToAction("Dashboard"));
            }
            // Show Add page with errors
            return(View("Add"));
        }
Ejemplo n.º 7
0
        public ActionResult Create([Bind(Include = "ID,RaceTime,AID,EID,LID")] Result result)
        {
            if (ModelState.IsValid)
            {
                db.Results.Add(result);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.AID = new SelectList(db.Athletes, "ID", "Name", result.AID);
            ViewBag.EID = new SelectList(db.Events, "ID", "Type", result.EID);
            ViewBag.LID = new SelectList(db.LocationDetails, "ID", "Place", result.LID);
            return(View(result));
        }
Ejemplo n.º 8
0
        public void TestCreation()
        {
            var builder = new DbContextOptionsBuilder();

            builder
            .UseLazyLoadingProxies()
            .UseSqlite("Data Source=sports.db");
            using var db = new SportsContext(builder.Options);
            db.Database.EnsureDeleted();
            db.Database.EnsureCreated();
            var article = new NewsArticle()
            {
                Title = "test"
            };

            db.NewsArticles.Add(article);
            db.SaveChanges();
            Assert.NotEqual(Guid.Empty, article.NewsArticleId);
        }
Ejemplo n.º 9
0
        public IActionResult Register(RegisterViewModel model)
        {
            System.Console.WriteLine("In Register Route");
            if (ModelState.IsValid)
            {
                // Checks to see whether a User is already registered with this email.
                var existingPerson = _Context.Users.Where(you => you.EmailAddress == model.emailAddress).SingleOrDefault();
                if (existingPerson == null)
                {
                    // Create User object with hashed password.
                    User newUser = new User
                    {
                        FirstName    = model.firstName,
                        LastName     = model.lastName,
                        EmailAddress = model.emailAddress,
                        Password     = model.password
                    };

                    // Add new User to DB.
                    _Context.Users.Add(newUser);
                    _Context.SaveChanges();
                    System.Console.WriteLine("User Saved !!");

                    // Set session variables.
                    HttpContext.Session.SetInt32("CurrentUserId", newUser.UserId);
                    HttpContext.Session.SetString("FirstName", newUser.FirstName);
                    HttpContext.Session.SetString("LastName", newUser.LastName);
                    return(RedirectToAction("Dashboard", "Event"));
                }
                else
                {
                    System.Console.WriteLine("Not Good ..");
                    ViewBag.errors = "A User with that Email already exists.";
                    return(View("Index"));
                }
            }

            // Return View to show ASP-Validation errors.
            return(View("Index"));
        }
Ejemplo n.º 10
0
        public void DeleteAfterDate()
        {
            var newsArticle = new NewsArticle()
            {
                Title = "test", PublishedDate = DateTime.Now.AddDays(-1)
            };

            _sportsContext.NewsArticles.Add(newsArticle);

            Assert.NotEqual(Guid.Empty, newsArticle.NewsArticleId);
            _sportsContext.NewsArticlesComments.Add(new NewsArticleComment()
            {
                NewsArticleId = newsArticle.NewsArticleId,
                Text          = string.Empty
            });

            _sportsContext.SaveChanges();

            Assert.True(_sportsContext.NewsArticlesComments.Any());
            Assert.True(_sportsContext.NewsArticles.Any());
            _syncService.DeleteOldData(DateTimeOffset.Now);
            Assert.False(_sportsContext.NewsArticlesComments.Any());
            Assert.False(_sportsContext.NewsArticles.Any());
        }
 public Player AddPalyer(Player player)
 {
     _sportsContext.Player.Add(player);
     _sportsContext.SaveChanges();
     return(player);
 }
Ejemplo n.º 12
0
 public IActionResult Create(Team team)
 {
     db.Teams.Add(team);
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 13
0
 public IActionResult Create(Division division)
 {
     db.Divisions.Add(division);
     db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 14
0
        public ActionResult Create(
            [Bind(Include = "gameID,gameName,gameCode,gameDurationInMins,gameDescription,gameBookletPath")] Game game,
            HttpPostedFileBase gameBookletPath
            )
        {
            if (gameBookletPath != null)
            {
                // An array of allowed extensions
                // File upload source: http://rachelappel.com/upload-and-download-files-using-asp-net-mvc/
                var acceptedExtentions = new[] { ".pdf", ".doc", ".docx" };
                var fileExtension      = Path.GetExtension(gameBookletPath.FileName).ToLower();
                if (!acceptedExtentions.Contains(fileExtension))
                {
                    ModelState.AddModelError(string.Empty, "File is not a valid type!");
                }
                // Check if the file has any content. A 0 byte file will return invalid to the view
                if (!(gameBookletPath.ContentLength > 0))
                {
                    ModelState.AddModelError("", "Error uploading file, file is empty or corrupt!");
                }
            }
            else
            {
                ModelState.AddModelError("", "You must include a rules booklet!");
            }

            if (ModelState.IsValid)
            {
                if (gameBookletPath != null)
                {
                    var    fileExtension   = Path.GetExtension(gameBookletPath.FileName).ToLower();
                    string fileNamePattern = @"\s|[().,]";
                    var    fileName        = Regex.Replace(game.gameCode,
                                                           fileNamePattern, string.Empty)
                                             + fileExtension;

                    try
                    {
                        gameBookletPath.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Upload/Rules"), fileName));
                        game.gameBookletPath = "/Upload/Rules/" + fileName;
                    }
                    catch
                    {
                        // Show an error if file couldn't be saved for whatever reason
                        // In a more traditional application the exception would be logged, however I am not doing that here
                        ModelState.AddModelError("", "File could not be saved, please contact the administrator!");
                    }
                }

                game.gameCode = game.gameCode.ToUpper();

                // Verify the ModelState remains valid (try-catch block above could change it)
                if (ModelState.IsValid)
                {
                    db.Games.Add(game);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(game));
        }
Ejemplo n.º 15
0
 public static void DeleteAllNews(SportsContext sportsContext)
 {
     sportsContext.NewsArticles.RemoveRange(sportsContext.NewsArticles);
     sportsContext.SaveChanges();
 }
        public ActionResult Create(CompetitorViewModel competitorViewModel, HttpPostedFileBase competitorPhoto)
        {
            if (competitorPhoto != null)
            {
                // An array of allowed extensions
                var acceptedExtentions = new[] { ".png", ".jpg", ".jpeg", ".gif" };
                // Get extention of the file
                var fileExtension = Path.GetExtension(competitorPhoto.FileName).ToLower();
                if (!acceptedExtentions.Contains(fileExtension))
                {
                    ModelState.AddModelError(string.Empty, "File is not a valid type!");
                }
                // Check if the file has any content. A 0 byte file will return invalid to the view
                if (competitorPhoto.ContentLength < 1)
                {
                    ModelState.AddModelError("", "Error uploading file, file is empty or corrupt!");
                }
            }

            if (ModelState.IsValid)
            {
                // Populate competitor object with form data
                Competitor competitor = competitorViewModel.Competitor;
                // Convert email to lowercase
                competitor.competitorEmail = competitor.competitorEmail.ToLower();

                if (competitorViewModel.SelectedGames != null)
                {
                    foreach (var gameID in competitorViewModel.SelectedGames)
                    {
                        // Find the game by ID
                        Game game = db.Games.Find(gameID);
                        competitor.Games.Add(game);
                    }
                }

                if (competitorPhoto != null)
                {
                    var    fileExtension   = Path.GetExtension(competitorPhoto.FileName).ToLower();
                    string fileNamePattern = @"\s|[().,]";
                    var    fileName        = Regex.Replace(competitor.competitorName,
                                                           fileNamePattern, string.Empty)
                                             + fileExtension;
                    try
                    {
                        competitorPhoto.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Upload/Photos"), fileName));
                        competitor.competitorPhotoPath = "/Upload/Photos/" + fileName;
                    } catch
                    {
                        // Show an error if file couldn't be saved for whatever reason
                        // In a more traditional application the exception would be logged, however I am not doing that here
                        ModelState.AddModelError("", "File could not be saved, please contact the administrator!");
                    }
                }

                // Verify the ModelState remains valid (try-catch block above could change it)
                if (ModelState.IsValid)
                {
                    // Save changes to the DB
                    db.Competitors.Add(competitor);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            // Repopulate the ViewBag/AllGames variables if the form is not valid and has to be re-displayed
            MultiSelectList gamesList = new MultiSelectList(db.Games, "gameID", "gameName");

            competitorViewModel.AllGames = gamesList;
            ViewBag.countryList          = GetCountries();
            ViewBag.titlesList           = GetTitles();
            ViewBag.genderList           = GetGenders();

            return(View(competitorViewModel));
        }
Ejemplo n.º 17
0
        public ActionResult Create(EventViewModel eventViewModel, IEnumerable <HttpPostedFileBase> eventPhotos)
        {
            if (eventPhotos.Count() > 0)
            {
                // An array of allowed extensions
                var acceptedExtentions = new[] { ".png", ".jpg", ".jpeg", ".gif" };
                foreach (var file in eventPhotos)
                {
                    if (file != null)
                    {
                        // Get extention of the file
                        var fileExtension = Path.GetExtension(file.FileName).ToLower();
                        if (!acceptedExtentions.Contains(fileExtension))
                        {
                            ModelState.AddModelError(string.Empty, $"File ({file.FileName}) is not a valid type!");
                        }
                        else if (file.ContentLength < 1)
                        {
                            ModelState.AddModelError("", $"Error uploading file ({file.FileName}), file is empty or corrupt!");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "You added an additional photo but did not select a file!");
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "The event requires at least one photo!");
            }

            if (ModelState.IsValid)
            {
                Event @event = eventViewModel.Event;

                int tempNum = 0;
                foreach (var photo in eventPhotos)
                {
                    var fileExtension = Path.GetExtension(photo.FileName).ToLower();
                    var fileName      = Guid.NewGuid().ToString() + fileExtension;
                    try
                    {
                        // Save the photo
                        photo.SaveAs(Path.Combine(HttpContext.Server.MapPath("~/Upload/Photos"), fileName));
                    }
                    catch
                    {
                        // Show an error if file couldn't be saved for whatever reason
                        // In a more traditional application the exception would be logged, however I am not doing that here
                        ModelState.AddModelError("", "File could not be saved, please contact the administrator!");
                    }

                    fileName = "/Upload/Photos/" + fileName;
                    Photo eventPhoto = new Photo()
                    {
                        photoPath = fileName
                    };
                    var splitPattern = "[.,;]\\s*";
                    var tags         = Regex.Split(eventViewModel.PhotoTags[tempNum], splitPattern);
                    tags = tags.Distinct().ToArray();
                    foreach (string tag in tags)
                    {
                        // Check if the tag already exists, otherwsie create a new tag
                        var existingTag = db.Tags.FirstOrDefault(t => t.tagString.ToLower() == tag);
                        if (existingTag == null)
                        {
                            Tag newTag = new Tag()
                            {
                                tagString = tag
                            };
                            // Add to the photo
                            eventPhoto.Tags.Add(newTag);
                        }
                        else
                        {
                            // Add to the photo
                            eventPhoto.Tags.Add(existingTag);
                        }
                    }
                    tempNum++;
                    // Add the photo to the event
                    @event.Photos.Add(eventPhoto);

                    /* Note: There is a "bug" here. If the same tag is used more than once, but on a different
                     * photo it will create a dusplicate of that tag. Time constraints meant that I didn't have time
                     * to fix this */
                }

                db.Events.Add(@event);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            /* If the model is not valid then we return to the page where the appropriate validation errors are display,
             * if this happens we have to repopulate the Games list in the ViewModel */
            eventViewModel.Games = new SelectList(db.Games, "gameID", "gameName");

            return(View(eventViewModel));
        }
Ejemplo n.º 18
0
 public IActionResult Save(Player player)
 {
     _sportsContext.Player.Add(player);
     _sportsContext.SaveChanges();
     return(Ok());
 }