public async Task <IActionResult> Edit(int id, [Bind("Id,Name,AddressId,IdentityUserId,BusinessTypeId")] PetBusiness petBusiness) { if (id != petBusiness.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _repo.PetBusiness.Update(petBusiness); await _repo.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PetBusinessExists(petBusiness.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["BusinessType"] = new SelectList(_repo.BusinessType.GetAllBusinessTypes(), "Id", "TypeOfBusiness", petBusiness.BusinessType); return(View(petBusiness)); }
public async Task <IActionResult> UpdateProposedBack(int id, BackNotImageRequestModel backRqModel) { var userId = UserUtil.GetUserId(User); var admin = await userManager.GetAdmin(); var back = await repository.Back .QueryByBeingProposed(userId, admin.Id, id) .FirstOrDefaultAsync(); if (back == null) { return(NotFound()); } if (back.Approved) { return(Forbid()); } if (back.Image == null && (backRqModel.Meaning == null || backRqModel.Meaning.Length == 0)) { ModelState.AddModelError("", "Card must at least have either meaning or image."); return(BadRequest(ModelState)); } back.Type = backRqModel.Type == null || backRqModel.Type.Trim().Length == 0 ? null : backRqModel.Type.Trim().ToLower(); back.Meaning = backRqModel.Meaning == null || backRqModel.Meaning.Trim().Length == 0 ? null : backRqModel.Meaning.Trim(); back.Example = backRqModel.Example == null || backRqModel.Example.Trim().Length == 0 ? null : backRqModel.Example.Trim(); back.LastModifiedDate = DateTime.Now; await repository.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> DeleteUser(string userId) { var user = await userManager.GetUser(User); var userIsAdmin = await userManager.CheckAdminRole(user); if (!userIsAdmin) { return(Forbid()); } var deletedUser = await userManager.FindByIdAsync(userId); if (deletedUser == null) { return(NotFound()); } if (deletedUser.Id == user.Id) { ModelState.AddModelError("", "Cannot delete the admin account"); return(BadRequest(ModelState)); } var cards = await repository.Card .QueryIncludesBacks(userId) .ToListAsync(); repository.Card.DeleteRange(cards); repository.Deck.DeleteRange(repository.Deck.Query(userId)); await repository.SaveChangesAsync(); var result = await userManager.DeleteAsync(deletedUser); if (!result.Succeeded) { logger.LogError("An error when deleting the user with id {0}", deletedUser.Id); } foreach (var card in cards) { foreach (var back in card.Backs) { if (!imageService.TryDeleteImage(back.Image, ImageType.Image)) { logger.LogError("An error occurs when deleting the image with name {0}", back.Image); } } } if (deletedUser.Picture != null) { if (!imageService.TryDeleteImage(deletedUser.Picture, ImageType.Picture)) { logger.LogError("An error occurs when deleting the picture with name {0}", deletedUser.Picture); } } return(NoContent()); }
public async Task <IActionResult> Create(DeckRequestModel deckRqModel) { var userId = UserUtil.GetUserId(User); var deckSameName = await repository.Deck .QueryByName(userId, deckRqModel.Name) .AsNoTracking() .FirstOrDefaultAsync(); if (deckSameName != null) { ModelState.AddModelError("Name", "The deck name is taken."); return(BadRequest(ModelState)); } var now = DateTime.Now; var newDeck = new Deck() { Name = deckRqModel.Name.Trim(), Description = deckRqModel.Description == null || deckRqModel.Description.Trim().Length == 0 ? null : deckRqModel.Description.Trim(), Theme = deckRqModel.Theme, Completed = true, CreatedDate = now, LastModifiedDate = now, OwnerId = userId, AuthorId = userId }; repository.Deck.Create(newDeck); await repository.SaveChangesAsync(); return(CreatedAtAction(nameof(GetDeck), new { Id = newDeck.Id }, new { Message = "Created Successfully", Id = newDeck.Id })); }
public async Task <int> CreateCommentAsync(CommentCreateRequest request) { Comment comment = _mapper.Map <Comment>(request); comment.CreateDate = DateTime.Now; comment.ModifiedDate = DateTime.Now; await _repository.CommmentRepo.CreateAsync(comment); await _repository.SaveChangesAsync(); return(comment.Id); }
public async Task <BaseResponseDto <bool> > Handle(DeleteClassRequest request, CancellationToken cancellationToken) { BaseResponseDto <bool> response = new BaseResponseDto <bool>(); try { var deletedClass = await _repositoryWrapper.Class.Find(request.Id); if (deletedClass == null) { response.Errors.Add("Böyle bir sınıf bulunamadı."); } else { _repositoryWrapper.Class.Delete(deletedClass.Id); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = true; } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Class silinirken bir hata oluştu."); } return(response); }
public async Task <BaseResponseDto <PostDto> > Handle(CreatePostRequest request, CancellationToken cancellationToken) { BaseResponseDto <PostDto> response = new BaseResponseDto <PostDto>(); try { var post = new Post { Body = request.Body, Classid = request.Classid, CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now, Title = request.Title, Userid = request.Userid }; await _repositoryWrapper.Post.Create(post); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = post.Adapt <PostDto>(); } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Post oluşturulurken bir hata oluştu."); } return(response); }
public async Task <BaseResponseDto <MemberDto> > Handle(AddMemberRequest request, CancellationToken cancellationToken) { BaseResponseDto <MemberDto> response = new BaseResponseDto <MemberDto>(); try { var addMember = new Member { CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now, Classid = request.Classid, Userid = request.Userid }; await _repositoryWrapper.Member.Create(addMember); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = addMember.Adapt <MemberDto>(); } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Üye oluşturulurken bir hata oluştu."); } return(response); }
public async Task <bool> ImplementUpdateAsync() { if (_localDataModel.OpeningsLocalPullAction != null && _localDataModel.OpeningsLocalPullAction.Count() > 0) { _localPullUpdate = new LocalPullUpdating(_localDataModel.OpeningsLocalPullAction, _idDrawing, _repository); } if (_localDataModel.OpeningsLocalPushAction != null && _localDataModel.OpeningsLocalPushAction.Count() > 0) { _localPushUpdate = new LocalPushUpdating(_localDataModel.OpeningsLocalPushAction, _idDrawing, _repository); } var tasks = new List <Task <bool> >(); if (_localPushUpdate != null) { tasks.Add(_localPushUpdate.ImplementUpdateAsync()); } if (_localPullUpdate != null) { tasks.Add(_localPullUpdate.ImplementUpdateAsync()); } await Task.WhenAll(tasks); await _repository.SaveChangesAsync(); //_repository.CommitTransaction(); await UpdateProcessing.CreateRevisionAsync(_repository, _idDrawing); return(true); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Name")] PetOwner petOwner) { if (id != petOwner.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _repo.Update(petOwner); await _repo.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PetOwnerExists(petOwner.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(petOwner)); }
public async Task <IActionResult> PostAirAsync( AirFromSensorDto airFromSensorDto) { if (airFromSensorDto.Name != "2063272") { return(new UnauthorizedResult()); } var time = new Time { Timestamp = airFromSensorDto.Time.UtcDateTime, Values = new List <Value>() }; foreach (var value in airFromSensorDto.SensorDataValues) { var currentValue = _mapper.Map <Value>(value); time.Values.Add(currentValue); } await _repository.Times.CreateAsync(time); await _repository.SaveChangesAsync(); var timeDto = _mapper.Map <TimeDto>(time); return(CreatedAtRoute("GetTimes", new { time.Id }, timeDto)); }
public async Task <IActionResult> UpdatePublicDeckStatus(int id, BoolValueRequestModel valueRqModel) { var user = await userManager.GetUser(User); var userIsAdmin = await userManager.CheckAdminRole(user); if (!userIsAdmin) { return(Forbid()); } var notApprovedDeck = await repository.Deck .QueryByIdAndBeingNotApproved(id) .FirstOrDefaultAsync(); if (notApprovedDeck == null) { return(NotFound()); } notApprovedDeck.Approved = valueRqModel.Value; notApprovedDeck.Public = valueRqModel.Value; await repository.SaveChangesAsync(); return(NoContent()); }
public async Task <BaseResponseDto <UserDto> > Handle(CreateUserRequest request, CancellationToken cancellationToken) { BaseResponseDto <UserDto> response = new BaseResponseDto <UserDto>(); try { var user = new User { CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now, Firstname = request.Firstname, Lastname = request.Lastname, Password = getHash(request.Password), Email = request.Email, ActivationCode = "123asd133", ProfileImageUrl = "asdasdasdasd654f6asdf", SchoolNumber = request.SchoolNumber, UserRole = Policies.User }; await _repositoryWrapper.User.Create(user); await _repositoryWrapper.SaveChangesAsync(); response.Data = user.Adapt <UserDto>(); //await _mediator.Publish(new NewUserCreatedEvent(user.Firstname)); } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Kullanıcı oluşturulurken bir hata oluştu."); } return(response); }
public async Task <BaseResponseDto <bool> > Handle(UpdateUserRequest request, CancellationToken cancellationToken) { BaseResponseDto <bool> response = new BaseResponseDto <bool>(); try { var user = await _repositoryWrapper.User.Find(request.Id); user.Firstname = request.Firstname; user.Lastname = request.Lastname; user.SchoolNumber = request.SchoolNumber; user.Email = request.Email; _repositoryWrapper.User.Update(user); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = true; } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Kullanıcı oluşturulurken bir hata oluştu."); } return(response); }
public async Task <BaseResponseDto <bool> > Handle(UpdatePostRequest request, CancellationToken cancellationToken) { BaseResponseDto <bool> response = new BaseResponseDto <bool>(); try { var post = await _repositoryWrapper.Post.Find(request.Id); if (post != null) { post.Body = request.Body; post.Title = request.Title; _repositoryWrapper.Post.Update(post); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = true; } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } else { response.Errors.Add("Böyle bir post bulunamadı."); } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Post güncellenirken bir hata oluştu."); } return(response); }
public async Task <IActionResult> Create(CardRequestModel cardRqModel) { var user = await userManager.GetUser(User); var cardSameFront = await repository.Card .QueryByFront(user.Id, cardRqModel.Front) .FirstOrDefaultAsync(); if (cardSameFront != null && (!cardSameFront.Public || cardSameFront.Approved)) { ModelState.AddModelError("Front", "The front is taken."); return(BadRequest(ModelState)); } var userIsAdmin = await userManager.CheckAdminRole(user); var now = DateTime.Now; if (cardSameFront == null) { cardSameFront = new Card() { Front = cardRqModel.Front.Trim(), Public = userIsAdmin, Approved = userIsAdmin, CreatedDate = now, LastModifiedDate = now, OwnerId = user.Id, AuthorId = user.Id }; repository.Card.Create(cardSameFront); } else { cardSameFront.Front = cardRqModel.Front.Trim(); cardSameFront.Public = true; cardSameFront.Approved = true; cardSameFront.CreatedDate = now; cardSameFront.LastModifiedDate = now; } await repository.SaveChangesAsync(); return(CreatedAtAction(nameof(GetCardById), new { Id = cardSameFront.Id }, new { Message = "Created Successfully.", Id = cardSameFront.Id })); }
public async Task <IActionResult> Update(int id, BackNotImageRequestModel backRqModel) { var user = await userManager.GetUser(User); var back = await repository.Back .QueryById(user.Id, id) .FirstOrDefaultAsync(); if (back == null) { return(NotFound()); } var notChanged = true; notChanged = back.Meaning.ToLower() == backRqModel.Meaning.Trim().ToLower() && notChanged; notChanged = back.Type?.ToLower() == backRqModel.Type?.Trim().ToLower() && notChanged; notChanged = back.Example?.ToLower() == backRqModel.Example?.Trim().ToLower() && notChanged; back.Type = backRqModel.Type == null || backRqModel.Type.Trim().Length == 0 ? null : backRqModel.Type.Trim().ToLower(); back.Meaning = backRqModel.Meaning == null || backRqModel.Meaning.Trim().Length == 0 ? null : backRqModel.Meaning.Trim(); back.Example = backRqModel.Example == null || backRqModel.Example.Trim().Length == 0 ? null : backRqModel.Example.Trim(); back.LastModifiedDate = DateTime.Now; var decks = await repository.Deck .QueryByCardId(back.CardId) .ToListAsync(); var userIsAdmin = await userManager.CheckAdminRole(user); foreach (var deck in decks) { deck.Approved = deck.Approved && (userIsAdmin || notChanged); } await repository.SaveChangesAsync(); return(NoContent()); }
public async Task <BaseResponseDto <ClassDto> > Handle(CreateClassRequest request, CancellationToken cancellationToken) { BaseResponseDto <ClassDto> response = new BaseResponseDto <ClassDto>(); try { System.Security.Claims.ClaimsPrincipal claims = new System.Security.Claims.ClaimsPrincipal(); var identifier = claims.Claims.FirstOrDefault(predicate => predicate.Type == "id"); if (identifier == null) { response.Errors.Add("Yetkilendirme hatası"); response.Data = null; } else { var user = await _repositoryWrapper.User.Find(int.Parse(identifier.ToString())); if (user.UserRole != "Admin") { response.Errors.Add("Sınıf oluşturmak için yetkiniz bulunmamaktadır."); response.Data = null; } else { var newClass = new Class { CreatedAt = DateTime.Now, EducationYear = request.EducationYear, ModifiedAt = DateTime.Now, Name = request.Name, AlphaNumericCode = AlphanumericCodeGenerator(8) }; await _repositoryWrapper.Class.Create(newClass); if (await _repositoryWrapper.SaveChangesAsync()) { response.Data = newClass.Adapt <ClassDto>(); } else { response.Errors.Add("Veri tabanı kayıt esnasında bir sorun oluştu."); } } } } catch (Exception ex) { _logger.LogError(ex, ex.InnerException.Message); response.Errors.Add(ex.InnerException.Message); response.Errors.Add("Class oluşturulurken bir hata oluştu."); } return(response); }
public async Task <Guid?> CreateCustomerAsync(CustomerDTO customerDTO) { try { var customer = _mapper.Map <CustomerDTO, Customer>(customerDTO); _rw.Customer.CreateCustomer(customer); await _rw.SaveChangesAsync(); customerDTO.Id = customer.Id; var company = _mapper.Map <CustomerCompanyDTO, Company>(customerDTO.Company); if (company != null) { company.Customer = customer; AddCompany(company, customer.Id); } var person = _mapper.Map <CustomerPersonDTO, Person>(customerDTO.Person); if (person != null) { AddPerson(person, customer.Id); } var phones = _mapper.Map <List <CustomerPhoneDTO>, List <CustomerPhones> >(customerDTO.Phones); if (phones != null) { foreach (var phone in phones) { AddCustomerPhone(phone, customer.Id); } } await _rw.SaveChangesAsync(); return(customer.Id); }catch (Exception ex) { return(null); } }
public async Task <ActionResult <FCMClientDTO> > PostFCMClient(FCMClientDTO model) { var output = new FCMClientDTO(); try { if (model == null) { output.ErrorCode = "001"; output.Message = Utils.ConstMessage.GetMsgConst("001"); return(output); } var checkExists = _repoWrapper.FCMClient.FirstOrDefault(p => p.Token == model.Token); if (checkExists != null) { output.ErrorCode = "009"; output.Message = Utils.ConstMessage.GetMsgConst("009"); return(output); } model.CreateDate = DateTime.Now; model.LastSeen = DateTime.Now; var models = _mapper.Map <FCMClient>(model); _repoWrapper.FCMClient.Create(models); await _repoWrapper.SaveChangesAsync(); output.FCMClientID = models.FCMClient_ID; output.Message = Utils.ConstMessage.GetMsgConst("006"); return(output); } catch (Exception ex) { _logger.LogError($"PostFCMClient: " + ex.ToString()); output.ErrorCode = "01"; output.Message = $"Có lỗi trong quá trình cập nhật"; return(output); } }
public async Task <IActionResult> DeleteShortcut(int deckId) { var userId = UserUtil.GetUserId(User); var sharedDeck = await repository.SharedDeck .QueryByUserIdAndDeckIdAndBeingPinned(userId, deckId) .FirstOrDefaultAsync(); if (sharedDeck == null) { return(NotFound()); } sharedDeck.Pinned = false; await repository.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> SyncDataOfLocalAsync([FromBody] LocalDataModelDTO <ElementGetDTO> localDataModel) { IUpdatingData updatingFromLocal = new ManagerUpdate(localDataModel, _repository); using (var transaction = await _repository.StartTransaction()) { try { await updatingFromLocal.ImplementUpdateAsync(); await _repository.SaveChangesAsync(); transaction.Commit(); return(Ok()); } catch (Exception ex) { transaction.Rollback(); throw; } } }
public async Task <ApiResult <bool> > DeleteUserAsync(int id) { var user = await _repository.UserRepo.FindByIdAsync(id); if (user is null) { return(new ApiErrorResult <bool>("User does not found")); } user.Status = UserStatus.Disable; _repository.UserRepo.Update(user); var result = await _repository.SaveChangesAsync(); if (result != 0) { return(new ApiSuccessResult <bool>()); } return(new ApiErrorResult <bool>("Delete failed")); }
public async Task <IActionResult> PostLoanDetail([FromBody] LoanDetail loanDetail) { try { if (loanDetail == null) { return(BadRequest(ModelState)); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _repoWrapper.LoanDetail.PostLoanDetail(loanDetail); await _repoWrapper.SaveChangesAsync(); return(CreatedAtAction("GetLoanDetail", new { id = loanDetail.LNId }, loanDetail)); } catch { return(StatusCode(500, "Internal server error")); } }
public async Task <IActionResult> GetShortcutFromDeck(int id) { var userId = UserUtil.GetUserId(User); var publicDeck = await repository.Deck .QueryByIdIncludesSharedDeck(id) .FirstOrDefaultAsync(); if (publicDeck == null) { return(NotFound()); } if (publicDeck.OwnerId == userId) { return(BadRequest()); } if (!publicDeck.SharedDecks.Any(sd => sd.UserId == userId)) { publicDeck.SharedDecks.Add(new SharedDeck() { UserId = userId, Pinned = true }); } else { var sharedDeck = await repository.SharedDeck .QueryByUserIdAndDeckId(userId, publicDeck.Id) .FirstOrDefaultAsync(); sharedDeck.Pinned = true; } await repository.SaveChangesAsync(); return(CreatedAtAction("GetDeck", "Decks", new { Id = id }, new { Message = "Created Successfully.", Id = id })); }
public async Task <IActionResult> ProposeCard([FromForm] ProposedCardRequestModel cardRqModel) { if (cardRqModel.Image != null) { if (cardRqModel.Image.Length > 5242880) { ModelState.AddModelError("Image", "File is not exceeded 5MB."); } if (!ImageUtil.CheckExtensions(cardRqModel.Image)) { ModelState.AddModelError("Image", "Accepted images that images are with an extension of .png, .jpg, .jpeg or .bmp."); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } var admin = await userManager.GetAdmin(); var card = await repository.Card .QueryByFront(admin.Id, cardRqModel.Front) .AsNoTracking() .FirstOrDefaultAsync(); var userId = UserUtil.GetUserId(User); var now = DateTime.Now; if (card == null) { card = new Card() { Front = cardRqModel.Front.Trim(), Public = true, Approved = false, CreatedDate = now, LastModifiedDate = now, Owner = admin, AuthorId = userId }; repository.Card.Create(card); await repository.SaveChangesAsync(); } var imageName = await imageService.UploadImage(cardRqModel.Image, ImageType.Image); var newBack = new Back() { Type = cardRqModel.Type == null || cardRqModel.Type.Trim().Length == 0 ? null : cardRqModel.Type.Trim().ToLower(), Meaning = cardRqModel.Meaning == null || cardRqModel.Meaning.Trim().Length == 0 ? null : cardRqModel.Meaning.Trim(), Example = cardRqModel.Example == null || cardRqModel.Example.Trim().Length == 0 ? null : cardRqModel.Example.Trim(), Image = imageName, Public = true, Approved = false, CreatedDate = now, LastModifiedDate = now, CardId = card.Id, AuthorId = userId }; repository.Back.Create(newBack); await repository.SaveChangesAsync(); return(Ok()); }
public async Task <IActionResult> DownloadPublicCard(int id) { var publicCard = await repository.Card .QueryByIdIncludesBacks(id) .FirstOrDefaultAsync(); if (publicCard == null || !publicCard.Approved) { return(NotFound()); } var userId = UserUtil.GetUserId(User); var ownedCard = await repository.Card .QueryByFrontIncludesBacks(userId, publicCard.Front) .FirstOrDefaultAsync(); if (ownedCard == null) { ownedCard = new Card() { Front = publicCard.Front, CreatedDate = publicCard.CreatedDate, LastModifiedDate = publicCard.LastModifiedDate, OwnerId = userId, AuthorId = publicCard.AuthorId, Backs = new List <Back>() }; repository.Card.Create(ownedCard); } if (ownedCard.SourceId == null) { ownedCard.Source = publicCard; } foreach (var publicBack in publicCard.Backs) { if (publicBack.Approved && !ownedCard.Backs.Any(b => b.SourceId == publicBack.Id)) { var imageName = imageService.DuplicateImage(publicBack.Image); if (publicBack.Image != null && imageName == null) { logger.LogError("An error occurs when duplicating the image with name {0}", publicBack.Image); } ownedCard.Backs.Add(new Back() { Type = publicBack.Type, Meaning = publicBack.Meaning, Example = publicBack.Example, Image = imageName, CreatedDate = publicBack.CreatedDate, LastModifiedDate = publicBack.LastModifiedDate, SourceId = publicBack.Id, AuthorId = publicBack.AuthorId }); } } await repository.SaveChangesAsync(); return(NoContent()); }
public async Task <IActionResult> DownloadDeck(int id) { var admin = await userManager.GetAdmin(); var publicDeck = await repository.Deck .QueryByIdAndBeingApproved(admin.Id, id) .FirstOrDefaultAsync(); if (publicDeck == null) { return(NotFound()); } var userId = UserUtil.GetUserId(User); var ownedDeck = await repository.Deck .QueryBySourceId(userId, publicDeck.Id) .AsNoTracking() .FirstOrDefaultAsync(); if (ownedDeck != null) { return(Ok()); } var allDeckNames = repository.Deck .Query(userId) .Select(d => d.Name) .ToHashSet(); var newDeckName = GetDeckName(allDeckNames, publicDeck.Name); var newDeck = new Deck() { Name = newDeckName, Description = publicDeck.Description, Theme = publicDeck.Theme, CreatedDate = publicDeck.CreatedDate, LastModifiedDate = publicDeck.LastModifiedDate, OwnerId = userId, AuthorId = publicDeck.AuthorId, Source = publicDeck, CardAssignments = new List <CardAssignment>() }; repository.Deck.Create(newDeck); var publicCards = await repository.Card .QueryByDeckIdIncludesBacks(publicDeck.Id) .ToListAsync(); var publicFronts = publicCards.Select(c => c.Front.ToLower()).ToArray(); var ownedCards = await repository.Card .QueryByFrontsIncludesBacks(userId, publicFronts) .ToListAsync(); var cardsOfDeck = new List <Card>(); foreach (var publicCard in publicCards) { var ownedCard = ownedCards.FirstOrDefault(c => c.Front.ToLower() == publicCard.Front.ToLower()); if (ownedCard == null) { ownedCard = new Card() { Front = publicCard.Front, CreatedDate = publicCard.CreatedDate, LastModifiedDate = publicCard.LastModifiedDate, OwnerId = userId, AuthorId = publicCard.AuthorId, Backs = new List <Back>() }; repository.Card.Create(ownedCard); } cardsOfDeck.Add(ownedCard); if (ownedCard.SourceId == null) { ownedCard.Source = publicCard; } foreach (var publicBack in publicCard.Backs) { if (publicBack.Approved && !ownedCard.Backs.Any(b => b.SourceId == publicBack.Id)) { var imageName = imageService.DuplicateImage(publicBack.Image); if (publicBack.Image != null && imageName == null) { logger.LogError("An error occurs when duplicating the image with name {0}", publicBack.Image); } ownedCard.Backs.Add(new Back() { Type = publicBack.Type, Meaning = publicBack.Meaning, Example = publicBack.Example, Image = imageName, CreatedDate = publicBack.CreatedDate, LastModifiedDate = publicBack.LastModifiedDate, SourceId = publicBack.Id, AuthorId = publicBack.AuthorId }); } } } await repository.SaveChangesAsync(); foreach (var card in cardsOfDeck) { newDeck.CardAssignments.Add(new CardAssignment() { Card = card }); } await repository.SaveChangesAsync(); return(Ok(new { Message = "Downloaded Successfully.", Id = newDeck.Id })); }
public async Task <IActionResult> ConsiderProposedBacks(ProposedBacksRequestModel backsRqModel) { var user = await userManager.GetUser(User); var userIsAdmin = await userManager.CheckAdminRole(user); if (!userIsAdmin) { return(Forbid()); } if (backsRqModel.ProposedBacks.Length == 0) { ModelState.AddModelError("ProposedBacks", "The ProposedBacks field is required."); return(BadRequest(ModelState)); } var notApprovedBacks = await repository.Back .QueryByBeingNotApproved(user.Id, backsRqModel.ProposedBacks) .ToListAsync(); if (notApprovedBacks.Count != backsRqModel.ProposedBacks.Length) { ModelState.AddModelError("ProposedBacks", "At least a back is not proposed back."); return(BadRequest(ModelState)); } if (backsRqModel.Approved) { foreach (var back in notApprovedBacks) { back.Approved = true; } } else { repository.Back.DeleteRange(notApprovedBacks); } await repository.SaveChangesAsync(); var card = await repository.Card .QueryByIdIncludesBacks(user.Id, notApprovedBacks[0].CardId) .FirstOrDefaultAsync(); if (card == null) { return(NoContent()); } if (backsRqModel.Approved) { card.Approved = true; } else if (card.Backs.Count == 0) { repository.Card.Delete(card); } await repository.SaveChangesAsync(); if (!backsRqModel.Approved) { foreach (var back in notApprovedBacks) { if (back.Image != null) { if (!imageService.TryDeleteImage(back.Image, ImageType.Image)) { logger.LogError("An error occurs when deleting the image with name {0}", back.Image); } } } } return(NoContent()); }
public async Task <int> CreateListingAsync(ListingCreateRequest request) { User user = await _repository.UserRepo.FindByCondition(x => x.UserName == request.CreateBy) .SingleOrDefaultAsync(); Listing listing = _mapper.Map <Listing>(request); listing.CreateDate = DateTime.Now; listing.ModifiedDate = DateTime.Now; listing.ListingNotes = new List <ListingNote>() { new ListingNote() { UserId = user.Id, Text = request.ListingNote } }; if (request.ThumbnailImage != null) { listing.ListingPhotos = new List <ListingPhoto>() { new ListingPhoto() { PhotoUrl = await SaveFile(request.ThumbnailImage), IsDefault = true } }; } await _repository.ListingRepo.CreateAsync(listing); await _repository.SaveChangesAsync(); return(listing.Id); }