Exemple #1
0
        public async Task <IHtmlContent> WriteMenu2DBAsync(IHtmlContent html, int doctorId, int stationId)
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            StringBuilder          sb = new StringBuilder();

            System.IO.TextWriter tw = new System.IO.StringWriter(sb);
            html.WriteTo(tw, System.Text.Encodings.Web.HtmlEncoder.Default);
            tw.Dispose(); sw.Dispose();
            var find = await MainDbContext.CHIS_Sys_UserMenu.AsNoTracking().FirstOrDefaultAsync(m => m.DoctorId == doctorId && m.StationId == stationId);

            if (find == null)
            {
                await MainDbContext.AddAsync(new Models.CHIS_Sys_UserMenu
                {
                    Id          = Guid.NewGuid(),
                    DoctorId    = doctorId,
                    StationId   = stationId,
                    MenuContent = sb.ToString()
                });
            }
            else
            {
                find.MenuContent = sb.ToString();
                MainDbContext.Update(find);
            }
            await MainDbContext.SaveChangesAsync();

            return(html);
        }
        public async Task <Status> Register(RegistrationDto registrationDto)
        {
            var user = _mainDbContext.Users.Any(u => u.Username == registrationDto.Username);

            if (user)
            {
                var status = new Status
                {
                    Success = false,
                    Message = $"User with login {registrationDto.Username} exist"
                };
                return(status);
            }

            var salt         = Guid.NewGuid().ToString();
            var passwordHash = PrepareHashPassword(registrationDto.Password, salt, registrationDto.IsPasswordKeptAsHash);

            var newUser = new User
            {
                Username            = registrationDto.Username,
                PasswordHash        = passwordHash,
                Salt                = salt,
                IsPasswordKeptAsSha = registrationDto.IsPasswordKeptAsHash
            };

            await _mainDbContext.AddAsync(newUser);

            await _mainDbContext.SaveChangesAsync();

            return(new Status(true, "You've successfully signed up"));
        }
