コード例 #1
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Account>();

            validationContext.When(model, m => m.Email)
            .IsNotEmail()
            .AddValidationDetail("Это не email =/");

            validationContext.When(model, m => m.Password)
            .IsNullOrWhitespace()
            .AddValidationDetail("Укажите ваш пароль");

            if (validationContext.IsValid(model, m => m.Email) && validationContext.IsValid(model, m => m.Password))
            {
                var account = await databaseContext
                              .Accounts
                              .FirstOrDefaultAsync(x => x.Email == model.Email);

                var accountExists = account != null &&
                                    passwordHasher.VerifyHashedPassword(
                    account,
                    account.Password,
                    model.Password) == PasswordVerificationResult.Success;

                validationContext.When()
                .IsNot(() => accountExists)
                .AddValidationDetail("Email/пароль неверный, либо аккаунт не существует");
            }
        }
コード例 #2
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var columnExists = await databaseContext
                               .Columns
                               .Include(x => x.Board)
                               .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                               .AnyAsync(x => x.Id == model.Id);

            validationContext.When()
            .IsNot(() => columnExists)
            .AddValidationDetail("Колонка не существует");

            if (validationContext.IsValid())
            {
                var hasColumns = await databaseContext
                                 .Columns
                                 .Where(x => x.Id == model.Id)
                                 .Where(x => x.Cards.Any())
                                 .AnyAsync();

                validationContext.When()
                .Is(() => hasColumns)
                .AddValidationDetail("Колонка содержит карточки");
            }
        }
コード例 #3
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Organization>();

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Задайте имя организации");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var organizationNameExists = await databaseContext
                                             .Organizations
                                             .AnyAsync(organization => organization.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => organizationNameExists)
                .AddValidationDetail("Имя организации уже используется");
            }

            validationContext.When(model, m => m.Accounts)
            .IsEmpty()
            .AddValidationDetail("Создайте хотя-бы один аккаунт");

            for (var index = 0; index < model.Accounts.Count; index++)
            {
                var account = model.Accounts[index];

                using (var scope = validationContext.CreateScope(model, m => m.Accounts[index]))
                {
                    await accountValidation.ValidateAccount(scope, account);
                }
            }
        }
コード例 #4
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var boardExists = await databaseContext
                              .Boards
                              .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                              .AnyAsync(x => x.Id == model.BoardId);

            validationContext.When(model, m => m.BoardId)
            .IsNot(() => boardExists)
            .AddValidationDetail("Доска не найдена");

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Имя колонки не указано");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var columnExists = await databaseContext
                                   .Columns
                                   .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                   .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => columnExists)
                .AddValidationDetail("Колонка с таким именем уже сущетсвует");
            }
        }
        public void IsTrue()
        {
            var validationDetail = validationContext.When("key", true)
                                   .IsTrue()
                                   .AddValidationDetail("template1");

            Assert.NotNull(validationDetail);

            Assert.Equal("key", validationDetail.ValidationKey);
            Assert.Equal("template1", validationDetail.ValidationMessage);
            Assert.Equal(ValidationSeverity.Error, validationDetail.ValidationSeverity);
        }
コード例 #6
0
        public void ValidationScope_OwnCollection_AddDetailsToRoot()
        {
            validationContext.When("key").AddValidationDetail("Error");

            var validationScope = validationContext.CreateScope("Scope");

            Assert.Empty(validationScope.ValidationDetails);

            validationScope.When("Key").AddValidationDetail("Error");

            Assert.Single(validationScope.ValidationDetails);
            Assert.Equal(2, validationContext.ValidationDetails.Count);
        }
コード例 #7
0
        public Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model = context.GetArgument <Invite>();

            validationContext.When(model, m => m.Role)
            .IsNotIn(Roles.All)
            .AddValidationDetail("Неизвестная роль");

            validationContext.When(model, m => m.Description)
            .IsNullOrWhitespace()
            .AddValidationDetail("Заполните описание");

            return(Task.CompletedTask);
        }
コード例 #8
0
        public void Save(IValidationContext validationContext)
        {
            validationContext.When(this, a => a.City)
            .IsNullOrWhitespace()
            .AddValidationDetail("City must be set");

            validationContext.When(this, a => a.Street)
            .IsNullOrWhitespace()
            .AddValidationDetail("Street must be set");

            validationContext.When(this, a => a.House)
            .IsNull()
            .AddValidationDetail("House must be set");
        }
