public IActionResult Create() { var viewModel = new CreateCompetitionInputModel(); viewModel.CountryItems = this.countriesService.GetAllAsKeyValuePairs(); return(this.View(viewModel)); }
public async Task <IActionResult> Create(CreateCompetitionInputModel input) { if (!this.ModelState.IsValid) { input.CountryItems = this.countriesService.GetAllAsKeyValuePairs(); return(this.View(input)); } var user = await this.userManager.GetUserAsync(this.User); try { await this.competitionService.CreateAsync(input, user.Id, $"{this.environment.WebRootPath}/images"); } catch (Exception) { var viewModel = new CreateCompetitionInputModel(); viewModel.CountryItems = this.countriesService.GetAllAsKeyValuePairs(); return(this.View(viewModel)); } return(this.Redirect("/")); }
public async Task CreateAsync(CreateCompetitionInputModel input, string userId, string imagePath) { var competition = new Competition { Name = input.Name, Description = input.Description, DateTime = input.DateTime, CountryId = input.CountryId, AddedByUserId = userId, }; foreach (var inputCategory in input.Categories) { var category = this.categoriesRespository.All() .FirstOrDefault(x => x.Name == inputCategory.CategoryName); if (category == null) { category = new Category { Name = inputCategory.CategoryName }; } competition.Categories.Add(new CompetitionCategory { Category = category, Competition = competition, }); } Directory.CreateDirectory($"{imagePath}/competitions"); var dbImage = new Image(); if (input.ImageUrl == null) { if (input.Image == null) { throw new Exception($"No Image Uploaded"); } var extension = Path.GetExtension(input.Image.FileName); extension = extension.TrimStart('.'); if (!this.AllowedExtensions.Any(x => extension.EndsWith(x))) { throw new Exception($"Invalid image extension {extension}"); } dbImage.AddedByUserId = userId; dbImage.Extension = extension; var physicalPath = $"{imagePath}/competitions/{dbImage.Id}.{extension}"; using (Stream fileStream = new FileStream(physicalPath, FileMode.Create)) { await input.Image.CopyToAsync(fileStream); } } else { dbImage.AddedByUserId = userId; dbImage.RemoteImageUrl = input.ImageUrl; } competition.Image = dbImage; await this.competitionsRepository.AddAsync(competition); await this.competitionsRepository.SaveChangesAsync(); }