public async Task <IResponse <ITasksGroup> > SaveAsync(string groupName)
        {
            try
            {
                ITasksGroup tasksGroup = mTaskGroupFactory.CreateGroup(groupName);

                if (!mTasksGroupNameValidator.IsNameValid(tasksGroup.Name))
                {
                    return(new FailResponse <ITasksGroup>(
                               $"Group name '{tasksGroup.Name}' exceeds the maximal group name length: {NameLengths.MaximalGroupNameLength}"));
                }

                if (!await mTasksGroupRepository.AddAsync(tasksGroup).ConfigureAwait(false))
                {
                    return(new FailResponse <ITasksGroup>(
                               $"Group name '{tasksGroup.Name}' already exist"));
                }

                return(new SuccessResponse <ITasksGroup>(tasksGroup));
            }
            catch (Exception ex)
            {
                return(new FailResponse <ITasksGroup>($"An error occurred when saving tasks group name {groupName}: {ex.Message}"));
            }
        }
        public async Task <User> RegisterIfNotExists(Update update)
        {
            var user = (await _usersRepository.FindAsync(x => x.Id == update.Message.From.Id))
                       .FirstOrDefault();

            if (user != null)
            {
                return(user);
            }

            var newUser = new User
            {
                LastName   = update.Message.From.LastName,
                Id         = update.Message.From.Id,
                FirstName  = update.Message.From.FirstName,
                Username   = update.Message.From.Username,
                ChatId     = update.Message.Chat.Id,
                UserStatus = UserStatus.NewUser,
                IsWinner   = false
            };

            _logger.LogDebug($"New user registered: {newUser.FirstName} {newUser.LastName}");
            await _usersRepository.AddAsync(newUser);

            return(newUser);
        }
Beispiel #3
0
        public virtual IActionResult Create([FromBody] CreateMetricRequest request)
        {
            _logger.LogInformation(string.Format("params: time {0}; value {1}", request.Time, request.Value));
            _repository.AddAsync(_mapper.Map <T>(request));

            return(Ok());
        }
Beispiel #4
0
        /// <summary>
        /// Создание задачи
        /// </summary>
        /// <param name="objectiveModel">Модель задачи</param>
        /// <returns>Новый элемент меню</returns>
        public async Task <MenuItemModel> Create(ObjectiveModel objectiveModel)
        {
            var entity = _mapper.Map <ObjectiveEntity>(objectiveModel);

            if (objectiveModel.ParentId == null || objectiveModel.ParentId == Guid.Empty)
            {
                await _dbRepository.AddAsync(entity);
            }
            else
            {
                var parentEntity = _dbRepository
                                   .Get <ObjectiveEntity>(x => x.Id == objectiveModel.ParentId)
                                   .Include(x => x.SubObjectives).FirstOrDefault();

                if (parentEntity == null)
                {
                    return(null);
                }

                parentEntity.SubObjectives.Add(entity);
            }
            await _dbRepository.SaveChangesAsync();

            var menuItem = _mapper.Map <MenuItemModel>(entity);

            return(menuItem);
        }
        public async Task SaveTaskAsync_InvalidTaskName_FailResponseReturnedAndSaveNotPerformed()
        {
            const string groupName = "groupName";

            IWorkTask workTask = A.Fake <IWorkTask>();

            workTask.GroupName   = groupName;
            workTask.Description = mInvalidTaskName;
            OperationResult <IWorkTask> createTaskResult = new OperationResult <IWorkTask>(true, workTask);

            ITasksGroup tasksGroup = A.Fake <ITasksGroup>();

            tasksGroup.SetGroupName(groupName);

            A.CallTo(() => tasksGroup.CreateTask(A <string> .Ignored, A <string> .Ignored)).Returns(createTaskResult);

            IDbRepository <ITasksGroup> dbRepository = A.Fake <IDbRepository <ITasksGroup> >();

            A.CallTo(() => dbRepository.ListAsync()).Returns(new List <ITasksGroup> {
                tasksGroup
            });

            TasksGroupService tasksGroupService =
                new TasksGroupService(dbRepository, mTasksGroupFactory, NullLogger <TasksGroupService> .Instance);

            IResponse <IWorkTask> response =
                await tasksGroupService.SaveTaskAsync(workTask.GroupName, workTask.Description).ConfigureAwait(false);

            Assert.False(response.IsSuccess);
            Assert.Null(response.ResponseObject);
            A.CallTo(() => dbRepository.AddAsync(A <ITasksGroup> .Ignored)).MustNotHaveHappened();
        }
        public async Task <Guid> Create(ShoppingListModel shoppingListModel)
        {
            var shoppingListEntity = _mapper.Map <ShoppingListEntity>(shoppingListModel);
            await _dbRepository.AddAsync(shoppingListEntity);

            await _dbRepository.SaveChangesAsync();

            return(shoppingListEntity.Id);
        }