コード例 #9
0
        public void Save(IValidationContext validationContext)
        {
            validationContext.When(this, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Order name must be set");

            validationContext.When(this, m => m.Cost)
            .IsNotInRange(0, 10)                     // .IsLessOrEqual(0).IsGreaterOrEqual(10)
            .AddValidationDetail("Cost must be in [1, 9] range");

            validationContext.When(this, m => m.Address)
            .IsNull()
            .AddValidationDetail("You should add your address");

            Address?.Save(/*databaseContext, */ validationContext.CreateScope(this, m => m.Address));
        }
コード例 #10
0
 /// <summary>
 ///   Specifies validation part with <see cref="TValue" /> value
 /// </summary>
 public static IValidationCondition <TValue> When <TValue>(
     this IValidationContext validationContext,
     string validationPart,
     TValue value)
 {
     return(validationContext.When(validationPart, new Lazy <TValue>(() => value)));
 }
コード例 #11
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Column>();

            var columnExists = await databaseContext
                               .Columns
                               .Include(x => x.Board)
                               .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                               .AnyAsync(x => x.Id == model.Id);

            validationContext.When(model, m => m.Id)
            .IsNot(() => columnExists)
            .AddValidationDetail("Колонка не найдена");

            validationContext.When(model, m => m.Name)
            .IsWhitespace()
            .AddValidationDetail("Имя колонки не указано");

            if (validationContext.IsValid(model, m => m.Name) && model.Name != null)
            {
                var columnNameExists = await databaseContext
                                       .Columns
                                       .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                       .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => columnNameExists)
                .AddValidationDetail($"Колонка с именем '{model.Name}' уже сущетсвует");
            }

            if (model.Order != 0)
            {
                validationContext.When(model, x => x.Order)
                .IsLess(0)
                .AddValidationDetail("Порядок не может быть меньше нуля");

                var columnsCount = await databaseContext
                                   .Columns
                                   .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                                   .CountAsync(x => x.Board.Columns.Any(c => c.Id == model.Id));

                validationContext.When(model, m => m.Order)
                .IsGreater(columnsCount)
                .AddValidationDetail($"Порядок не может быть больше {columnsCount}");
            }
        }
コード例 #12
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <CardComment>();

            validationContext.When(model, m => m.Text)
            .IsNullOrWhitespace()
            .AddValidationDetail("Пустой текст");

            var cardExists = await databaseContext.Cards
                             .Where(x => x.Column.Board.Organization.Accounts.Any(a => a.Id == accountId))
                             .AnyAsync(x => x.Id == model.CardId);

            validationContext.When(model, m => m.CardId)
            .IsNot(() => cardExists)
            .AddValidationDetail("Карточка не найдена");
        }
コード例 #13
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Board>();

            var boardExists = await databaseContext.Boards
                              .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                              .AnyAsync(x => x.Id == model.Id);

            validationContext.When(model, m => m.Id)
            .IsNot(() => boardExists)
            .AddValidationDetail("Доска не найдена");

            validationContext.When(model, m => m.Name)
            .IsWhitespace()
            .AddValidationDetail("Название доски не задано");
        }
コード例 #14
0
        public async Task ValidateCardOrder(IValidationContext validationContext, Card card, Card model)
        {
            if (model.Order != 0)
            {
                validationContext.When(model, x => x.Order)
                .IsLess(0)
                .AddValidationDetail("Порядок не может быть меньше нуля");

                var cardsCount = await databaseContext
                                 .Columns
                                 .Where(x => x.Id == card.ColumnId)
                                 .SelectMany(x => x.Cards)
                                 .CountAsync();

                validationContext.When(model, m => m.Order)
                .IsGreater(cardsCount)
                .AddValidationDetail($"Порядок не может быть больше {cardsCount}");
            }
        }
コード例 #15
0
        public async Task ValidateColumnExists(IValidationContext validationContext, Card model, Guid accountId)
        {
            var columnExists = await databaseContext.Columns
                               .Where(x => x.Board.Organization.Accounts.Any(account => account.Id == accountId))
                               .AnyAsync(x => x.Id == model.ColumnId);

            validationContext.When(model, m => m.ColumnId)
            .IsNot(() => columnExists)
            .AddValidationDetail("Колонка не найдена");
        }
コード例 #16
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Board>();

            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Название доски не задано");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var boardExists = await databaseContext.Boards
                                  .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                  .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => boardExists)
                .AddValidationDetail("Доска с таким именем уже существует");
            }
        }
