public async Task SeedAllAsync(CancellationToken cancellation) { #region SeedData var adminRole = new Role { Name = "Admin", Description = "System Admin Role", IsVital = true, }; if (!_roleRepository.GetAll().Any()) { await _roleRepository.AddAsync(adminRole); await _roleRepository.AddAsync(new Role { Name = "Manager", Description = "Mange User", IsVital = true, }); await _roleRepository.AddAsync(new Role { Name = "User", Description = "System Admin Role", IsVital = true, }); } if (!_userRepository.GetAll().Any()) { await _userRepository.AddAsync(new User { FirstName = "نیما", LastName = "نصرتی", Email = "*****@*****.**", Password = PasswordManagement.HashPass("nima1234!"), ActiveCode = Guid.NewGuid().ToString("N"), Mobile = "09107602786", IsEmailConfirm = true, IsMobileConfirm = true, RegisterDate = DateTime.Now, ModifiedDate = DateTime.Now.AddDays(2), Roles = new List <Role> { adminRole } }); } #endregion }
public async System.Threading.Tasks.Task Consume(ConsumeContext <ProjectUserAdded> context) { await projectUserRepository.AddAsync(new ProjectUser( NewId.NextGuid(), context.Message.ProjectId, context.Message.UserId)); }
public async Task <Result <ContractDto> > Handle(CreateContractCommand request, CancellationToken cancellationToken) { #region Validation var user = await _userRepository.GetAsync(x => x.IsDelete == false && x.Id == Guid.Parse(_currentUserService.UserId), cancellationToken); if (user is null) { return(Result <ContractDto> .Failed(new NotFoundObjectResult(new ApiMessage(ResponseMessage.UserNotFound)))); } var plan = await _planRepository.GetAsync(x => x.IsDeleted == false && x.Id == request.PlanId, cancellationToken); if (plan is null) { return(Result <ContractDto> .Failed(new NotFoundObjectResult(new ApiMessage(ResponseMessage.PlanNotFound)))); } #endregion var contract = _mapper.Map <Contract>(request); contract.EndContract = DateTime.Now.AddMonths(plan.Month); contract.User = user; contract.Plan = plan; await _contractRepository.AddAsync(contract); return(Result <ContractDto> .SuccessFul(_mapper.Map <ContractDto>(contract))); }
public async Task <Result> Handle(CreateAgentSettingCommand request, CancellationToken cancellationToken) { List <Employee> employees = new List <Employee>(); foreach (var id in request.EmployeeIds) { var employee = await _employeeRepository.GetAsync(id, cancellationToken); if (employee is null) { return(Result.Failed( new NotFoundObjectResult(new ApiMessage(ResponseMessage.EmployeeNotFound)))); } employees.Add(employee); } var agentSetting = _mapper.Map <Models.AgentSetting>(request); agentSetting.Employees = employees; await _agentSettingRepository.AddAsync(agentSetting); return(Result.SuccessFul()); }
public async Task Send <T>(T message, string messageId = null, string correlationId = null, string spanContext = null, object messageContext = null, IDictionary <string, object> headers = null) where T : class { if (!Enabled) { _logger.LogInformation("Outbox is disabled, outgoing messages won't be saved into the storage."); return; } var outboxMessage = new OutboxMessage { Id = string.IsNullOrWhiteSpace(messageId) ? Guid.NewGuid().ToString("N") : messageId, Headers = (Dictionary <string, object>)headers, MessageContextType = messageContext?.GetType().AssemblyQualifiedName, SerializedMessageContext = messageContext != null?JsonConvert.SerializeObject(messageContext) : "{}", MessageType = message?.GetType().AssemblyQualifiedName, SerializedMessage = message != null?JsonConvert.SerializeObject(message) : "{}", CorrelationId = correlationId, SpanContext = spanContext, SentAt = DateTime.UtcNow }; try { await _outboxRepository.AddAsync(outboxMessage); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task HandleAsync(CreateOrder command) { var exists = await _repository.ExistsAsync(o => o.Id == command.OrderId); if (exists) { throw new InvalidOperationException($"Order with given id: {command.OrderId} already exists!"); } _logger.LogInformation($"Fetching a price for order with id: {command.OrderId}..."); var pricingDto = await _pricingServiceClient.GetAsync(command.OrderId); if (pricingDto is null) { throw new InvalidOperationException($"Pricing was not found for order: {command.OrderId}"); } _logger.LogInformation($"Order with id: {command.OrderId} will cost: {pricingDto.TotalAmount}$."); var order = new Order(command.OrderId, command.CustomerId, pricingDto.TotalAmount); await _repository.AddAsync(order); _logger.LogInformation($"Created an order with id: {command.OrderId}, customer: {command.CustomerId}."); var spanContext = _tracer.ActiveSpan.Context.ToString(); await _publisher.PublishAsync(new OrderCreated(order.Id), spanContext : spanContext); }
public async Task <Result <UserDto> > Handle(CreateUserCommand request, CancellationToken cancellationToken) { var currentUser = await _userRepository.GetAsync(u => u.Id == Guid.Parse(_currentUserService.UserId), cancellationToken); if (currentUser.Organizations is null) { return(Result <UserDto> .Failed( new BadRequestObjectResult(new ApiMessage(ResponseMessage.NeedOrganization)))); } var user = _mapper.Map <User>(request); var role = await _roleRepository.GetAsync(x => x.Name == Role.User, cancellationToken); user.Roles = new List <Role> { role }; user.Organizations = new List <Models.Organization> { currentUser.Organizations.FirstOrDefault() }; await _userRepository.AddAsync(user); return(Result <UserDto> .SuccessFul(_mapper.Map <UserDto>(user))); }
public async System.Threading.Tasks.Task Consume(ConsumeContext <CreateTask> context) { try { var taskCreated = new { context.Message.Id, context.Message.ProjectId, context.Message.CreatorUserId, context.Message.AssignedToUserId, context.Message.State, context.Message.Name, context.Message.Description, context.Message.Priority, context.Message.DueDateUtc, context.Message.DependsOnTaskId }; await eventRepository.AddAsync(new Event(NewId.NextGuid(), typeof(TaskCreated).FullName, JsonConvert.SerializeObject(taskCreated))); await context.Publish <TaskCreated>(taskCreated); logger.LogInformation($"task created with id: {context.Message.Id}"); } catch (Exception ex) { logger.LogError(ex.ToString()); } }
public async Task AddAsync(User user) { _sql.Users.Add(user); await _sql.SaveChangesAsync(); await _mongoRepository.AddAsync(user); }
public async Task HandleAsync(SignUp command) { _validator.Validate(command).ThrowIfInvalid(); var alreadyExists = await _repository.ExistsAsync(u => u.Username == command.Username || u.Email == command.Email); if (alreadyExists) { throw new UserAlreadyExistsException(command.Username, command.Email); } var salt = _passwordService.CreateSalt(); var passwordHash = _passwordService.HashPassword(command.Password, salt); var user = new IdentityDocument { Id = command.Id, Username = command.Username, FullName = command.FullName, Email = command.Email, PhoneNumber = command.PhoneNumber, Password = passwordHash, Salt = salt, UpdatedAt = DateTime.UtcNow }; await _repository.AddAsync(user); }
public UserEntity AddUser(SignupUserContract user, out AuthInfo authInfo) { if (!string.IsNullOrEmpty(user.Email.Trim()) && EmailExistsAsync(user.Email).Result) { authInfo = null; return(null); } var newId = Guid.NewGuid(); var expiration = DateTime.UtcNow.AddDays(ExpirationDays); var bearerToken = TokenGenerator.GenerateToken(newId, _configuration["Security:SecretKey"], expiration, null, _configuration["Security:EncryptionKey"]); var passwordHash = CredentialUtility.HashPassword(user.Password); var addUser = new UserEntity { UserId = newId, Email = user.Email, EmailCandidate = user.Email, EmailConfirmed = false, PasswordHash = passwordHash, BearerToken = bearerToken, DateJoined = DateTimeOffset.UtcNow }; authInfo = new AuthInfo { Token = bearerToken, Expiration = expiration }; _userRepository.AddAsync(addUser).Wait(); return(addUser); }
public async Task <Result <string> > AddAsync <TRequest>(TRequest request, CancellationToken cancellationToken) where TRequest : BaseRequest { if (request == null) { return(new Result <string>(string.Empty, HttpStatusCode.BadRequest, problemTittle: "Object is null")); } TEntity objEntity; try { objEntity = _mapper.Map <TRequest, TEntity>(request); } catch (AutoMapperMappingException ex) { return(new Result <string>(string.Empty, HttpStatusCode.BadRequest, problemDetail: ex.InnerException.Message)); } if (!objEntity.IsValid(EValidationStage.Insert)) { return(new Result <string>(string.Empty, HttpStatusCode.BadRequest, errors: objEntity.Errors)); } try { objEntity = await _repositoryBase.AddAsync(objEntity, cancellationToken); } catch (Exception) { return(new Result <string>(string.Empty, HttpStatusCode.InternalServerError, problemDetail: $"Error on create object {typeof(TEntity).Name}.")); } return(new Result <string>(objEntity.Id, HttpStatusCode.Created)); }
public async Task <ServiceResult> AddBasketProduct(ProductBasket productBasket) { try { var serviceResult = new ServiceResult(); var stockDmo = await _stockRepository.GetByIdAsync(x => x.ProductId == productBasket.ProductId); if (productBasket.ProductPiece > stockDmo.Piece) { throw new System.Exception("Ürün stokta bulunmamaktadır."); } if (productBasket.ProductPiece > stockDmo.MaxPiece) { throw new System.Exception("Maksimum Ürün limitini aştınız."); } var filterBasketList = await _mongoRepository.GetAllAsync(x => x.Product.Id, productBasket.ProductId); var basketProductSum = _basketRepository.Sum(filterBasketList); if (basketProductSum + productBasket.ProductPiece > stockDmo.MaxPiece || basketProductSum + productBasket.ProductPiece > stockDmo.Piece) { throw new Exception("Sepete Stokta bulunandan fazla veya Maksimum Ekleme limitini aştınız."); } var productDmo = await _productRepository.GetByIdAsync(productBasket.ProductId); var basket = new Basket { ProductPiece = productBasket.ProductPiece, Product = new Product { Id = productDmo.Id, Name = productDmo.Name, Price = productDmo.Price }, UserIpAdress = AuthUser.Current.RequestIp }; await _mongoRepository.AddAsync(basket); var data = JsonConvert.SerializeObject(basket); await _redisRepository.Add(AuthUser.Current.RequestIp, data); return(new ServiceResult { StatusCode = HttpStatusCode.OK, Message = "Sepete ekleme başarılı" }); } catch (Exception ex) { throw new System.Exception($"{ex.Message}"); } }
public async Task <Result <PlanDto> > Handle(CreatePlanCommand request, CancellationToken cancellationToken) { var plan = _mapper.Map <Plan>(request); await _planRepository.AddAsync(plan); return(Result <PlanDto> .SuccessFul(_mapper.Map <PlanDto>(plan))); }
public async Task <CountryDto> CreateAsync(CountryRequestModel requestModel) { await CheckCountryExist(requestModel); Country createdCountry = await _countryRepository.AddAsync(_mapper.Map <Country>(requestModel)); return(_mapper.Map <CountryDto>(createdCountry)); }
public async Task <Result <ToolCategoryDto> > Handle(CreateCategoryCommand request, CancellationToken cancellationToken) { var toolCategory = _mapper.Map <ToolsCategory>(request); await _toolCategoryRepository.AddAsync(toolCategory); return(Result <ToolCategoryDto> .SuccessFul(_mapper.Map <ToolCategoryDto>(toolCategory))); }
public async Task HandleAsync(AddUserCommand command) { var sticker = new User( command.Id, command.Email, command.OauthSubject, command.OauthIssuer); await _repository.AddAsync(sticker); }
public async Task AddAsync(CourseModule courseModule, Guid courseId) { await _repository.AddAsync(courseModule.AsDocument()); var course = await _courseRepository.GetAsync(courseId); course.Modules = course.Modules.Append <Guid>(courseModule.Id); await _courseRepository.UpdateAsync(course); }
public async Task AddAsync(CourseEpisode episode, Guid moduleId) { var module = await _moduleRepository.GetAsync(moduleId); module.Episodes.ToList().Add(episode.Id); await _repository.AddAsync(episode.AsDocument()); await _moduleRepository.UpdateAsync(module); }
public async Task AssignUserToRolesAsync(Guid userId, IList <Guid> RoleIds) { foreach (var roleId in RoleIds) { var userRoles = new UserRoles(userId, roleId); await _userRolerepository.AddAsync(userRoles); } }
public Task HandleAsync(CreateCategory command, ICorrelationContext context) { Category category = new Category(command.Id, command.Name, command.Description); _mongoRepository.AddAsync(category); return(_busPublisher.PublishAsync( new CategoryCreated(command.Id, command.Name, command.Description), context)); }
private async Task AddRequestsAsync(IEnumerable <RequestEntity> requestEntitiesToUpdate) { var savingList = new List <Task>(); foreach (var requestEntity in requestEntitiesToUpdate) { savingList.Add(_requestEntityRepository.AddAsync(requestEntity)); } await Task.WhenAll(savingList); }
public async Task HandleAsync(AddStickerCommand command) { var sticker = new Sticker(command); await _repository.AddAsync(sticker); var stickerMovedEvent = new StickerCreatedEvent( "testId", //todo db boardId unhardcode sticker.Id); await _publisher.Publish(stickerMovedEvent, PublishStrategy.ParallelNoWait); }
public async Task <Result <AuthenticationResult> > Generate(User user, CancellationToken cancellationToken) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("Id", user.Id.ToString()), new Claim("fullName", $"{user.FirstName} {user.LastName}"), new Claim("RoleName", user.Roles.FirstOrDefault() !.Name) }; claims.AddRange(user.Roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role.Name) )); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(14), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), Audience = _jwtSettings.ValidAudience, Issuer = _jwtSettings.ValidIssuer }; var token = tokenHandler.CreateToken(tokenDescriptor); var userToken = new UserToken { Token = tokenHandler.WriteToken(token), CreateDate = DateTime.UtcNow, ExpiredDate = DateTime.UtcNow.AddDays(14), Device = _requestMeta.Device, Os = _requestMeta.Os, Ip = _requestMeta.Ip, UserAgent = _requestMeta.UserAgent, UserId = user.Id }; await _userTokenRepository.AddAsync(userToken); return(Result <AuthenticationResult> .SuccessFul(new AuthenticationResult { AccessToken = userToken.Token, IsSuccess = true, RoleName = user.Roles.FirstOrDefault()?.Name })); }
public async Task <ApiBaseResponse> CommentPostAsync(CommentRequestModel comment) { var userId = Guid.Parse(_httpContextAccessor?.HttpContext?.User?.Identity?.Name); BlogStatsItem statsItem = new BlogStatsItem(); if (await _blogStatsItemRepository.ExistsAsync(c => c.PostId == comment.PostId)) { statsItem = await _blogStatsItemRepository.GetAsync(c => c.PostId == comment.PostId); statsItem.CommentCount = statsItem.CommentCount + 1; statsItem.Comments.Add(new Comment { Id = Guid.NewGuid(), UserId = userId, CommentText = comment.Comment, CreateDate = DateTime.UtcNow }); await _blogStatsItemRepository.UpdateAsync(statsItem); } else { statsItem = new BlogStatsItem { Id = Guid.NewGuid(), PostId = comment.PostId, CommentCount = 1, FavouriteCount = 0 }; statsItem.Comments.Add(new Comment { Id = Guid.NewGuid(), UserId = userId, CommentText = comment.Comment, CreateDate = DateTime.UtcNow }); await _blogStatsItemRepository.AddAsync(statsItem); } return(new ApiBaseResponse(HttpStatusCode.OK, ApplicationStatusCode.Success, null, "Succesfully commented.")); }
public async System.Threading.Tasks.Task Consume(ConsumeContext <ProjectCreated> context) { await projectRepository.AddAsync(new Project( context.Message.Id, context.Message.CreatorUserId, context.Message.Name, context.Message.Description, context.Message.IconClass, context.Message.IconColor, context.Message.IconBackgroundColor, context.Message.Priority, context.Message.Tags.Select(x => new Tag(x.Class, x.Key, x.Value)))); }
public async Task <Result <TicketDto> > Handle(CreateTicketCommand request, CancellationToken cancellationToken) { var ticket = _mapper.Map <Ticket>(request); var user = await _userRepository.GetAsync(x => x.IsDelete == false && x.Id == Guid.Parse(_currentUserService.UserId), cancellationToken); ticket.User = user; await _ticketRepository.AddAsync(ticket); return(Result <TicketDto> .SuccessFul(_mapper.Map <TicketDto>(ticket))); }
public async Task CreateAsync(CinemaDto dto) { var alreadyExists = await _repository.ExistsAsync(c => c.Id == dto.Id); if (alreadyExists) { throw new CinemaAlreadyExistsException(dto.Id); } var events = dto.Halls.Select(h => new HallAdded(dto.Id, h.Id)); await _repository.AddAsync(dto.AsDocument()); await _broker.PublishAsync(events); }
public Task HandleAsync(CreateCustomer command, ICorrelationContext context) { Customer user = new Customer(command.Id, command.FullName, command.Email, command.Phone, command.Address); mongoRepository.AddAsync(user); return(busPublisher.PublishAsync( new CustomerCreated( command.Id, command.FullName, command.Email, command.Phone, command.Address ), context)); }
public async Task <ActionResult> OrderShip(CreateOrderInput input) { Order order = new Order { OrderDesc = input.OrderDesc, OrderNo = input.OrderNo, Amount = input.Amount, State = input.State }; await _mongoRepository.AddAsync(order); return(Ok()); }