Beispiel #7
0
 public async Task AddReviewAsync(string bookId, AddReviewResource resource)
 {
     var review = new BookReview
     {
         BookId        = bookId,
         ReviewComment = resource.ReviewComment,
         ReviewedBy    = _tenantContext.User
     };
     await _dbRepo.AddAsync(review);
 }
Beispiel #8
0
        public async Task AddAsync(ClientCreateModel model)
        {
            var client = new Client
            {
                Id   = Guid.NewGuid(),
                Name = model.Name
            };

            await _repository.AddAsync(client);
        }
Beispiel #9
0
        public async Task AddReviewAsync(string bookId)
        {
            var history = new BookHistory
            {
                BookId   = bookId,
                ReadyBy  = _tenantContext.User,
                ReadDate = DateTime.UtcNow
            };

            await _dbRepo.AddAsync(history);
        }
        public async Task <ProductModel> Create(ProductModel productModel)
        {
            var productEntity = _mapper.Map <ProductEntity>(productModel);
            var result        = await _dbRepository.AddAsync(productEntity);

            await _dbRepository.SaveChangesAsync();

            var productResult = _mapper.Map <ProductModel>(result);

            return(productResult);
        }
        public async Task SaveAsync_ValidTasksGroupToAdd_SavePerformed()
        {
            ITasksGroup tasksGroup = mTasksGroupFactory.CreateGroup("ValidGroupName");

            IDbRepository <ITasksGroup> dbRepository      = A.Fake <IDbRepository <ITasksGroup> >();
            TasksGroupService           tasksGroupService =
                new TasksGroupService(dbRepository, mTasksGroupFactory, NullLogger <TasksGroupService> .Instance);

            await tasksGroupService.SaveAsync(tasksGroup.Name).ConfigureAwait(false);

            A.CallTo(() => dbRepository.AddAsync(A <ITasksGroup> .Ignored)).MustHaveHappenedOnceExactly();
        }
Beispiel #12
0
        /// <summary>
        /// Создать новый проект
        /// </summary>
        /// <param name="projectDto">Объект нового проекта (DTO)</param>
        /// <returns>Созданные проект</returns>
        public async Task <Project> CreateNewProject(ProjectDto projectDto)
        {
            var project = new Project
            {
                Title          = projectDto.Title,
                Description    = projectDto.Description,
                AuthorId       = _currentUser.Id,
                AuthorUsername = _currentUser.Username
            };

            await _dbRepository.AddAsync(project);

            return(project);
        }
        public async Task <TodoComment> PostComment(TodoCommentDto todoCommentDto)
        {
            var comment = new TodoComment
            {
                AuthorName   = _currentUser.Username,
                AuthorId     = _currentUser.Id,
                CommentBody  = todoCommentDto.CommentBody,
                ParentTodoId = todoCommentDto.ParentTodoId,
            };

            await _dbRepository.AddAsync(comment);

            return(comment);
        }
Beispiel #14
0
        public async Task <Post> AddAsync(Post Post)
        {
            try
            {
                Post = await dbRepository.AddAsync(Post);

                return(Post);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.StackTrace);
                throw new Exception($"Failed to create {nameof(Post)}", ex);
            }
        }
        public async Task SaveTaskAsync_GroupIdentifierNotExists_SaveNotPerformed()
        {
            IDbRepository <ITasksGroup> dbRepository = A.Fake <IDbRepository <ITasksGroup> >();

            A.CallTo(() => dbRepository.ListAsync()).Returns(new List <ITasksGroup>());

            TasksGroupService tasksGroupService =
                new TasksGroupService(dbRepository, mTasksGroupFactory, NullLogger <TasksGroupService> .Instance);

            IResponse <IWorkTask> response =
                await tasksGroupService.SaveTaskAsync("notExistingGroupIdentifier", mInvalidTaskName).ConfigureAwait(false);

            A.CallTo(() => dbRepository.AddAsync(A <ITasksGroup> .Ignored)).MustNotHaveHappened();
        }
Beispiel #16
0
        /// <inheritdoc />
        public async Task <BookingEntity> AddBookingAsync(int roomId, DateTime startDate, DateTime endDate)
        {
            var result = await _bookingRepository.AddAsync(new BookingEntity()
            {
                RoomId      = roomId,
                StartDate   = startDate,
                EndDate     = endDate,
                Size        = 1,
                GenderModel = GenderModel.Male
            });

            await _bookingRepository.SaveAsync();

            return(result);
        }
Beispiel #17
0
        public async Task <int> Create(ProviderModel providerModel)
        {
            var providerEntity = _mapper.Map <ProviderEntity>(providerModel);
            var providerCheck  = await _dbRepository.Get <ProviderEntity>(p => p.Name == providerModel.Name).FirstOrDefaultAsync();

            if (providerCheck != null)
            {
                return(0);
            }
            await _dbRepository.AddAsync(providerEntity);

            await _dbRepository.SaveChangesAsync();

            return(providerEntity.Id);
        }