コード例 #17
0
        public async Task ValidateCardName(IValidationContext validationContext, Card model, Guid accountId)
        {
            validationContext.When(model, m => m.Name)
            .IsNullOrWhitespace()
            .AddValidationDetail("Укажите название карточки");

            if (validationContext.IsValid(model, m => m.Name))
            {
                var cardNameExists = await databaseContext.Boards
                                     .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                                     .Where(x => x.Columns.Any(c => c.Id == model.ColumnId))
                                     .SelectMany(x => x.Columns)
                                     .SelectMany(x => x.Cards)
                                     .AnyAsync(x => x.Name == model.Name);

                validationContext.When(model, m => m.Name)
                .Is(() => cardNameExists)
                .AddValidationDetail("Карточка с таким названием уже существует");
            }
        }
コード例 #18
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var id        = context.GetArgument <Guid>("id");

            var comment = await databaseContext
                          .CardComments
                          .FirstOrDefaultAsync(x => x.Id == id && x.AccountId == accountId);

            validationContext.When("id")
            .Is(() => comment == null)
            .AddValidationDetail("Комментарий не найден");

            if (comment != null)
            {
                validationContext.When()
                .Is(() => comment.CreatedAt.AddHours(1) < DateTime.UtcNow)
                .AddValidationDetail("Комментарий можно удалить только в первый час создания");
            }
        }
コード例 #19
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var inviteId  = context.GetArgument <Guid>("id");

            var invite = await databaseContext
                         .Invites
                         .Where(x => x.Organization.Accounts.Any(account => account.Id == accountId))
                         .FirstOrDefaultAsync(x => x.Id == inviteId);

            validationContext.When("id")
            .Is(() => invite == null)
            .AddValidationDetail("Приглашение не найдено");

            if (validationContext.IsValid("id"))
            {
                validationContext.When("id")
                .Is(() => invite.AccountId != null)
                .AddValidationDetail("Нельзя удалить использованное приглашение");
            }
        }
コード例 #20
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Card>();

            await ValidateColumnExists(validationContext, model, accountId);
            await ValidateCardName(validationContext, model, accountId);

            validationContext.When(model, m => m.Description)
            .IsNullOrWhitespace()
            .AddValidationDetail("Описание не задано");
        }
コード例 #21
0
        public async Task <Card> ValidateCardExists(IValidationContext validationContext, Card model, Guid accountId)
        {
            var card = await databaseContext.Cards
                       .Where(x => x.Column.Board.Organization.Accounts.Any(account => account.Id == accountId))
                       .SingleOrDefaultAsync(x => x.Id == model.Id);

            validationContext.When(model, m => m.Id)
            .Is(() => card == null)
            .AddValidationDetail("Карточка не найдена");

            return(card);
        }
コード例 #22
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Card>();

            var card = await databaseContext.Cards
                       .Where(x => x.Column.Board.Organization.Accounts.Any(account => account.Id == accountId))
                       .SingleOrDefaultAsync(x => x.Id == model.Id);

            validationContext.When(model, m => m.Id)
            .Is(() => card == null)
            .AddValidationDetail("Карточка не найдена");
        }
コード例 #23
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <CardAssignment>();

            var accountExists = await databaseContext.Accounts
                                .Where(x => x.Id == accountId)
                                .Select(x => x.Organization)
                                .SelectMany(x => x.Accounts)
                                .AnyAsync(x => x.Id == model.AccountId);

            validationContext.When(model, m => m.AccountId)
            .IsNot(() => accountExists)
            .AddValidationDetail("Аккаунт не найден");

            var cardExists = await databaseContext.Accounts
                             .Where(x => x.Id == accountId)
                             .Select(x => x.Organization)
                             .SelectMany(x => x.Boards)
                             .SelectMany(x => x.Columns)
                             .SelectMany(x => x.Cards)
                             .AnyAsync(x => x.Id == model.CardId);

            validationContext.When(model, m => m.AccountId)
            .IsNot(() => cardExists)
            .AddValidationDetail("Карточка не найдена");

            if (validationContext.IsValid())
            {
                var assignmentExists = await databaseContext
                                       .CardAssignments
                                       .AnyAsync(x => x.AccountId == model.AccountId && x.CardId == model.CardId);

                validationContext.When()
                .Is(() => assignmentExists)
                .AddValidationDetail("Аккаунт уже назначен");
            }
        }