Exemple #3
0
        public async Task <PlayerOutVM> CreatePlayer(PlayerInVM playerIn)
        {
            using var transaction = await _transactionManager.BeginTransactionAsync();

            var existingPlayer = await _context.Players.Where(p => p.Username == playerIn.Username).AnyAsync();

            if (existingPlayer)
            {
                throw new ValidationException("Player with given name already exists");
            }
            var salt   = Guid.NewGuid().ToString();
            var player = new Player
            {
                Username       = playerIn.Username,
                HashedPassword = _passwordService.HashPassword(playerIn.Password, salt),
                Salt           = salt
            };
            await _context.AddAsync(player);

            await _context.SaveChangesAsync();

            await transaction.CommitAsync();

            return(new PlayerOutVM {
                ID = player.ID,
                Username = player.Username
            });
        }
        public async Task <Status> EditEntry(EditEntryDto editEntryDto, int userId)
        {
            var owner = await _mainDbContext.Users.FirstOrDefaultAsync(user => user.UserId == userId);

            if (owner == null)
            {
                return(new Status(false, "User owner not found"));
            }

            var userEntry =
                await _mainDbContext.UsersEntries.Include(p => p.Entry.CurrentEntryState).FirstOrDefaultAsync(x =>
                                                                                                              x.EntryId == editEntryDto.EntryId && x.UserId == userId);

            if (userEntry == null)
            {
                return(new Status(false, "Entry not found"));
            }

            if (!userEntry.IsUserOwner)
            {
                return(new Status(false, "You cannot edit shared for you entry. You have to be an owner for edit."));
            }

            try
            {
                var newEntryState = new EntryState
                {
                    PasswordE   = SymmetricEncryptor.EncryptString(editEntryDto.PasswordDecrypted, owner.PasswordHash),
                    Username    = editEntryDto.Username,
                    Description = editEntryDto.Description,
                    Email       = editEntryDto.Email,
                    WebAddress  = editEntryDto.WebAddress,
                    IsDeleted   = false
                };
                userEntry.Entry.CurrentEntryState = newEntryState;
                var entryAction = CreateEntryAction(owner, newEntryState, userEntry.Entry, ActionTypesEnum.Edit);

                await _mainDbContext.AddAsync(entryAction);

                await _mainDbContext.SaveChangesAsync();

                return(new Status(true, "Password has been successfully edited"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(new Status
                {
                    Success = false,
                    Message = "Something went wrong"
                });
            }
        }
Exemple #5
0
        public async Task <JoinGroupPayload> JoinGroup(
            JoinGroupInput input,
            [ScopedService] MainDbContext db,
            [Service] ITopicEventSender eventSender
            )
        {
            var(groupId, userId) = input;
            var group = await db.Groups.FindAsync(groupId);

            var user = await db.Users.FindAsync(userId);

            group.Users.Add(user);
            await db.AddAsync(group);

            await db.SaveChangesAsync();

            return(new JoinGroupPayload(group));
        }
        public async Task <TEntity> AddAsync(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
            }

            try
            {
                await _mainDbContext.AddAsync(entity);

                await _mainDbContext.SaveChangesAsync();

                return(entity);
            }
            catch (Exception)
            {
                throw new Exception($"{nameof(entity)} could not be saved");
            }
        }
Exemple #7
0
        public async Task <CreateGroupPayload> CreateGroup(
            CreateGroupInput input,
            [Service] MainDbContext db,
            [Service] ITopicEventSender eventSender,
            CancellationToken ct
            )
        {
            var(groupName, userIds) = input;
            var users = userIds.Select(userId =>
                                       db.Users.Find(userId)
                                       ?? throw new RequestException($"user with id `{userId}` does not exist"));
            var newGroup = new Group(groupName);

            newGroup.Users.AddRange(users);
            var entry = await db.AddAsync(newGroup, ct);

            await db.SaveChangesAsync(ct);

            return(new CreateGroupPayload(entry.Entity));
        }
Exemple #8
0
        public async Task <ProductDto> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var brand = await _dbContext.Brands
                        .FirstOrDefaultAsync(x => x.Id == request.BrandId, cancellationToken);

            if (brand is null)
            {
                throw new NotFoundBrandException(request.BrandId);
            }

            var category = await _dbContext.Categories
                           .FirstOrDefaultAsync(x => x.Id == request.CategoryId, cancellationToken);

            if (category is null)
            {
                throw new NotFoundBrandException(request.CategoryId);
            }

            var product = new Product();

            product.CreateProduct(request.Name, request.ModelYear, request.ListPrice, brand, category);

            var created = await _dbContext.AddAsync(product, cancellationToken);

            await _dbContext.SaveChangesAsync(cancellationToken);

            return(new ProductDto
            {
                Id = created.Entity.Id,
                Name = created.Entity.Name,
                ModelYear = created.Entity.ModelYear,
                ListPrice = created.Entity.ListPrice
            });
        }
Exemple #9
0
        public async Task <FullGameStateOutVM> CreateGame(string[] playerList, int cardLimit)
        {
            if (cardLimit < 1)
            {
                throw new BadRequestException("Cannot create game without in-hand cards");
            }
            using var transaction = await _transactionManager.BeginTransactionAsync();

            var randomInstance = _randomGenerator.CreateRandom();

            await _gameManagementService.CloseExistingGames(playerList);

            var cards     = _deckService.CreateCards();
            var cardQueue = new Queue <Card>(cards);

            var empty = _cardSerializer.SerializeCards(new Card[0]);

            var game = new Game
            {
                GameStartedAt = DateTimeOffset.UtcNow,
                CardLimit     = cardLimit,
                Discarded     = empty,
            };
            var players = (await _context
                           .Players
                           .Where(p => playerList.Contains(p.Username))
                           .ToListAsync())
                          .Select(player => new
            {
                Player = player,
                Cards  = cardQueue.Dequeue(cardLimit)
            })
                          .ToList();

            if (players.Count != playerList.Length)
            {
                throw new ArgumentOutOfRangeException("Not all players exist");
            }
            var state = players.Select(e => new GamePlayerState
            {
                Game   = game,
                Player = e.Player,
                Hand   = _cardSerializer.SerializeCards(e.Cards),
                Table  = _mapper.SerializeQueues(new List <List <Card> > {
                    new List <Card>(), new List <Card>()
                }),
            }).ToList();
            var remaining = cardQueue.ToList();

            game.State      = state;
            game.Deck       = _cardSerializer.SerializeCards(remaining);
            game.NextPlayer = players[randomInstance.Next(players.Count)].Player;

            await _context.AddAsync(game);

            await _context.SaveChangesAsync();

            var output = _mapper.MapFullGameState(game);
            await transaction.CommitAsync();

            return(output);
        }