Beispiel #18
0
        public async Task <int> Create(OrderModel orderModel)
        {
            var orderEntity   = _mapper.Map <OrderEntity>(orderModel);
            var providerCheck = await _dbRepository.Get <ProviderEntity>(p => p.Id == orderModel.Provider.Id)
                                .FirstOrDefaultAsync();

            if (providerCheck != null)
            {
                orderEntity.Provider = providerCheck;
            }
            await _dbRepository.AddAsync(orderEntity);

            await _dbRepository.SaveChangesAsync();

            return(orderEntity.Id);
        }
Beispiel #19
0
        public async Task <Category> AddAsync(Category category)
        {
            try
            {
                category = await dbRepository.AddAsync(category);

                busClient.Publish(new CategoryCreated());

                return(category);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.StackTrace);
                throw new Exception($"Failed to create {nameof(Category)}", ex);
            }
        }
Beispiel #20
0
        public async Task <Tag> AddAsync(Tag Tag)
        {
            try
            {
                Tag = await dbRepository.AddAsync(Tag);

                busClient.Publish(new TagCreated());

                return(Tag);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.StackTrace);
                throw new Exception($"Failed to create {nameof(Tag)}", ex);
            }
        }
        public async Task SaveAsync_ValidTasksGroupToAdd_SuccessResponseReturned()
        {
            const string groupName = "ValidGroupName";

            IDbRepository <ITasksGroup> dbRepository = A.Fake <IDbRepository <ITasksGroup> >();

            A.CallTo(() => dbRepository.AddAsync(A <ITasksGroup> .Ignored)).Returns(true);

            TasksGroupService tasksGroupService =
                new TasksGroupService(dbRepository, mTasksGroupFactory, NullLogger <TasksGroupService> .Instance);

            IResponse <ITasksGroup> response = await tasksGroupService.SaveAsync(groupName).ConfigureAwait(false);

            Assert.True(response.IsSuccess);
            Assert.Equal(groupName, response.ResponseObject.Name);
        }
Beispiel #22
0
        public async Task <Todo> CreateNewTodo(TodoDto newTodo)
        {
            var todo = new Todo
            {
                Title              = newTodo.Title,
                TextBody           = newTodo.TextBody,
                ExpirationDateTime = newTodo.ExpirationDateTime,
                TodoImportance     = newTodo.TodoImportance,
                AuthorId           = _currentUser.Id,
                AuthorUsername     = _currentUser.Username,
                ProjectId          = newTodo.ProjectId
            };

            await _dbRepository.AddAsync(todo);

            return(todo);
        }
        public async Task Handle(UpdateDatabaseRequest request, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Updating DB...");

            await _answersRepository.ClearAsync();

            await _questionRepository.ClearAsync();

            await _userAnswerRepository.ClearAsync();

            await _categoriesRepository.ClearAsync();

            foreach (var category in JsonConvert.DeserializeObject <Category[]>(File.ReadAllText("Data/categories.json")))
            {
                await _categoriesRepository.AddAsync(category);
            }

            foreach (var question in JsonConvert.DeserializeObject <Question[]>(File.ReadAllText("Data/questions.json")))
            {
                await _questionRepository.AddAsync(question);

                var stub = new Answer
                {
                    QuestionId = question.Id,
                    IsStub     = true,
                    Text       = string.Empty
                };

                await _answerRepository.AddAsync(stub);
            }

            var users = await _userRepository.FindAsync(x => true);

            foreach (var user in users)
            {
                user.UserStatus = UserStatus.NewUser;
                user.IsWinner   = false;

                await _userRepository.UpdateAsync(user);
            }

            _logger.LogDebug("DB updated");
        }
Beispiel #24
0
        public Task Execute(IJobExecutionContext context)
        {
            var cpu = Convert.ToInt32(_cpuCounter.NextValue());

            _cpuRepository.AddAsync(new CpuMetric()
            {
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Value = cpu
            });

            var hdd = Convert.ToInt32(_hddCounter.NextValue());

            _hddRepository.AddAsync(new HddMetric()
            {
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Value = hdd
            });

            var ram = Convert.ToInt32(_ramCounter.NextValue());

            _ramRepository.AddAsync(new RamMetric()
            {
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Value = ram
            });

            var network = Convert.ToInt32(_networkCounter.NextValue());

            _networkRepository.AddAsync(new NetworkMetric()
            {
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Value = network
            });

            var dotnet = Convert.ToInt32(_dotnetCounter.NextValue());

            _dotnetRepository.AddAsync(new DotnetMetric()
            {
                Time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), Value = dotnet
            });

            return(Task.CompletedTask);
        }
Beispiel #25
0
 public async Task AddBookAsync(Models.Book book)
 {
     await _dbRepo.AddAsync(book);
 }