public async Task <IActionResult> Create([FromBody] User user) { user.Password = _securityService.GetMD5HashData(user.Password); user.Language = user.Customer.Address.Country.Language; user.Customer.Address.Country = null; var newUser = await _repository.AddAsync(user); if (newUser.Id > 0) { var token = Guid.NewGuid().ToString(); var activation = await _userActivationRepository.AddAsync(new UserActivation { IsUsed = false, UserId = newUser.Id, Token = token, }); if (activation.Id > 0) { await _userEmailFactory.SendActivationEmail(user, activation); } } return(Redirect($"{_configuration["Web:Url"]}/successfully-registered")); }
public async Task Add_SingleItem_ShouldFind(IEntityRepository <GenericEntity <string> > repository) { // Act Entity entity = await repository.AddAsync(new GenericEntity <string>("The cake is a lie")); await repository.AddAsync(new GenericEntity <string>("Cupcakes and chocolate")); var match = await repository.FindAsync(entity.Id); // Assert match.Should().NotBeNull("because we added an entity before"); }
public async Task HandleAsync(CreateShop command) { var shopCategory = await _repository.LoadAsync <ShopCategory>(command.ShopCategoryId); var manager = await _repository.LoadAsync <User>(command.ManagerId); if (manager.Shop != null) { throw new DomainException(UserIsAlreadyManager(manager)); } manager.IsShopManager = true; var shop = new Shop(command.Id, command.Name) { ShopCategory = shopCategory, Manager = manager, IsEntryPoint = command.IsEntryPoint, IsExitPoint = command.IsExitPoint }; if (shopCategory.Shops.Count == 0) { shop.IsDefaultForCategory = true; } shopCategory.Shops.Add(shop); await _repository.AddAsync(shop); await _eventTransmitter.BroadcastAsync(new DomainEvent <User>(manager, Trigger.Changed, command.InitiatorId)); await _eventTransmitter.BroadcastAsync(new DomainEvent <Shop>(shop, Trigger.Added, command.InitiatorId)); }
public async Task <Lesson> AddLessonRequestAsync(int offerId, IEnumerable <int> slotIds, int userId) { using (var transaction = _transactionFactory.Begin()) { var offer = await _repository.GetAsync <Offer>(offerId); var slots = new List <CalendarSlot>(); foreach (var id in slotIds) { var entity = await _repository.GetAsync <CalendarSlot>(id); entity.Status = SlotStatus.BookRequest; slots.Add(entity); } var user = await _repository.GetAsync <User>(userId); var lesson = new Lesson { Offer = offer, Status = LessonStatus.Requested, Slots = slots, User = user, StartAt = slots.Select(s => s.StartAt).Min() }; await _repository.AddAsync(lesson); transaction.Save(); return(lesson); } }
public async Task FindAll_AddedEntities_ReturnsCorrectCount(IEntityRepository <GenericEntity <string> > repository) { // Arrange var entityIceCream = GenericEntityBuilder.Create("Ice Cream"); var entityChocoCake = GenericEntityBuilder.Create("Choco Cake"); // Act await repository.AddAsync(entityIceCream); await repository.AddAsync(entityChocoCake); var list = (await repository.FindAllAsync()).ToList(); // Assert list.Should().HaveCount(2, "because we added two items"); }
public async Task <Schedule> CreateScheduleAsync(string title, DateTimeOffset startDate) { var endDate = startDate.AddDays(DaysOnDisplay).AddMinutes(-1); var slots = (await _repository.GetAllAsync <CalendarSlot>()) .Where(slot => slot.StartAt >= startDate && slot.StartAt < endDate).ToList(); var schedule = new Schedule { Title = title, Days = slots.GroupBy(s => s.StartAt.DayOfWeek).Select(g => new ScheduleDay { DayOfWeek = g.Key, Slots = g.Select(s => new ScheduleSlot { StartTime = s.StartAt.TimeOfDay }).ToList() }).ToList() }; using (var transaction = _transactionFactory.Begin()) { await _repository.AddAsync(schedule); transaction.Save(); } return(schedule); }
public async Task HandleAsync(AddBillOfMaterial command) { var article = await _repository.GetAsync <Article>(command.ArticleId); var input = (await _repository.LoadSomeAsync <Article>(command.Input.Select(i => i.articleId))) .Select(a => new InventoryItem(a, command.Input.Single(i => i.articleId == a.Id).amount)).ToHashSet(); var bom = article.BillsOfMaterial.FirstOrDefault(b => b.Input.SetEquals(input)); if (bom != null) { throw new DomainException(IdenticalBomExists(bom)); } var newBom = new BillOfMaterial(command.Id, command.Name) { Article = article, Input = input, Output = command.Output, Primary = false }; await _repository.AddAsync(newBom); article.BillsOfMaterial.Add(newBom); await _eventTransmitter.BroadcastAsync(new DomainEvent <BillOfMaterial>(newBom, Trigger.Added, command.InitiatorId)); }
public async Task HandleAsync(CreateMaterialRequest command) { var supplier = await _repository.GetAsync <Supplier>(command.SupplierId); var requestedItems = new List <InventoryItem>(); foreach (var(articleId, amount) in command.Items) { if (supplier.SuppliableArticles.All(a => a.Id != articleId)) { throw new DomainException(RequestingUnregisteredArticle(supplier, articleId)); } var article = await _repository.LoadAsync <Article>(articleId); requestedItems.Add(new InventoryItem(article, amount)); } var name = $"To {supplier.Name} from {DateTimeOffset.Now}"; var request = new MaterialRequest(command.Id, name) { Supplier = supplier, Status = MaterialRequestStatus.Submitted, ItemsRequested = requestedItems, CreatedAt = DateTimeOffset.Now }; supplier.MaterialRequests.Add(request); await _repository.AddAsync(request); await _eventTransmitter.BroadcastAsync(new DomainEvent <MaterialRequest>(request, Trigger.Added, command.InitiatorId)); }
public async Task HandleAsync(RegisterCustomer command) { var contact = new Contact(Guid.NewGuid(), $"{command.PrimaryContactFirstName} {command.PrimaryContactLastName} of {command.Name}") { FirstName = command.PrimaryContactFirstName, LastName = command.PrimaryContactLastName, PhoneNumber = command.PrimaryContactPhone, Email = command.PrimaryContactEmail, Primary = true }; var address = new Address(Guid.NewGuid(), $"{command.Name} shipping address.") { AddressLine1 = command.ShippingAddressLine1, AddressLine2 = command.ShippingAddressLine2, City = command.ShippingAddressCity, Province = command.ShippingAddressProvince, Country = command.ShippingAddressCountry, PostalCode = command.ShippingAddressPostalCode }; var customer = new Customer(command.Id, command.Name) { CustomerType = command.Type, Contacts = contact.CollectToHashSet(), ShippingAddress = address }; await _repository.AddAsync(customer); await _eventTransmitter.BroadcastAsync(new DomainEvent <Customer>(customer, Trigger.Added, command.InitiatorId)); }
public async Task <string> RegisterAsync(string email, string password, string secret, string firstName, string lastName) { var users = await _repository.GetSomeAsync <User>(predicate : entity => entity.Email == email); if (users.Any()) { return(null); } var user = new User { FirstName = firstName, LastName = lastName, Email = email, Password = Encrypt(password, secret), TimeZone = "GMT", //ToDo:: time zone RegisteredAt = DateTimeOffset.Now }; using (var transaction = _transactionFactory.Begin()) { await _repository.AddAsync(user); transaction.Save(); } return(GenerateToken(user, secret)); }
public async Task Consume(ConsumeContext <UserRegisteredEvent> context) { await _userEntityRepository.AddAsync(new ChatUser { Id = context.Message.Id, DisplayName = context.Message.DisplayName }); }
private async Task <Payment> AddPaymentTransaction(CardDetails cardDetails, string gateway) { var paymentTransction = _mapper.Map <Payment>(cardDetails); paymentTransction.Status = "pending"; paymentTransction.GateWayType = gateway; return(await _entityPaymentRepository.AddAsync(paymentTransction)); }
public async Task <TEntity> AddAsync(TEntity entity) { await _repository.AddAsync(entity); await _unitOfWork.CommitAsync(); return(entity); }
public async Task <IActionResult> Create([FromBody] CreateCategoryRequest request) { var item = _mapper.Map <Category>(request); await _entityRepository.AddAsync(item); await _unitOfWork.CompleteAsync(); return(CreatedAtRoute("", new { id = item.Id })); }
public async Task HandleAsync(CreateEvent command) { await createEventValidator.ValidateAsync(command); var @event = eventBuilder.BuildWith(command); command.CreatedId = @event.Id; await eventRepository.AddAsync(@event); }
public async Task HandleAsync(RegisterToEvent command) { await registerToEventValidator.ValidateAsync(command); var registration = registrationBuilder.BuildWith(command); command.CreatedId = registration.Id; await registrationRepository.AddAsync(registration); }
public async Task HandleAsync(CreateOrder command) { var customer = await _repository.GetAsync <Customer>(command.CustomerId); if (customer == null) { throw new ArgumentNullException(nameof(customer)); } //load items var itemsOrdered = new HashSet <InventoryItem>(); foreach (var(articleId, amount) in command.Items) { var article = await _repository.LoadAsync <Article>(articleId); itemsOrdered.Add(new InventoryItem(article, amount)); } //check stocks availability foreach (var item in itemsOrdered) { var allocatable = await _inventoryService.CalculateAllocatableAmount(item.Article); if (item.Amount > allocatable) { throw new DomainException(InsufficientInventory(item.Article, item.Amount, allocatable)); } } //check time var eta = await _inventoryService.CalculateTimeOfCompletion(itemsOrdered); if (eta > command.ShipmentDeadline) { throw new DomainException(InsufficientTime(command.Name, command.ShipmentDeadline, eta)); } //Create order var order = new Order(command.Id, command.Name) { Status = OrderStatus.New, ItemsOrdered = itemsOrdered, ItemsProduced = itemsOrdered.Select(i => InventoryItem.Empty(i.Article)).ToHashSet(), ShipmentDeadline = command.ShipmentDeadline, Customer = customer, Type = command.OrderType }; //Save order and reference in db await _repository.AddAsync(order); customer.Orders.Add(order); await _eventTransmitter.BroadcastAsync(new DomainEvent <Order>(order, Trigger.Added, command.InitiatorId)); }
public async Task <LessonType> CreateLessonTypeAsync(LessonType entity) { using (var transaction = _transactionFactory.Begin()) { entity.OnSale = entity.Offers.Any(o => o.OnSale); await _repository.AddAsync(entity); transaction.Save(); } return(entity); }
public async Task <ActionResult> Add(RolesModel roles) { //add to storage //var entity = roles.Map<RolesModel, Roles>(); var entity = DomainMaps.Mapper.Map <Roles>(roles); var res = await _rolesRepository.AddAsync(entity); return(new ActionResult() { Success = (res != null ? true : false) }); }
public async Task HandleAsync(CreateSubOrders command) { var order = await _repository.GetAsync <Order>(command.OrderId); var inventory = _orderService.CalculateInventoryInput(order).ToList(); foreach (var item in inventory) { var spare = await _inventoryRepo.FindSpareInventoryAsync(item.Article); if (spare > 0) { item.Amount -= spare; } } var subOrders = new List <Order>(); foreach (var item in order.ItemsOrdered) { await CreateSubOrder(item, order); } async Task CreateSubOrder(InventoryItem item, Order parent) { var input = inventory.Of(item.Article); if (!(input.Amount > 0) || input.Article.ProductionShopCategory == null) { return; } var subOrder = _orderService.CreateSubOrder(input, parent); subOrders.Add(subOrder); if (item.Article.PrimaryBillOfMaterial == null) { return; } foreach (var subItem in item.Article.PrimaryBillOfMaterial.Input) { await CreateSubOrder(subItem, subOrder); } await _repository.AddAsync(subOrder); } foreach (var subOrder in subOrders) { await _eventTransmitter.BroadcastAsync(new DomainEvent <Order>(subOrder, Trigger.Added, command.InitiatorId)); } }
public async Task Remove_ExistingItem_Removes(IEntityRepository <GenericEntity <string> > repository) { // Act var entity = await repository.AddAsync(new GenericEntity <string>("Cookies")); await repository.RemoveAsync(entity); var match = await repository.FindAsync(entity.Id); // Assert match.Should().BeNull("because it was removed from the repository"); }
public async Task <IEnumerable <CalendarSlot> > CreateVacantSlotsAsync(IEnumerable <CalendarSlot> entities) { using (var transaction = _transactionFactory.Begin()) { foreach (var entity in entities) { await _repository.AddAsync(entity); } transaction.Save(); } return(entities); }
public async Task AddToCategoryAsync(CategoryBlogDto categoryBlogDto) { var control = await _categoryBlogService.GetAsync(I => I.CategoryId == categoryBlogDto.CategoryId && I.BlogId == categoryBlogDto.ArticleId); if (control == null) { await _categoryBlogService.AddAsync(new CategoryBlog { BlogId = categoryBlogDto.ArticleId, CategoryId = categoryBlogDto.CategoryId }); } }
public async Task HandleAsync(CreateUser command) { var user = new User(command.Id, command.Name) { FirstName = command.FirstName, LastName = command.LastName, //UserType = command.UserType, Email = command.Email }; await _repository.AddAsync(user); await _eventTransmitter.BroadcastAsync(new DomainEvent <User>(user, Trigger.Added, command.InitiatorId)); }
public async Task <IActionResult> Create([FromBody] CreateProductRequest request) { if (await _entityRepository.HasMatchingAsync(x => x.Name == request.Name)) { throw new UseCaseException("Name Already Exists"); } var item = _mapper.Map <Product>(request); await _entityRepository.AddAsync(item); await _unitOfWork.CompleteAsync(); return(Ok(item)); }
public async Task RemoveById_ExistingItem_Remove(IEntityRepository <GenericEntity <string> > repository) { // Act var domainModel = new GenericEntity <string>("Cookies"); var entity = await repository.AddAsync(domainModel); var id = entity.Id; await repository.RemoveAsync(id); var match = await repository.FindAsync(id); // Assert match.Should().BeNull("because we removed it by its ID"); }
public async Task Add_Entity_PersistsId(IEntityRepository <GenericEntity <string> > repository) { // Arrange var entity = GenericEntityBuilder.Create("Nuts"); entity.Id = "123"; // Act var addedEntity = await repository.AddAsync(entity); // Assert entity.Id .Should() .Be(addedEntity.Id, "because we added it before with this ID"); }
public async Task <IActionResult> Create([FromBody] CreateOrderRequest request) { var item = _mapper.Map <Order>(request); item.MakeOrderCreated(); foreach (var ite in item.OrderItems) { var product = await _entityProductRepository.FindAsync(ite.ProductId); ite.SetProductName(product.Name); ite.SetUnitPrice(product.Price); ite.AddTotalPrice(); } await _entityRepository.AddAsync(item); await _unitOfWork.CompleteAsync(); return(Ok(item)); }
public async Task FindByLinq_ExistingItem_Successfully(IEntityRepository <GenericEntity <KeyValuePair <string, string> > > repository) { // Arrange const string expectedKey = "*****@*****.**"; await repository.AddAsync( new GenericEntity <KeyValuePair <string, string> >( new KeyValuePair <string, string>(expectedKey, "unidash"))); // Act var entity = (await repository.FindByPredicateAsync(x => x.Data.Key == expectedKey)) .First(); // Assert entity.Data.Key .Should() .Be(expectedKey, "because it exists in the repository with the same key"); }
public async Task <IActionResult> Handle(PostChannelRequest request, CancellationToken cancellationToken) { var userId = _currentUserAccessor.GetUserId(); request.Participants.Add(userId); var channel = new ChatChannel { Title = request.Title, ParticipantUserIds = request.Participants, CreatorUserId = userId }; // TODO: Check whether all participants even exist in DB await _channelEntityRepository.AddAsync(channel); return(new OkResult()); }