Example #1
0
        /// <summary>
        /// Performs additional checks on the request.
        /// </summary>
        private async Task ValidateUpdateRequestAsync(UserEditorVM request)
        {
            var val = new Validator();

            var emailUsed = await _db.Users
                            .AnyAsync(x => x.Id != request.Id && x.Email == request.Email);

            if (emailUsed)
            {
                val.Add(nameof(request.Email), "Адрес почты уже используется другим пользователем");
            }

            if (request.PersonalPageId != null)
            {
                var exists = await _db.Pages
                             .AnyAsync(x => x.Id == request.PersonalPageId);

                if (!exists)
                {
                    val.Add(nameof(request.PersonalPageId), "Страница не существует");
                }
            }

            val.ThrowIfInvalid();
        }
Example #2
0
        /// <summary>
        /// Performs additional checks on the registration request.
        /// </summary>
        private async Task ValidateRegisterRequestAsync(RegisterUserVM vm, bool usePasswordAuth)
        {
            var val = new Validator();

            if (FuzzyDate.TryParse(vm.Birthday) == null)
            {
                val.Add(nameof(vm.Birthday), "Дата рождения указана неверно.");
            }

            var emailExists = await _db.Users.AnyAsync(x => x.Email == vm.Email);

            if (emailExists)
            {
                val.Add(nameof(vm.Email), "Адрес электронной почты уже зарегистрирован.");
            }

            if (usePasswordAuth)
            {
                if (vm.Password == null || vm.Password.Length < 6)
                {
                    val.Add(nameof(vm.Password), "Пароль должен содержать как минимум 6 символов.");
                }

                if (vm.Password != vm.PasswordCopy)
                {
                    val.Add(nameof(vm.PasswordCopy), "Пароли не совпадают.");
                }
            }

            val.ThrowIfInvalid();
        }
Example #3
0
        /// <summary>
        /// Performs additional checks on the registration request.
        /// </summary>
        private async Task ValidateRegisterRequestAsync(RegisterUserVM vm)
        {
            var val = new Validator();

            if (FuzzyDate.TryParse(vm.Birthday) == null)
                val.Add(nameof(vm.Birthday), "Дата рождения указана неверно.");

            var emailExists = await _db.Users.AnyAsync(x => x.Email == vm.Email);
            if (emailExists)
                val.Add(nameof(vm.Email), "Адрес электронной почты уже зарегистрирован.");

            val.ThrowIfInvalid();
        }
Example #4
0
        /// <summary>
        /// Converts a binary data list to list a data list item view models.
        /// </summary>
        /// <param name="dataListToConvert">The data list to convert.</param>
        /// <param name="errorString">The error string.</param>
        /// <returns></returns>
        private void ConvertBinaryDataListToListOfIDataListItemModels(IBinaryDataList dataListToConvert, out string errorString)
        {
            errorString      = string.Empty;
            RecsetCollection = new OptomizedObservableCollection <IDataListItemModel>();
            ScalarCollection = new OptomizedObservableCollection <IDataListItemModel>();

            IList <IBinaryDataListEntry> listOfEntries = dataListToConvert.FetchAllEntries();

            foreach (IBinaryDataListEntry entry in listOfEntries)
            {
                if (entry.IsRecordset)
                {
                    IDataListItemModel recset = DataListItemModelFactory.CreateDataListModel(entry.Namespace, entry.Description, entry.ColumnIODirection);
                    recset.IsEditable = entry.IsEditable;
                    Validator.Add(recset);
                    foreach (Dev2Column col in entry.Columns)
                    {
                        IDataListItemModel child = DataListItemModelFactory.CreateDataListModel(col.ColumnName, col.ColumnDescription, col.ColumnIODirection);
                        child.Parent     = recset;
                        child.IsEditable = col.IsEditable;
                        recset.Children.Add(child);
                        recset.Validator.Add(child);
                    }

                    RecsetCollection.Add(recset);
                }
                else
                {
                    IDataListItemModel scalar = DataListItemModelFactory.CreateDataListModel(entry.Namespace, entry.Description, entry.ColumnIODirection);
                    scalar.IsEditable = entry.IsEditable;
                    ScalarCollection.Add(scalar);
                    Validator.Add(scalar);
                }
            }
        }
