/// <summary>
        /// Saving user statistics both in the storage and in the json file database
        /// if user is identified by his/her authorization <paramref name="token"/>.
        /// </summary>
        /// <param name="token">User's authorization token.</param>
        /// <param name="outcome">Game outcome. One of <see cref="GameOutcome"/></param>
        /// <param name="move">Chosen move option. One of <see cref="MoveOptions"/></param>
        /// <returns>Returns true if user was found by token, else returns false.</returns>
        public async Task <bool> SaveAsync(string token, GameOutcome outcome, MoveOptions move)
        {
            // get user id
            var userWithToken = (await _tokens.GetAllAsync()).Where(tk => tk.Item == token).FirstOrDefault();

            // if user was not found
            if (userWithToken == null)
            {
                // only one logger message here so as not to litter the file with messages
                // about saving statistics, since this method will be called very often
                _logger.LogInformation($"{nameof(StatisticsService)}: User was not identified for saving statistics. The authorization token did not exist or expired.");
                return(false);
            }

            // get user id
            var userId = userWithToken.Id;

            // add user statistics to the storage if it doesn't exist
            await _statistics.AddAsync(new UserStatistics(userId), userId, new StatisticsEqualityComparer());

            // change state
            var record = await _statistics.GetAsync(userId);

            record.AddRoundInfo(DateTime.Now, outcome, move);

            // map with StatisticsDb
            var statisticsToSave = ModelsMapper.ToStatisticsDb(record);

            //save to file
            await _jsonDataService.WriteAsync(_options.StatisticsPath + $"{userId}.json", statisticsToSave);

            return(true);
        }
Exemple #2
0
        public async Task <ActionResult <int> > CreateAccount(AccountDto accountDto)
        {
            try
            {
                var account = new Account
                {
                    Id       = Guid.NewGuid().ToString(),
                    Login    = accountDto.Login,
                    Password = accountDto.Password
                };
                var statistics = new Statistics
                {
                    Id    = account.Id,
                    Login = account.Login,
                };

                await _accountStorage.AddAsync(account);

                await _statisticsStorage.AddAsync(statistics);

                return(Created("", $"Account [{account.Login}] successfully created"));
            }
            catch (ValidationException exception)
            {
                _logger.Log(LogLevel.Warning, exception.Message);
                return(BadRequest(exception.Message));
            }
            catch (UnknownReasonException exception)
            {
                _logger.Log(LogLevel.Warning, exception.Message);
                return(BadRequest(exception.Message));
            }
        }
Exemple #3
0
 public async Task AddProductAsync(Product product)
 {
     await Task.Run(async() =>
     {
         await _storage.AddAsync(product);
         await _storage.SaveChanges();
     });
 }
Exemple #4
0
 public async Task AddCategoryAsync(Category category)
 {
     await Task.Run(async() =>
     {
         await _storage.AddAsync(category);
         await _storage.SaveChanges();
     });
 }
 public async Task AddBidAsync(Bid bid)
 {
     await Task.Run(async() =>
     {
         await _storage.AddAsync(bid);
         await _storage.SaveChanges();
     });
 }
Exemple #6
0
        public void AddUser(User user)
        {
            var jsonModelUser = new User {
                Id = Guid.NewGuid()
            };

            ////jsonModelUser.InjectFrom(user);
            _storage.AddAsync(user);
            _storage.SaveChanges();
        }
        /// <summary>
        /// Saving user both in the storage and in the json file database.
        /// </summary>
        /// <param name="login">User login.</param>
        /// <param name="password">User password.</param>
        /// <returns>Returns whether the user was saved.
        /// True if user was saved.
        /// False if user was not saved (because already exists).
        /// </returns>
        public async Task <bool> SaveAsync(string login, string password)
        {
            _logger.LogInformation($"{nameof(UsersService)}: Saving a new user.");

            // add user to the user storage
            var userId = await _users.AddAsync(new User(login, password), null, new UserEqualityComparer());

            // if user was not added because already exists
            if (userId == null)
            {
                _logger.LogInformation($"{nameof(UsersService)}: User was not added because the login {login} already exists.");
                return(false);
            }

            _logger.LogInformation($"{nameof(UsersService)}: New user with login {login} was added to the storage.");

            // create empty statistics for the new user in memory storage
            var userStatistics = new UserStatistics((int)userId);
            await _statistics.AddAsync(userStatistics, (int)userId);

            _logger.LogInformation($"{nameof(UsersService)}: Empty statistics for the new user with login {login} was added to the storage.");

            // save empty statistics for the new user to the json-file database
            var statisticsToSave = ModelsMapper.ToStatisticsDb(userStatistics);
            await _statDataService.WriteAsync($"{_options.StatisticsPath}{userId}.json", statisticsToSave);

            _logger.LogInformation($"{nameof(UsersService)}: Empty statistics for the new user with login {login} was saved to the file {_options.StatisticsPath}{userId}.json.");

            // get all users
            var users = await _users.GetAllAsync();

            // map with UserDb
            var usersToSave = users.Select(user => ModelsMapper.ToUserDb(user.Id, user.Item));

            // save to file
            await _userDataService.WriteAsync(_options.UsersPath, usersToSave);

            _logger.LogInformation($"{nameof(UsersService)}: All users were rewritten in {_options.UsersPath}.");

            return(true);
        }
        public void AddPermission(Permission permission)
        {
            /*Permission permission = new Permission()
             * {
             *  AuctionId = permissionDTO.AuctionId,
             *  CategoriesId = permissionDTO.CategoriesId,
             *  Role = (int)permissionDTO.Role,
             *  Id = permissionDTO.Id,
             *  UserId = permissionDTO.UserId
             * };*/

            _storage.AddAsync(permission);
            _storage.SaveChanges();
        }
Exemple #9
0
        public async Task <IActionResult> PostAsync([FromBody] User user)
        {
            // option SuppressModelStateInvalidFilter should be enabled
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _logger.LogInformation($"New user registration from {Platform}");

            var id = await _users.AddAsync(user);

            // return 201
            return(CreatedAtAction(nameof(GetByIdAsync), new { id }, id));
        }
Exemple #10
0
        public override async Task <Result> Add(ItemRequest request, ServerCallContext context)
        {
            _ = request?.Item ?? throw new ArgumentNullException(nameof(request));

            _logger.LogDebug("Adding item");

            var newId = Guid.NewGuid();

            request.Item.InsertedOn = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow);

            await _storage.AddAsync(newId, request.Item);

            return(new Result {
                Response = Service.Result.Types.Response.Ok
            });
        }
 public Task AddAsync(IEnumerable <Contact> contacts) => _persistenceStorage.AddAsync(contacts);