コード例 #24
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <CardComment>();

            validationContext.When(model, m => m.Text)
            .IsNullOrWhitespace()
            .AddValidationDetail("Текст пустой");

            var comment = await databaseContext.CardComments
                          .FirstOrDefaultAsync(x => x.Id == model.Id && x.AccountId == accountId);

            validationContext.When(model, m => m.Id)
            .Is(() => comment == null)
            .AddValidationDetail("Комментарий не найден");

            if (comment != null)
            {
                validationContext.When()
                .Is(() => comment.CreatedAt.AddHours(1) < DateTime.UtcNow)
                .AddValidationDetail("Комментарий можно отредактировать только в первый час создания");
            }
        }
コード例 #25
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var model  = context.GetArgument <Account>();
            var secret = context.GetArgument <Guid>("secret");

            var inviteExists = await databaseContext.Invites
                               .Where(x => x.Secret == secret)
                               .AnyAsync(x => x.Account == null);

            validationContext.When("secret")
            .IsNot(() => inviteExists)
            .AddValidationDetail("Приглашение не найдено, либо уже использовано");

            await ValidateAccount(validationContext, model);
        }
        /// <summary>
        ///   Specifies <see cref="TModel" /> with expression-based validation key
        /// </summary>
        public static IValidationCondition <TValue> When <TModel, TValue>(
            this IValidationContext validationContext,
            TModel model,
            Expression <Func <TModel, TValue> > expression,
            Func <TValue> provider)
        {
            var serviceProvider        = (IServiceProvider)validationContext;
            var validationPathResolver = serviceProvider.GetRequiredService <IValidationPathResolver>();

            var validationPart = validationPathResolver.FromExpression(expression.Body);

            return(validationContext.When(
                       validationPart,
                       new Lazy <TValue>(provider)));
        }
コード例 #27
0
        public async Task ValidateAccount(IValidationContext validationContext, Account model)
        {
            var loginDetail = validationContext.When(model, m => m.Login)
                              .IsNullOrWhitespace()
                              .AddValidationDetail("Логин не задан");

            if (loginDetail is null)
            {
                var loginExists = await databaseContext
                                  .Accounts
                                  .AnyAsync(x => x.Login == model.Login);

                validationContext.When(model, m => m.Login)
                .Is(() => loginExists)
                .AddValidationDetail("Логин уже используется");
            }

            var emailDetail = validationContext.When(model, m => m.Email)
                              .IsNotEmail()
                              .AddValidationDetail("Это не email =/");

            if (emailDetail is null)
            {
                var accountExists = await databaseContext
                                    .Accounts
                                    .AnyAsync(account => account.Email == model.Email);

                validationContext.When(model, m => m.Email)
                .Is(() => accountExists)
                .AddValidationDetail("Email уже используется");
            }

            validationContext.When(model, m => m.Password)
            .IsNullOrWhitespace()
            .AddValidationDetail("Пароль не задан");

            validationContext.When(model, m => m.FirstName)
            .IsNullOrWhitespace()
            .AddValidationDetail("Имя не задано");

            validationContext.When(model, m => m.LastName)
            .IsNullOrWhitespace()
            .AddValidationDetail("Фамилия не задана");
        }
コード例 #28
0
        public async Task Validate(DocumentIOResolveFieldContext <object> context, IValidationContext validationContext)
        {
            var accountId = context.GetAccountId();
            var model     = context.GetArgument <Card>();

            var card = await ValidateCardExists(validationContext, model, accountId);

            await ValidateCardName(validationContext, card, model, accountId);
            await ValidateCardOrder(validationContext, card, model);

            if (model.ColumnId != Guid.Empty)
            {
                var columnExists = await databaseContext.Columns
                                   .AnyAsync(x => x.Board
                                             .Columns
                                             .Any(column =>
                                                  column.Cards.Any(c => c == card)));

                validationContext.When(model, m => m.ColumnId)
                .IsNot(() => columnExists)
                .AddValidationDetail("Колонка не найдена");
            }
        }
コード例 #29
0
        public void IsType_StringType_Invalid()
        {
            var(key, message) = validationContext.When("name", "john")
                                .IsType(typeof(string))
                                .AddValidationDetail("template1");

            Assert.Equal("name", key);
            Assert.Equal("template1", message);
        }
        public void IsEmpty()
        {
            var validationDetail = validationContext.When("key", Array.Empty <int>())
                                   .IsEmpty()
                                   .AddValidationDetail("template1");

            Assert.NotNull(validationDetail);
            Assert.Equal("key", validationDetail.ValidationKey);
            Assert.Equal("template1", validationDetail.ValidationMessage);
        }