Example #5
0
        public void ErrorListCanBeInspected()
        {
            var key11 = new Error("First rrror for Key1")
            {
                Key = "Key1"
            };

            Validator.Add(key11);
            var key12 = new Error("Second error for Key2")
            {
                Key = "Key1"
            };

            Validator.Add(key12);
            var key21 = new Error("Erorr for Key2")
            {
                Key = "Key2"
            };

            Validator.Add(key21);

            var key1Errors = Validator.ErrorsForKey("Key1");

            CollectionAssert.AreEqual(new[] { key11, key12 }, key1Errors.ToArray());
            var allErrors = Validator.Errors;

            CollectionAssert.AreEqual(new[] { key11, key12, key21 }, allErrors.ToArray());

            XAssert.IsTrue(Validator.HasErrorsForKey("Key1"));
            XAssert.IsTrue(Validator.HasErrorsForKey("Key2"));
        }
Example #6
0
        /// <summary>
        /// adds and removes the added and removed Sources from the Validator.
        /// </summary>
        private void OnSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (var i in e.NewItems)
                {
                    var s = (SourceEditViewViewModel)i;
                    _validator.Add(s.Source);
                }
            }
            if (e.OldItems != null)
            {
                foreach (var i in e.OldItems)
                {
                    var s = (SourceEditViewViewModel)i;

                    foreach (var c in s.Source.Columns.ToList())
                    {
                        _validator.Remove(c);
                    }
                    Sources.Remove(s);
                    _validator.Remove(s.Source);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Ensures that the password form has been filled correctly.
        /// </summary>
        private void ValidatePasswordForm(IPasswordForm form)
        {
            var val = new Validator();

            if (form.Password == null || form.Password.Length < 6)
            {
                val.Add(nameof(form.Password), "Пароль должен содержать как минимум 6 символов.");
            }

            if (form.Password != form.PasswordCopy)
            {
                val.Add(nameof(form.PasswordCopy), "Пароли не совпадают.");
            }

            val.ThrowIfInvalid();
        }
Example #8
0
        /// <summary>
        /// Checks if the update request contains valid data.
        /// </summary>
        private async Task ValidateRequestAsync(MediaEditorVM vm)
        {
            var val = new Validator();

            if (!string.IsNullOrEmpty(vm.Date) && FuzzyDate.TryParse(vm.Date) == null)
            {
                val.Add(nameof(vm.Date), "Введите корректную дату.");
            }

            var depictedIds = JsonConvert.DeserializeObject <IEnumerable <MediaTagVM> >(vm.DepictedEntities ?? "[]")
                              .Select(x => x.PageId)
                              .ToList();

            var locId  = vm.Location.TryParse <Guid?>();
            var evtId  = vm.Event.TryParse <Guid?>();
            var tagIds = depictedIds.Concat(new[] { locId, evtId })
                         .Where(x => x != null)
                         .Select(x => x.Value)
                         .ToList();

            if (tagIds.Any())
            {
                var existing = await _db.Pages
                               .Where(x => tagIds.Contains(x.Id) && !x.IsDeleted)
                               .ToHashSetAsync(x => x.Id);

                if (depictedIds.Any(x => x != null && !existing.Contains(x.Value)))
                {
                    val.Add(nameof(vm.DepictedEntities), "Страница не существует!");
                }

                if (locId != null && !existing.Contains(locId.Value))
                {
                    val.Add(nameof(vm.Location), "Страница не существует!");
                }

                if (evtId != null && !existing.Contains(evtId.Value))
                {
                    val.Add(nameof(vm.Event), "Страница не существует!");
                }
            }

            val.ThrowIfInvalid();
        }
Example #9
0
        /// <summary>
        /// Checks if the create/update request contains valid data.
        /// </summary>
        private async Task ValidateRequestAsync(PageEditorVM vm)
        {
            var val = new Validator();

            if (vm.Description == null)
            {
                vm.Description = string.Empty;
            }

            var key       = PageHelper.EncodeTitle(vm.Title).ToLowerInvariant();
            var otherPage = await _db.PageAliases
                            .AnyAsync(x => x.Key == key &&
                                      x.Page.Id != vm.Id);

            if (otherPage)
            {
                val.Add(nameof(PageEditorVM.Title), "Страница с таким названием уже существует.");
            }

            if (!string.IsNullOrEmpty(vm.Aliases))
            {
                var aliases = TryDeserialize <List <string> >(vm.Aliases)?.Select(x => x.ToLowerInvariant());
                if (aliases == null)
                {
                    val.Add(nameof(PageEditorVM.Aliases), "Ссылки указаны неверно!");
                }
                else
                {
                    var otherAliases = await _db.PageAliases
                                       .Where(x => aliases.Contains(x.Key) && x.Page.Id != vm.Id)
                                       .Select(x => x.Title)
                                       .ToListAsync();

                    if (otherAliases.Any())
                    {
                        val.Add(nameof(PageEditorVM.Aliases), "Ссылки уже заняты другими страницами: " + otherAliases.JoinString(", "));
                    }
                }
            }


            val.ThrowIfInvalid();
        }
Example #10
0
        private void AddRowToScalars()
        {
            IList <IDataListItemModel> blankList = ScalarCollection.Where(c => c.IsBlank).ToList();

            if (blankList.Count == 0)
            {
                IDataListItemModel scalar = DataListItemModelFactory.CreateDataListModel(string.Empty);
                ScalarCollection.Add(scalar);
                Validator.Add(scalar);
            }
        }
Example #11
0
        /// <summary>
        /// Adds a record set.
        /// </summary>
        private void AddRecordSet()
        {
            IDataListItemModel recset    = DataListItemModelFactory.CreateDataListModel(string.Empty);
            IDataListItemModel childItem = DataListItemModelFactory.CreateDataListModel(string.Empty);

            recset.IsExpanded = false;
            childItem.Parent  = recset;
            recset.Children.Add(childItem);
            recset.Validator.Add(childItem);
            RecsetCollection.Add(recset);
            Validator.Add(recset);
        }
Example #12
0
        /// <summary>
        /// Checks if the create/update request contains valid data.
        /// </summary>
        private async Task ValidateRequestAsync(RelationEditorVM vm, bool isNew)
        {
            var val = new Validator();

            vm.SourceIds = vm.SourceIds ?? new Guid[0];

            var pageIds = vm.SourceIds
                          .Concat(new [] { vm.DestinationId ?? Guid.Empty, vm.EventId ?? Guid.Empty })
                          .ToList();

            var pages = await _db.Pages
                        .Where(x => pageIds.Contains(x.Id))
                        .ToDictionaryAsync(x => x.Id, x => x.Type);

            var sourceTypes = vm.SourceIds.Select(x => pages.TryGetNullableValue(x)).ToList();
            var destType    = pages.TryGetNullableValue(vm.DestinationId ?? Guid.Empty);
            var eventType   = pages.TryGetNullableValue(vm.EventId ?? Guid.Empty);

            if (vm.SourceIds == null || vm.SourceIds.Length == 0)
            {
                val.Add(nameof(vm.SourceIds), "Выберите страницу");
            }
            else if (isNew == false && vm.SourceIds.Length > 1)
            {
                val.Add(nameof(vm.SourceIds), "При редактировании может быть указана только одна страница");
            }
            else if (sourceTypes.Any(x => x == null))
            {
                val.Add(nameof(vm.SourceIds), "Страница не найдена");
            }

            if (vm.DestinationId == null)
            {
                val.Add(nameof(vm.DestinationId), "Выберите страницу");
            }
            else if (destType == null)
            {
                val.Add(nameof(vm.DestinationId), "Страница не найдена");
            }

            if (destType != null && sourceTypes.Any(x => x != null && !RelationHelper.IsRelationAllowed(x.Value, destType.Value, vm.Type)))
            {
                val.Add(nameof(vm.Type), "Тип связи недопустимм для данных страниц");
            }

            if (vm.EventId != null)
            {
                if (eventType == null)
                {
                    val.Add(nameof(vm.EventId), "Страница не найдена");
                }
                else if (eventType != PageType.Event)
                {
                    val.Add(nameof(vm.EventId), "Требуется страница события");
                }
                else if (!RelationHelper.IsRelationEventReferenceAllowed(vm.Type))
                {
                    val.Add(nameof(vm.EventId), "Событие нельзя привязать к данному типу связи");
                }
            }

            if (!string.IsNullOrEmpty(vm.DurationStart) || !string.IsNullOrEmpty(vm.DurationEnd))
            {
                if (!RelationHelper.IsRelationDurationAllowed(vm.Type))
                {
                    val.Add(nameof(vm.DurationStart), "Дату нельзя указать для данного типа связи");
                }
                else
                {
                    var from = FuzzyDate.TryParse(vm.DurationStart);
                    var to   = FuzzyDate.TryParse(vm.DurationEnd);

                    if (from > to)
                    {
                        val.Add(nameof(vm.DurationStart), "Дата начала не может быть больше даты конца");
                    }
                    else if (FuzzyRange.TryParse(FuzzyRange.TryCombine(vm.DurationStart, vm.DurationEnd)) == null)
                    {
                        val.Add(nameof(vm.DurationStart), "Введите дату в корректном формате");
                    }
                }
            }

            var existingRelation = await _db.Relations
                                   .AnyAsync(x => vm.SourceIds.Contains(x.SourceId) &&
                                             x.DestinationId == vm.DestinationId &&
                                             x.Type == vm.Type &&
                                             x.Id != vm.Id);

            if (existingRelation)
            {
                val.Add(nameof(vm.DestinationId), "Такая связь уже существует!");
            }

            val.ThrowIfInvalid();
        }
Example #13
0
        public void AddMissingDataListItems(IList <IDataListVerifyPart> parts, bool async)
        {
            IList <IDataListItemModel> tmpRecsetList = new List <IDataListItemModel>();

            foreach (IDataListVerifyPart part in parts)
            {
                if (part.IsScalar)
                {
                    IDataListItemModel scalar = DataListItemModelFactory.CreateDataListModel(part.Field, part.Description, enDev2ColumnArgumentDirection.None);
                    ScalarCollection.Insert(ScalarCollection.Count - 1, scalar);
                    Validator.Add(scalar);
                }
                else
                {
                    IDataListItemModel recsetToAddTo = RecsetCollection.FirstOrDefault(c => c.Name == part.Recordset && c.IsRecordset);
                    IDataListItemModel tmpRecset     = tmpRecsetList.FirstOrDefault(c => c.Name == part.Recordset);

                    if (recsetToAddTo != null)
                    {
                        IDataListItemModel child = DataListItemModelFactory.CreateDataListModel(part.Field, part.Description, recsetToAddTo);
                        if (recsetToAddTo.Children.Count > 0)
                        {
                            recsetToAddTo.Children.Insert(recsetToAddTo.Children.Count - 1, child);
                        }
                        else
                        {
                            recsetToAddTo.Children.Add(child);
                        }
                        recsetToAddTo.Validator.Add(child);
                    }
                    else if (tmpRecset != null)
                    {
                        IDataListItemModel child = DataListItemModelFactory.CreateDataListModel(part.Field, part.Description, tmpRecset);
                        tmpRecset.Children.Add(child);
                        tmpRecset.Validator.Add(child);
                    }
                    else
                    {
                        IDataListItemModel recset = DataListItemModelFactory.CreateDataListModel(part.Recordset, part.Description, enDev2ColumnArgumentDirection.None);
                        tmpRecsetList.Add(recset);
                    }
                }
            }
            foreach (IDataListItemModel item in tmpRecsetList)
            {
                if (item.Children.Count == 0)
                {
                    item.Children.Add(DataListItemModelFactory.CreateDataListModel(string.Empty, string.Empty, item));
                }
                if (RecsetCollection.Count > 0)
                {
                    RecsetCollection.Insert(RecsetCollection.Count - 1, item);
                }
                else
                {
                    RecsetCollection.Add(item);
                }
                Validator.Add(item);
            }

            WriteToResourceModel();
            Mediator.SendMessage(MediatorMessages.UpdateIntelisense, this);
            RemoveBlankScalars();
            RemoveBlankRecordsets();
            RemoveBlankRecordsetFields();
            AddBlankRow(null);
        }
Example #14
0
 /// <summary>
 /// Add equality validator
 /// </summary>
 /// <param name="prev"></param>
 /// <param name="selector"></param>
 /// <param name="expected"></param>
 /// <param name="detail"></param>
 /// <typeparam name="TSource"></typeparam>
 /// <typeparam name="TTarget"></typeparam>
 /// <typeparam name="TDetail"></typeparam>
 /// <returns></returns>
 public static Validator <TSource, TDetail> AddEquals <TSource, TTarget, TDetail>(
     this Validator <TSource, TDetail> prev, Func <TSource, TTarget> selector, TTarget expected, TDetail detail)
 {
     return(prev.Add(source => selector(source).Equals(expected), detail));
 }
Example #15
0
 /// <summary>
 /// Add equality validator
 /// </summary>
 /// <param name="prev"></param>
 /// <param name="expected"></param>
 /// <param name="detail"></param>
 /// <typeparam name="TSource"></typeparam>
 /// <typeparam name="TDetail"></typeparam>
 /// <returns></returns>
 public static Validator <TSource, TDetail> AddEquals <TSource, TDetail>(this Validator <TSource, TDetail> prev,
                                                                         TSource expected, TDetail detail)
 {
     return(prev.Add(source => source.Equals(expected), detail));
 }