Exemple #1
0
        public async Task <List <KeyVm> > AddNewUserKeysAsync(IEnumerable <KeyVm> keys, long userId)
        {
            try
            {
                using (MessengerDbContext context = contextFactory.Create())
                {
                    var publicKeys = KeyConverter.GetKeys(keys);
                    publicKeys.ForEach(key => key.UserId = userId);
                    await context.Keys.AddRangeAsync(publicKeys).ConfigureAwait(false);

                    await context.SaveChangesAsync().ConfigureAwait(false);

                    return(KeyConverter.GetKeysVm(publicKeys));
                }
            }
            catch (DbUpdateException ex)
            {
                if (ex.InnerException is PostgresException postgresException)
                {
                    if (postgresException.ConstraintName == "IX_Keys_KeyId_UserId")
                    {
                        throw new ObjectAlreadyExistsException();
                    }
                }
                throw new Exception("Error while saving key", ex);
            }
        }
        private async Task HandleNewUserKeysBlockSegmentAsync(BlockSegmentVm segment)
        {
            using (MessengerDbContext _context = CreateContext())
            {
                using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
                {
                    try
                    {
                        NewUserKeysBlockData blockData = (NewUserKeysBlockData)segment.PublicData;
                        var keysCondition = PredicateBuilder.New <Key>();
                        keysCondition = blockData.Keys.Aggregate(keysCondition,
                                                                 (current, value) => current.Or(opt => opt.KeyId == value.KeyId && opt.UserId == value.UserId).Expand());
                        var existingKeys = await _context.Keys.Where(keysCondition).ToListAsync().ConfigureAwait(false);

                        var nonExistingKeys = blockData.Keys.Where(key => !existingKeys.Any(opt => opt.KeyId == key.KeyId && opt.UserId == blockData.UserId));
                        if (nonExistingKeys.Any())
                        {
                            var newKeys = KeyConverter.GetKeys(nonExistingKeys);
                            await _context.Keys.AddRangeAsync(newKeys).ConfigureAwait(false);

                            await _context.SaveChangesAsync().ConfigureAwait(false);

                            transaction.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        AddErrorMessage(nameof(HandleNewUserKeysBlockSegmentAsync), ex.ToString());
                        transaction.Rollback();
                    }
                }
            }
        }