public async Task CreateOrderAsync(int basketId, Address shippingAddress) { var basket = await _basketRepository.GetByIdAsync(basketId); Guard.Against.NullBasket(basketId, basket); var items = new List <OrderItem>(); foreach (var item in basket.Items) { var catalogItem = await _itemRepository.GetByIdAsync(item.CatalogItemId); var itemOrdered = new CatalogItemOrdered(catalogItem.Id, catalogItem.Name, catalogItem.PictureUri); var orderItem = new OrderItem(itemOrdered, item.UnitPrice, item.Quantity); items.Add(orderItem); } var order = new Order(basket.BuyerId, shippingAddress, items); await _orderRepository.AddAsync(order); }
public async Task TransferBasketAsync(string anonymousId, string userId) { var specAnon = new BasketWithItemsSpecification(anonymousId); var basketAnon = await _basketRepository.FirstOrDefaultAsync(specAnon); if (basketAnon == null || !basketAnon.Items.Any()) { return; } var specUser = new BasketWithItemsSpecification(userId); var basketUser = await _basketRepository.FirstOrDefaultAsync(specUser); if (basketUser == null) { basketUser = await _basketRepository.AddAsync(new Basket() { BuyerId = userId }); } foreach (BasketItem itemAnon in basketAnon.Items) { var itemUser = basketUser.Items.FirstOrDefault(x => x.ProductId == itemAnon.ProductId); if (itemUser == null) { basketUser.Items.Add(new BasketItem() { ProductId = itemAnon.ProductId, Quantity = itemAnon.Quantity }); } else { itemUser.Quantity += itemAnon.Quantity; } } await _basketRepository.UpdateAsync(basketUser); await _basketRepository.DeleteAsync(basketAnon); }
/// <summary> /// Create new comment /// </summary> /// <param name="viewModel">comment data</param> /// <returns></returns> public async Task <Comment> CreateCommentAsync(CreateCommentViewModel viewModel) { Guard.Against.Null(viewModel, nameof(viewModel)); Guard.Against.GuidEmpty(viewModel.FromId, nameof(viewModel.FromId)); Guard.Against.GuidEmpty(viewModel.PostId, nameof(viewModel.PostId)); Guard.Against.NullOrEmpty(viewModel.Text, nameof(viewModel.Text)); //check post exists var post = await _postRepository.GetByIdAsync(viewModel.PostId); Guard.Against.PostNotExists(post, viewModel.PostId); //create post based on commentDto var comment = new Comment(viewModel.FromId, viewModel.PostId, new Content(viewModel.Text)); await _commentRepository.AddAsync(comment); return(await _commentRepository.GetByIdAsync(comment.Id)); }
public async Task <CommentLike> Like(Guid userId, Guid commentId) { var isExist = await _commentLikeRepository.GetAll() .FirstOrDefaultAsync(x => x.IsDeleted == false && x.UserId == userId && x.CommentId == commentId); if (isExist != null) { throw new Exception("Bu islem daha once yapilmis"); } var model = new CommentLike { UserId = userId, CommentId = commentId }; await _commentLikeRepository.AddAsync(model); var comment = await _commentRepository.GetByIdAsync(commentId); var post = await _postRepository.GetByIdAsync(comment.PostId); var user = await _userRepository.GetByIdAsync(userId); var community = await _communityRepository.GetByIdAsync(post.CommunityId); if (comment.UserId == user.Id) { return(model); } var notify = new Notification { Content = user.Username + " " + "sallamanı beğendi : " + comment.Content, TargetId = post.Id, ImgPath = user.ProfileImagePath, TargetName = community.Slug + "/" + post.Slug, OwnerUserId = comment.UserId, Type = NotifyContentType.CommentLike }; await _notificationRepository.AddAsync(notify); return(model); }
public async Task <ResponseMessageDto> AddCustomerRates(CustomerRatesRequestDto dto) { try { if (_customerRateRepository.IsRateAssignedToCustomer(dto.CustomerId)) { return new ResponseMessageDto() { FailureMessage = ResponseMessages.RatesAssignedToCustomer, Success = false, Error = true } } ; var customerRates = await _asyncRepository.AddAsync(_mapper.Map <CustomerRates>(dto)); _customerRepository.SetIsCustomerRateAssigned(dto.CustomerId, true); return(new ResponseMessageDto() { Id = customerRates.Id, SuccessMessage = ResponseMessages.InsertionSuccessMessage, Success = true, Error = false }); } catch (Exception e) { Console.WriteLine(e); return(new ResponseMessageDto() { Id = Convert.ToInt16(Enums.FailureId), FailureMessage = ResponseMessages.InsertionFailureMessage, Success = false, Error = true, ExceptionMessage = e.InnerException != null ? e.InnerException.Message : e.Message }); } }
public async Task <User> CreateUser(CreateUserDto input) { var isUsernameTaken = await _userRepository.GetAll().FirstOrDefaultAsync(x => x.Username == input.Username); if (isUsernameTaken != null) { var model = new User(); model.Username = "******"; return(model); } var isEmailTaken = await _userRepository.GetAll().FirstOrDefaultAsync(x => x.EmailAddress == input.EmailAddress); if (isEmailTaken != null) { var model = new User(); model.EmailAddress = "Bu E-Posta adresi daha önce alınmış"; return(model); } var user = new User { Username = input.Username, EmailAddress = input.EmailAddress, Gender = input.Gender, Bio = input.Bio, VerificationCode = RandomString.GenerateString(35) }; if (input.ProfileImage != null) { var imgPath = await _blobService.InsertFile(input.ProfileImage); user.ProfileImagePath = imgPath; } var hashedPassword = SecurePasswordHasherHelper.Hash(input.Password); user.Password = hashedPassword; await _userRepository.AddAsync(user); return(user); }
public async Task <Event> AddVotesToEventAsync(Guid eventId, string personName, IReadOnlyList <DateTime> votedDates) { // Check if there is already a vote for this event by the person var existingVote = (await _voteRepository.ListAsync(new VoteSpecifications(eventId, personName))).SingleOrDefault(); var suggestedDateIds = (await _suggestedDateRepository.ListAsync(new SuggestedDateSpecifications(eventId, votedDates))).Select(i => i.Id); if (existingVote != null && suggestedDateIds.Any()) { var existingVoteSuggestedDateIds = existingVote.VoteSuggestedDates.Select(i => i.SuggestedDateId).ToArray(); var addedVotesForExistingDates = suggestedDateIds .Where(suggestedDateId => !existingVoteSuggestedDateIds.Contains(suggestedDateId)) .Select(suggestedDateId => new VoteSuggestedDate { VoteId = existingVote.Id, SuggestedDateId = suggestedDateId }).ToArray(); foreach (var addedVote in addedVotesForExistingDates) { await _voteSuggestedDateRepository.AddAsync(addedVote); } } else if (suggestedDateIds.Any()) { await _voteRepository.AddAsync(new Vote { PersonName = personName, EventId = eventId, VoteSuggestedDates = suggestedDateIds.Select(i => new VoteSuggestedDate { SuggestedDateId = i, }).ToArray() }); } else { return(null); } return(await GetEventByIdAsync(eventId)); }
public async Task <Result <Student> > Handle(RegisterStudentCommand command) { Course favoriteCourse = Course.FromId(command.FavoriteCourseId); if (favoriteCourse == null) { return(Result.Failure <Student>("Course not found")); } Suffix suffix = Suffix.FromId(command.NameSuffixId); if (suffix == null) { return(Result.Failure <Student>("Suffix not found")); } Result <Email> emailResult = Entities.Email.Create(command.Email); if (emailResult.IsFailure) { return(Result.Failure <Student>(emailResult.Error)); } Result <Name> nameResult = Name.Create(command.FirstName, command.LastName, suffix); if (nameResult.IsFailure) { return(Result.Failure <Student>(nameResult.Error)); } var student = new Student( nameResult.Value, emailResult.Value, favoriteCourse, command.FavoriteCourseGrade); await _studentRepository.AddAsync(student); await _studentRepository.SaveChangesAsync(); return(Result.Success(student)); }
public async Task <IActionResult> Create(TestUserProfile newProfile, IFormCollection collection) { try { if (!ModelState.IsValid) { return(View(newProfile)); } await _profileRepository.AddAsync(newProfile); return(RedirectToAction(nameof(Index))); } catch { //todo log exception } return(View(newProfile)); }
public async Task Add(CompanyViewModel companyVm) { var userId = ExtensionMethod.GetUserId(_httpContextAccessor.HttpContext); if (userId == null) { throw new ArgumentNullException("UserId is null"); } var company = new Company { Name = companyVm.Name, Address = companyVm.Address, HotLine = companyVm.HotLine, CreatorUserId = userId, CreationTime = DateTime.Now }; await _asyncRepository.AddAsync(company); await _asyncRepository.unitOfWork.SaveChangesAsync(); }
public async Task <ActionResult> Create() { var student = new Student() { Email = "*****@*****.**" }; await _repository.AddAsync(student); var address = new StudentAddress() { StudentId = student.Id }; await _addressRepository.AddAsync(address); await _uow.CommitAsync(); return(Ok()); }
public async Task <User> CreateUser(CreateUserDto input) { var user = new User { Name = input.Name, Surname = input.Surname, EmailAddress = input.EmailAddress, Profession = input.Profession, Gender = input.Gender, Username = input.Username, Age = input.Age, PhoneNumber = input.PhoneNumber }; var hashedPassword = SecurePasswordHasherHelper.Hash(input.Password); user.Password = hashedPassword; await _userRepository.AddAsync(user); return(user); }
public async Task AddFavorite(FavoriteRequestModel favoriteRequest) { if (_currentUserService.UserId != favoriteRequest.UserId) { throw new HttpException(HttpStatusCode.Unauthorized, "You are not Authorized to purchase"); } // See if Movie is already Favorite. if (await FavoriteExists(favoriteRequest.UserId, favoriteRequest.MovieId)) { throw new ConflictException("Movie already Favorited"); } var favorite = new Favorite() { MovieId = favoriteRequest.MovieId, UserId = favoriteRequest.UserId }; await _favoriteRepository.AddAsync(favorite); }
public async Task <Guid> Handle( CreateCandidateCommand request, CancellationToken cancellationToken) { var createCandidateCommandResponse = new CreateCandidateCommandResponse(); var validator = new CreateCandidateCommandValidator(); var validationResult = await validator.ValidateAsync(request); if (validationResult.Errors.Count > 0) { throw new Exceptions.ValidationException(validationResult); } var @candidate = _mapper.Map <Candidate>(request); @candidate = await _candidateRepository.AddAsync(@candidate); return(@candidate.CandidateId); }
public async Task <RequestConfirmarOrden> CreateOrden(RequestConfirmarOrden orden) { orden.FechaCreacion = DateTime.Now.ToString(); var EntityOrden = _mapper.Map <Ordenes>(orden); var ordenCreada = await _repositoryOrdenes.AddAsync(EntityOrden); var ListaDetalleOrden = orden.DetallesOrden; List <DetalleOrdenes> ListaEnDetalleOrdenes = new List <DetalleOrdenes>(); foreach (var elemento in ListaDetalleOrden) { var EntityDetalleOrden = _mapper.Map <DetalleOrdenes>(elemento); EntityDetalleOrden.OrdenId = ordenCreada.Id; ListaEnDetalleOrdenes.Add(EntityDetalleOrden); } await _repositoryDetalleOrdenes.AddRangeAsync(ListaEnDetalleOrdenes); return(orden); }
public async Task CreateAsync(OrderDetailsDto orderDetailsDto) { if (orderDetailsDto == null) { throw new InvalidServiceOperationException("Is null dto"); } var orderDetails = _mapper.Map <OrderDetails>(orderDetailsDto); await ValidateQuantityAsync(orderDetails); var gameDto = await _gameService.GetByIdAsync(orderDetailsDto.GameId); orderDetails.Price = gameDto.Price; orderDetails.Discount = gameDto.Discount; await _orderDetailsDecorator.AddAsync(orderDetails); await _unitOfWork.CommitAsync(); }
public async Task <CanastaDTO> CreateCanastaAsync(CanastaDTO canasta) { var nuevaCanasta = new ApplicationCore.Entities.Canasta { //id_canasta = canasta.Id, id_estado = canasta.Id_estado, id_producto = canasta.Id_producto, id_usuario = canasta.Id_usuario, cantidad_canasta = canasta.Cantidad_canasta, precio_canasta = canasta.precio_canasta }; nuevaCanasta = await _repository.AddAsync(nuevaCanasta); await _unitOfWork.ConfirmarAsync(); canasta.Id = nuevaCanasta.id_canasta; _publisher.DistribuirCanasta(nuevaCanasta); return(canasta); }
public async Task PurchaseMovie(PurchaseRequestModel purchaseRequest) { if (_currentUserService.UserId != purchaseRequest.UserId) { throw new HttpException(HttpStatusCode.Unauthorized, "You are not Authorized to purchase"); } // See if Movie is already purchased. if (await IsMoviePurchased(purchaseRequest)) { throw new ConflictException("Movie already Purchased"); } // Get Movie Price from Movie Table var movie = await _movieService.GetMovieAsync(purchaseRequest.MovieId); purchaseRequest.TotalPrice = movie.Price; var purchase = _mapper.Map <Purchase>(purchaseRequest); await _purchaseRepository.AddAsync(purchase); }
public async Task CreateOrderAsync( int basketId, Entities.OrderAggregate.Address shippingAddress, PaymentInfo paymentDetails, OrderStatus status, Purchase purchase, PurchaseResponse purchaseResponse) { var basket = await _basketRepository.GetByIdAsync(basketId); if (basket == null) { throw new BasketNotFoundException(basketId); } var items = new List <OrderItem>(); var pricesAndQuantities = new List <Tuple <decimal, int> >(); foreach (var item in basket.Items) { var catalogItem = await _itemRepository.GetByIdAsync(item.CatalogItemId); var itemOrdered = new CatalogItemOrdered(catalogItem.Id, catalogItem.Name, catalogItem.PictureUri); var orderItem = new OrderItem(itemOrdered, item.UnitPrice, item.Quantity); items.Add(orderItem); pricesAndQuantities.Add(new Tuple <decimal, int>(item.UnitPrice, item.Quantity)); } var totals = OrderCalculator.CalculateTotals(pricesAndQuantities); var order = new Order( basket.BuyerId, shippingAddress, paymentDetails, items, status, purchase, purchaseResponse, totals); await _orderRepository.AddAsync(order); }
public async Task CreateAndSendInvitationAsync(Employee employee, ServerSettings server, DateTime validTo) { if (employee == null) { throw new ArgumentNullException(nameof(employee)); } if (employee.Id == null) { throw new ArgumentNullException(nameof(employee.Id)); } if (employee.Email == null) { throw new ArgumentNullException(nameof(employee.Email)); } var activationCode = GenerateActivationCode(); var invitation = new SoftwareVaultInvitation() { EmployeeId = employee.Id, Status = SoftwareVaultInvitationStatus.Pending, CreatedAt = DateTime.UtcNow, ValidTo = validTo.Date, AcceptedAt = null, SoftwareVaultId = null, ActivationCode = activationCode }; var created = await _softwareVaultInvitationRepository.AddAsync(invitation); var activation = new SoftwareVaultActivation() { ServerAddress = server.Url, ActivationId = created.Id, ActivationCode = activationCode }; await _emailSenderService.SendSoftwareVaultInvitationAsync(employee, activation, validTo); }
public async Task <IEnumerable <CompetitionAreaViewModel> > GetCompetitions() { _logger.LogDebug("GetCompetitions"); var fetchCompetitions = await _footballDataService.GetCompetitions(); foreach (var fetchCompetition in fetchCompetitions) { CompetitionArea area = (await _areaRepository.ListAsync(a => a.Name.Equals(fetchCompetition.Area.Name, StringComparison.InvariantCultureIgnoreCase))).FirstOrDefault(); if (area == null) { area = new CompetitionArea { Name = fetchCompetition.Area.Name }; await _areaRepository.AddAsync(area); } Competition competition = (await _competitionRepository.ListAsync(c => c.Code.Equals(fetchCompetition.Code, StringComparison.InvariantCultureIgnoreCase))).FirstOrDefault(); if (competition == null) { competition = new Competition { Code = fetchCompetition.Code, Name = fetchCompetition.Name, AreaId = area.Id }; await _competitionRepository.AddAsync(competition); } } return(from competition in await _competitionRepository.ListAllAsync() group competition by new { competition.Area.Id, competition.Area.Name } into gArea select new CompetitionAreaViewModel { Name = gArea.Key.Name, Competitions = gArea.Select(c => new CompetitionViewModel { Id = c.Id, Name = c.Name }) }); }
public async Task <Template> CreateTmplateAsync(Template template) { if (template == null) { throw new ArgumentNullException(nameof(template)); } var accountExist = await _templateRepository .Query() .Where(x => x.Name == template.Name && x.Id != template.Id) .AnyAsync(); if (accountExist) { throw new AlreadyExistException("Template with current name already exists."); } template.Urls = Validation.VerifyUrls(template.Urls); return(await _templateRepository.AddAsync(template)); }
private async Task UpdateLocalizationsAsync( IEnumerable <PublisherLocalization> localizations, string publisherId = null) { foreach (var localization in localizations) { if (publisherId != default) { localization.PublisherEntityId = publisherId; } if (localization.Id == default) { await _publisherLocalizationRepository.AddAsync(localization); continue; } await _publisherLocalizationRepository.UpdateAsync(localization); } }
public async Task <Result <LivroModel> > AddLivroAsync(LivroModel livro) { var novoLivro = _mapper.Map <Livro>(livro); var validator = new LivroValidator(); var resultValidation = validator.Validate(novoLivro); if (!resultValidation.IsValid) { _logger.LogWarning("Novo livro não passou na validação. Erros: {0}", resultValidation.Errors.ToJson()); return(Result <LivroModel> .Invalid(resultValidation.AsErrors())); } var livroAdicionado = await _repositorio.AddAsync(novoLivro); Guard.Against.Null(livroAdicionado, "Novo livro"); _logger.LogInformation("Novo livro foi inserido com sucesso"); return(Result <LivroModel> .Success( _mapper.Map <LivroModel>(livroAdicionado))); }
public async Task <ReviewResponseModel> AddMovieReview(ReviewRequestModel reviewRequest) { Review review = new Review { UserId = reviewRequest.UserId, MovieId = reviewRequest.MovieId, ReviewText = reviewRequest.ReviewText, Rating = reviewRequest.Rating }; await _reviewRepository.AddAsync(review); var response = new ReviewResponseModel { UserId = review.UserId, MovieId = review.MovieId, ReviewText = review.ReviewText, Rating = review.Rating }; return(response); }
public async Task <Result <AutorModel> > AddAutorAsync(AutorModel autor) { var novoAutor = _mapper.Map <Autor>(autor); var validator = new AutorValidator(); var resultValidation = validator.Validate(novoAutor); if (!resultValidation.IsValid) { _logger.LogWarning("Novo autor não passou na validação. Erros: {0}", resultValidation.Errors.ToJson()); return(Result <AutorModel> .Invalid(resultValidation.AsErrors())); } var autorAdicionado = await _repositorio.AddAsync(novoAutor); Guard.Against.Null(autorAdicionado, "Novo Autor"); _logger.LogInformation("Novo autor foi inserido com sucesso"); return(Result <AutorModel> .Success( _mapper.Map <AutorModel>(autorAdicionado))); }
public static async Task SeedAsync(IAsyncRepository <Account> repository, string userId) { var accountGuid = Guid.Parse("{B0788D2F-8003-43C1-92A4-EDC76A7C5DDE}"); var firstAccount = new Account() { Id = accountGuid, Name = "Current", Number = "12345678", UserId = Guid.Parse(userId), Balance = 100m, CreatedOn = DateTime.Now, Currency = "GBP" }; var account = await repository.GetByIdAsync(accountGuid); if (account == null) { await repository.AddAsync(firstAccount); } }
public async Task AddWorkstationAsync(WorkstationInfoDto workstationInfoDto) { if (workstationInfoDto == null) { throw new ArgumentNullException(nameof(workstationInfoDto)); } var workstation = new Workstation() { Id = workstationInfoDto.Id, Name = workstationInfoDto.MachineName, Domain = workstationInfoDto.Domain, OS = workstationInfoDto.OsName, ClientVersion = workstationInfoDto.AppVersion, IP = workstationInfoDto.IP, LastSeen = DateTime.UtcNow, DepartmentId = null }; await _workstationRepository.AddAsync(workstation); }
public async Task MoveCriteriaDetails_To_Prod() { IEnumerable <CriteriaDetails> cds = null; using (IDbConnection devDb = new SqlConnection(ConfigurationManager.ConnectionStrings[_devAppConfigName].ConnectionString)) { IKernel kernel = new StandardKernel(new RepoTestsModule(devDb)); IAsyncRepository <CriteriaDetails> repo = kernel.Get <IAsyncRepository <CriteriaDetails> >(); cds = await repo.FindByName("Steward - Nashoba Valley Medical Center: Evicor Submit"); } using (IDbConnection devDb = new SqlConnection(ConfigurationManager.ConnectionStrings[_devAppConfigName].ConnectionString)) { IKernel kernel = new StandardKernel(new RepoTestsModule(devDb)); IAsyncRepository <CriteriaDetails> repo = kernel.Get <IAsyncRepository <CriteriaDetails> >(); var result = await repo.AddAsync(cds); } foreach (var cd in cds) { Console.WriteLine(cd); } }
public async Task <ProductDto> AddProductAsync(AddProductDto model) { Domain.Models.Product product = new Domain.Models.Product() { Name = model.Name, Description = model.Description, Price = model.Price, Category = model.Category }; await _productRepository.AddAsync(product); return(new ProductDto() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, Category = product.Category }); }