public void CreateNewPhoto() { // arrange var mockUserRep = new Mock <IUserRepository>(); var mockPhotoRep = new Mock <IPhotoRepository>(); var mockLogger = new Mock <INRAKOLogger>(); var mockS3Amazon = new Mock <AmazonS3Tools>(); var mockMutation = new Mock <IMutationActionFactorySelector>(); CreatePhotoViewModel photoVM = new CreatePhotoViewModel() { Description = "Test", DoConversion = false, DoResize = false, HashtagsString = "Test", OriginalImageExtension = "png" }; mockUserRep.Setup(x => x.GetUser(null)).Returns((NRAKOUser)null); mockLogger.Setup(x => x.Log(null, null)); mockPhotoRep.Setup(x => x.SavePhoto(photoVM, null)).Returns(new Photo { Size = 0, Width = 0, Height = 0 }); var controller = new PhotosController(mockUserRep.Object, mockPhotoRep.Object, mockLogger.Object, mockS3Amazon.Object, mockMutation.Object); // act var result = controller.CreateNewPhoto(photoVM); // assert var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Index", redirectToActionResult.ActionName); Assert.Null(redirectToActionResult.ControllerName); }
public ActionResult Create(CreatePhotoViewModel model) { if (!ModelState.IsValid) { return(View(model)); } if (model.File == null) { ViewBag.Error = "Please choose a file"; return(View(model)); } if (!_userProfileService.CanUserAddPhoto(User.Identity.GetUserId())) { ModelState.AddModelError("Error", "You have reached your maximum number of free photos"); return(View(model)); } Photo photo = Mapper.Map <Photo>(model); photo.UserId = User.Identity.GetUserId(); _photoService.AddPhoto(photo, model.File.InputStream); return(RedirectToAction("Index")); }
public IActionResult CreateNewPhoto() { var userPhotos = _photoRepository.GetphotosByUserID(CurrentUser.Id); MaxNumberOfPhotosExceededSubscriptionValidationChecker checker = new MaxNumberOfPhotosExceededSubscriptionValidationChecker(); checker.SetNext(new DailyUploadLimitExceededSubscriptionValidationChecker()); SubscriptionModel sm = _userRepository.GetSubscriptionModel(CurrentUser.Id); SubscriptionModel uc = new SubscriptionModel() { DailyUploadLimit = userPhotos.Where(up => up.DateCreated.Date == DateTime.Today).Count(), MaxNumberOfPhotos = userPhotos.Count() }; string violation = checker.CheckViolation(sm, uc); if (violation != null) { ViewBag.Violation = violation; return(View("Violation")); } CreatePhotoViewModel cpvm = new CreatePhotoViewModel(); cpvm.AvailableFormats = Helpers.Helpers.GetAvailableFormats(); return(View(cpvm)); }
public IActionResult Create(string contestName) { var createPhotoVM = new CreatePhotoViewModel() { ContestName = contestName }; return(View(createPhotoVM)); }
internal static Photo GetPhotoFromCreatePhotoViewModel(CreatePhotoViewModel model, string userId) { Photo photo = new Photo(); DateTime now = DateTime.Now; photo.DateCreated = now; photo.DateModified = now; photo.Description = model.Description; photo.NRAKOUserId = userId; return(photo); }
public Photo SavePhoto(CreatePhotoViewModel model, string userId) { string[] hashtags = model.HashtagsString.Split(' '); Photo photo = Helpers.Helpers.GetPhotoFromCreatePhotoViewModel(model, userId); var extension = model.OriginalImageExtension; if (model.DoConversion) { extension = model.ConversionExtension; } if (!Helpers.Helpers.GetAvailableFormats().Any(f => f == extension)) { extension = "Jpeg"; } //var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); string uniqueFileName = Helpers.Helpers.GetUniqueFileName(extension); //var filePath = Path.Combine(uploads, uniqueFileName); long imageSize = 0; MemoryStream ms = new MemoryStream(); using (Image <Rgba32> image = Image.Load <Rgba32>(model.PhotoFile.OpenReadStream())) { if (model.DoResize) { image.Mutate(x => x .Resize(model.ResizeWidth, model.ResizeHeight) ); } image.Save(ms, Helpers.Helpers.ResolveImageEncoder(extension)); photo.Width = image.Width; photo.Height = image.Height; } photo.Url = _storageStrategy.Store(ms, uniqueFileName, out imageSize); ms.Close(); photo.Size = imageSize; _db.Photos.Add(photo); AddHashtagsToPhoto(hashtags, photo.Id); _db.SaveChanges(); return(photo); }
public IActionResult CreateNewPhoto(CreatePhotoViewModel model) { if (!ModelState.IsValid) { return(View()); } Photo photo = _photoRepository.SavePhoto(model, CurrentUser?.Id); _logger.Log(CurrentUser?.Id, $"Created a new photo @{photo.Url}"); return(RedirectToAction("Index")); }
public async Task <IActionResult> AddPhotoForUser(int userId, [FromForm] CreatePhotoViewModel photoViewModel) { if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) { return(Unauthorized()); } User user = await this.repository.GetUserAsync(userId); IFormFile file = photoViewModel.File; ImageUploadResult uploadResult = new ImageUploadResult(); // TODO: Add validation to check if the file is actually a photo if (file.Length > 0) { using (Stream stream = file.OpenReadStream()) { ImageUploadParams uploadParams = new ImageUploadParams() { File = new FileDescription(file.Name, stream), Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face") }; uploadResult = this.cloudinary.Upload(uploadParams); } } photoViewModel.Url = uploadResult.Url.AbsoluteUri; photoViewModel.PublicId = uploadResult.PublicId; Photo photo = this.mapper.Map <Photo>(photoViewModel); if (!user.Photos.Any()) { photo.IsMain = true; } user.Photos.Add(photo); if (await this.repository.SaveAllAsync()) { ReturnPhotoViewModel returnPhotoView = this.mapper.Map <ReturnPhotoViewModel>(photo); return(CreatedAtRoute("GetPhoto", new { userId = userId, id = photo.Id }, returnPhotoView)); } return(BadRequest("Could not upload image")); }
public async Task <IActionResult> Create(CreatePhotoViewModel model) { if (ModelState.IsValid) { try { var newFileName = $"{Guid.NewGuid()}_{model.File.FileName}"; var fileDbPath = $"/Images/{newFileName}"; var saveFile = Path.Combine(webHostEnvironment.WebRootPath, "Images", newFileName); using (var fileSelected = new FileStream(saveFile, FileMode.Create)) { await model.File.CopyToAsync(fileSelected); } using (var img = Image.Load(model.File.OpenReadStream())) { img.Mutate(x => x.Resize(400, 400)); //img.Save(fileDbPath); } var newPhotoDTO = new NewPhotoDTO() { Title = model.Title, Description = model.Description, PhotoUrl = fileDbPath, ContestName = model.ContestName }; await this.photoService.CreateAsync(newPhotoDTO); return(RedirectToAction("GetUserContests", "Contests")); } catch (Exception e) { toastNotification.AddErrorToastMessage(e.Message, new NotyOptions()); var path = Request.Path.Value.ToString() + "?contestName=" + model.ContestName; return(Redirect(path)); } } return(View(model)); }