public async Task <IActionResult> CreateLot(CreateLotViewModel model) { if (ModelState.IsValid) { AuctionLot toAdd = new AuctionLot { Name = model.Name, User = new User { UserName = User.Identity.Name }, Description = model.Description, StartDate = model.StartDate.Value, EndDate = model.EndDate.Value, PriceInfo = new PriceInfo { StartPrice = model.StartPrice.Value, CurrentPrice = model.StartPrice.Value, BidStep = model.BidStep.Value } }; string dbPhotoPath = $"/images/{User.Identity.Name}/{model.Name}/photo{Path.GetExtension(model.Photo.FileName)}"; toAdd.PhotoSrc = dbPhotoPath; try { await lotLogic.Create(toAdd); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } string physicalDirectory = Path.GetDirectoryName($"{environment.WebRootPath + dbPhotoPath}"); if (!Directory.Exists(physicalDirectory)) { Directory.CreateDirectory(physicalDirectory); } using (FileStream fs = new FileStream($"{environment.WebRootPath + dbPhotoPath}", FileMode.Create)) { await model.Photo.CopyToAsync(fs); } return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotCreatedMessages(), RedirectUrl = "/Home/Lots", SecondsToRedirect = ApplicationConstantsProvider.GetMaxRedirectionTime() })); } return(View(model)); }
public async Task <IActionResult> EditLot(EditLotViewModel model) { if (ModelState.IsValid) { if (string.IsNullOrWhiteSpace(model.Id)) { return(NotFound()); } AuctionLot lotToEdit = new AuctionLot { Id = model.Id, Name = model.Name, Description = model.Description, StartDate = model.StartDate.Value, EndDate = model.EndDate.Value, Status = LotStatusProvider.GetOnModerationStatus(), PriceInfo = new PriceInfo { StartPrice = model.StartPrice.Value, BidStep = model.BidStep.Value } }; string newDbPath = $"/images/{User.Identity.Name}/{model.Name}/photo{Path.GetExtension(model.Photo.FileName)}"; lotToEdit.PhotoSrc = newDbPath; try { await lotLogic.Update(lotToEdit); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } string oldPath = $"{environment.WebRootPath + Path.GetDirectoryName(model.OldPhotoSrc)}"; if (Directory.Exists(oldPath)) { Directory.Delete(oldPath, true); } string newPhysicalDirectory = Path.GetDirectoryName($"{environment.WebRootPath + newDbPath}"); if (!Directory.Exists(newPhysicalDirectory)) { Directory.CreateDirectory(newPhysicalDirectory); } using (FileStream fs = new FileStream($"{environment.WebRootPath + newDbPath}", FileMode.Create)) { await model.Photo.CopyToAsync(fs); } return(View("Redirect", new RedirectModel { InfoMessages = RedirectionMessageProvider.LotUpdatedMessages(), RedirectUrl = "/Home/Lots", SecondsToRedirect = ApplicationConstantsProvider.GetMaxRedirectionTime() })); } return(View(model)); }