public async Task <ProcessResult <bool> > RemovePhoto(RemovePhotoViewModel viewModel) { ProcessResult <bool> result = new ProcessResult <bool>(); ProcessResult <bool> categoryStatus = await CategoryIsInRequiredStatus(viewModel.CategoryId, CategoryStatusCodes.SubmittingPhotos); if (!categoryStatus.Success) { result.AddError(categoryStatus.ErrorMessage); } if (result.Success) { Photograph photo = await _db.Photographs .FirstOrDefaultAsync(p => p.Category.CategoryId == viewModel.CategoryId && p.UserCategoryPhotoNumber == viewModel.PhotoNumber && p.Photographer.UserName == User.Identity.Name); if (photo != null) { result = _db.SaveRemoves(photo); } else { result.AddError("Unable to find a photo with these details"); } } return(result); }
public override async Task <ProcessResult <Guid> > Handle(CreateUserCommand request, CancellationToken cancellationToken) { var result = new ProcessResult <Guid>(); try { var user = _mapper.Map <UserEntity>(request); _ctx.Users.Add(user); var saveSucces = await _ctx.SaveChangesAsync() == 1; if (saveSucces) { result.Result = user.Id; } else { result.AddError(@"Save failed ¯\_(ツ)_/¯"); } return(result); } catch (Exception ex) { result.AddError(ex.Message); return(result); } }
public async Task <ProcessResult <PhotoScoreboardItemViewModel[]> > GetPhotoScoreboard(int id) { ProcessResult <PhotoScoreboardItemViewModel[]> result = new ProcessResult <PhotoScoreboardItemViewModel[]>(); try { List <Photograph> photographs = await _db.Photographs .Include(p => p.Votes) .Where(p => p.Category.CategoryId == id) .ToListAsync(); List <KeyValuePair <Photograph, int> > allScores = new List <KeyValuePair <Photograph, int> >(); foreach (Photograph photo in photographs) { allScores.Add(new KeyValuePair <Photograph, int>(photo, photo.Votes.Sum(v => 4 - v.Position))); } allScores = allScores .OrderByDescending(i => i.Value) .ThenBy(i => i.Key.AnonymousPhotoName) .ToList(); PhotoScoreboardItemViewModelMapper mapper = new PhotoScoreboardItemViewModelMapper(); int relativePosition = 0; int actualPosition = 0; int previousScore = 1000000; List <PhotoScoreboardItemViewModel> scoreboard = new List <PhotoScoreboardItemViewModel>(); foreach (KeyValuePair <Photograph, int> photoScore in allScores) { actualPosition++; if (photoScore.Value < previousScore) { relativePosition = actualPosition; } if (relativePosition <= 5) { scoreboard.Add(mapper.BuildModel(relativePosition, photoScore.Value, photoScore.Key)); } previousScore = photoScore.Value; } if (scoreboard.Count < 3) { result.AddError("Unable to find enough photos in the scoreboard"); } else { result.SetResult(scoreboard.ToArray()); } } catch (Exception e) { result.AddError(e.Message); } return(result); }
public async Task <ProcessResult <Guid> > Handle(CreateUserCommand request, CancellationToken cancellationToken) { var result = new ProcessResult <Guid>(); var user = _mapper.Map <UserDTO>(request); try { user.Id = Guid.NewGuid(); var messageId = Guid.NewGuid(); await _eventBus.Publish <IUserCreateMessage>(new UserCreateMessage { Id = messageId, User = user, CreatedDate = DateTime.Now }); result.Result = user.Id; Log.Information($"{nameof(UserCreateMessage)} sended to rmq with Id {messageId}"); return(result); } catch (Exception ex) { result.AddError(ex.Message); return(result); } }
public async Task <ProcessResult <string[]> > GetExistingVotes(int id) { ProcessResult <string[]> result = new ProcessResult <string[]>(); ApplicationUser user = null; if (result.Success) { user = await _userManager.FindByNameAsync(User.Identity.Name); if (user == null) { result.AddError("Unable to find this user"); } } if (result.Success) { string[] votes = _db.PhotoVotes .Where(v => v.Photo.Category.CategoryId == id && v.Voter.UserName == user.UserName) .OrderBy(v => v.Position) .Select(v => v.Photo.AnonymousPhotoName) .ToArray(); result.SetResult(votes); } return(result); }
public override async Task <ProcessResult <PagedList <UserDTO> > > Handle(GetUsersQuery query, CancellationToken cancellationToken) { var result = new ProcessResult <PagedList <UserDTO> >(); var org = _ctx.Organizations.FirstOrDefault(x => x.Id == query.OrgId); if (org == null) { result.AddError("OrganizationNotExist"); return(result); } var skip = query.PageIndex * query.PageSize; var users = _ctx.Users .Include(x => x.Organization) .Where(x => x.OrganizationId == query.OrgId) .Take(query.PageSize) .Skip(skip) .ToList(); var totalPages = _ctx.Users.Count() / query.PageSize; var dtos = _mapper.Map <List <UserDTO> >(users); result.Result = new PagedList <UserDTO>(query.PageIndex, query.PageSize, totalPages, dtos); return(result); }
public override async Task <ProcessResult <bool> > Handle(LinkUserToOrganizationCommand request, CancellationToken cancellationToken) { var result = new ProcessResult <bool>(); try { var user = _ctx.Users.FirstOrDefault(x => x.Id == request.UserId); if (user == null) { result.AddError("User not exist"); return(result); } var org = _ctx.Organizations.FirstOrDefault(x => x.Id == request.OrganizationId); if (org == null) { result.AddError("OrgNotExist"); return(result); } user.OrganizationId = request.OrganizationId; _ctx.Users.Update(user); var saveSucces = await _ctx.SaveChangesAsync() == 1; if (saveSucces) { result.Result = true; } else { result.AddError(@"Save failed ¯\_(ツ)_/¯"); } return(result); } catch (Exception ex) { result.AddError(ex.Message); return(result); } }
private async Task <ProcessResult <bool> > CategoryIsInRequiredStatus(int categoryId, params string[] statuses) { ProcessResult <bool> result = new ProcessResult <bool>(); PhotoCategory category = await _db. PhotoCategories .FirstOrDefaultAsync(p => p.CategoryId == categoryId); if (category == null) { result.AddError("Cannot find category"); } if (result.Success && !statuses.Contains(category.StatusCode)) { result.AddError("Category does not have the correct status to perform this action"); } return(result); }
private async Task <ProcessResult <PhotoCategory> > GetPhotoCategory(int categoryId) { ProcessResult <PhotoCategory> result = new ProcessResult <PhotoCategory>(); PhotoCategory category = await _db .PhotoCategories .FirstOrDefaultAsync(c => c.CategoryId == categoryId); if (category != null) { result.SetResult(category); } else { result.SetResult(new PhotoCategory()); result.AddError("Unable to find this category"); } return(result); }
private async Task <ProcessResult <UserViewModel> > GetUserViewModel(string userName) { ProcessResult <UserViewModel> result = new ProcessResult <UserViewModel>(); ApplicationUser user = await _userManager.FindByNameAsync(userName); if (user != null) { UserViewModelMapper mapper = new UserViewModelMapper(); UserViewModel viewModel = mapper.BuildViewModel(user); result.SetResult(viewModel); } else { result.AddError("Unable to find this user"); result.SetResult(new UserViewModel()); } return(result); }
private async Task <ProcessResult <bool> > CategoryViewModelIsValid(CategoryViewModel viewModel, int existingCategoryId = 0) { ProcessResult <bool> result = new ProcessResult <bool>(); PhotoCategory category = await _db .PhotoCategories .FirstOrDefaultAsync(p => p.CategoryName.ToUpper() == viewModel.CategoryName.ToUpper() && p.CategoryId != existingCategoryId); if (category != null) { result.AddFieldError("CategoryName", "You dummy. A category with name has already been created"); } if (!CategoryStatusCodes.GetAll().Contains(viewModel.StatusCode)) { result.AddFieldError("StatusCode", "Invalid status code"); } if (!PhotoNamingThemes.ThemeCodes.GetAll().Contains(viewModel.PhotoNamingThemeCode)) { result.AddFieldError("PhotoNamingThemeCode", "Invalid theme code"); } if (existingCategoryId != 0) { category = await _db .PhotoCategories .FirstOrDefaultAsync(p => p.CategoryId == existingCategoryId); if (category == null) { result.AddError("This category cannot be found"); } } return(result); }
private async Task <ProcessResult <bool> > SaveUserViewModel(UserViewModel viewModel, FormMode mode) { ProcessResult <bool> processResult = new ProcessResult <bool>(); if (mode == FormMode.Edit) { ApplicationUser user = await _userManager.FindByNameAsync(viewModel.UserName); if (user != null) { UserViewModelMapper mapper = new UserViewModelMapper(); user = mapper.BuildRepositoryModel(viewModel, user); IdentityResult identityResult = await _userManager.UpdateAsync(user); processResult.SetResult(identityResult); if (identityResult.Succeeded && !string.IsNullOrEmpty(viewModel.Password)) { string token = await _userManager.GeneratePasswordResetTokenAsync(user); identityResult = await _userManager.ResetPasswordAsync(user, token, viewModel.Password); processResult.SetResult(identityResult); } } else { processResult.AddError("Unable to find this user"); } } else { IdentityResult identityResult = await _userManager.CreateApplicationUserAsync(viewModel.UserName, viewModel.Nickname, viewModel.Email, viewModel.Password, JudgeMyPhotoRoles.Photographer); processResult.SetResult(identityResult); } return(processResult); }
private async Task <ProcessResult <List <Photograph> > > GetPhotoNameUpdatesAsync(int categoryId, string namingThemeCode) { string[] existingNames = await _db.Photographs .Where(p => p.Category.CategoryId == categoryId && !string.IsNullOrEmpty(p.AnonymousPhotoName)) .Select(p => p.AnonymousPhotoName) .ToArrayAsync(); List <string> potentialNames = PhotoNamingThemes .GetThemeItems(namingThemeCode) .Minus(existingNames) .InRandomSequence(); List <Photograph> photosToUpdate = await _db.Photographs .Where(p => p.Category.CategoryId == categoryId && string.IsNullOrEmpty(p.AnonymousPhotoName)) .ToListAsync(); photosToUpdate = photosToUpdate.InRandomSequence(); ProcessResult <List <Photograph> > result = new ProcessResult <List <Photograph> >(); if (photosToUpdate.Count > potentialNames.Count) { result.AddError("Not enough anonymous photo names to assign for the number of photos in this category"); } else { int itemNo = 0; foreach (Photograph photo in photosToUpdate) { photo.AnonymousPhotoName = potentialNames[itemNo]; itemNo++; } result.SetResult(photosToUpdate); } return(result); }
public async Task <ProcessResult <string> > SubmitPhoto(SubmitSinglePhotoViewModel viewModel) { ProcessResult <string> result = new ProcessResult <string>(); ProcessResult <bool> categoryStatus = await CategoryIsInRequiredStatus(viewModel.CategoryId, CategoryStatusCodes.SubmittingPhotos); if (!categoryStatus.Success) { result.AddError(categoryStatus.ErrorMessage); } if (!viewModel.FileType.ToLower().StartsWith("image")) { result.AddError("Silly thing. Only an image file type is allowed"); } if (result.Success) { Photograph photo = await _db.Photographs .FirstOrDefaultAsync(p => p.Category.CategoryId == viewModel.CategoryId && p.UserCategoryPhotoNumber == viewModel.PhotoNumber && p.Photographer.UserName == User.Identity.Name); SubmitSinglePhotoViewModelMapper mapper = new SubmitSinglePhotoViewModelMapper(); ProcessResult <bool> saveResult = null; if (photo == null) { ApplicationUser user = await _userManager.FindByNameAsync(User.Identity.Name); if (user == null) { result.AddError("Unable to find this user"); } PhotoCategory category = await _db.PhotoCategories.FirstOrDefaultAsync(c => c.CategoryId == viewModel.CategoryId); if (category == null) { result.AddError("Unable to find this category"); } if (result.Success) { photo = mapper.BuildRepositoryModel(viewModel, user, category); saveResult = _db.SaveAdditions(photo); } } else { photo = mapper.BuildRepositoryModel(viewModel, photo); saveResult = _db.SaveUpdates(photo); } if (result.Success) { if (saveResult.Success) { result.SetResult(GetImageString(photo.SmallImage)); } else { result.AddError(saveResult.ErrorMessage); } } } return(result); }
public async Task <ProcessResult <string[]> > SubmitVotes([FromBody] VotePhotosViewModel viewModel) { ProcessResult <string[]> result = new ProcessResult <string[]>(); if (viewModel.PhotoIds.Length != 3) { result.AddError("Invalid number of photos voted for"); } ApplicationUser user = null; if (result.Success) { user = await _userManager.FindByNameAsync(User.Identity.Name); if (user == null) { result.AddError("Unable to find this user"); } } PhotoCategory category = null; if (result.Success) { category = _db.PhotoCategories.FirstOrDefault(c => c.CategoryId == viewModel.CategoryId); if (category == null) { result.AddError("Unable to find this category"); } } PhotoVote[] votes = new PhotoVote[3]; if (result.Success) { int position = 0; foreach (int photoId in viewModel.PhotoIds) { Photograph photo = _db.Photographs .FirstOrDefault(p => p.PhotoId == photoId); if (photo == null) { result.AddError($"Unable to find photo id {photoId}"); } else { PhotoVote vote = new PhotoVote() { Position = position + 1, Voter = user, Photo = photo }; votes[position] = vote; } position++; } } if (result.Success) { _db.PhotoVotes.RemoveRange(_db.PhotoVotes.Where(p => p.Photo.Category.CategoryId == viewModel.CategoryId && p.Voter.UserName == user.UserName)); ProcessResult <bool> saveResult = _db.SaveAdditions(votes); if (!saveResult.Success) { result.AddError(saveResult.ErrorMessage); } } if (result.Success) { result = await GetExistingVotes(viewModel.CategoryId); } return(result); }