public SaveResult <BTSEntryModel> Save(BTSDTO btsDTO, DateTime dateStamp) { ModelValidationResult validationResult = btsValidator.Validate(btsDTO); bool success = false; BTSEntryModel model = null; if (validationResult.IsValid) { tblM_BTS bts = AddBTS(btsDTO, dateStamp); Db.SaveChanges(); btsDTO.BTS_PK = bts.BTS_PK; AddBTSTechnologies(btsDTO, dateStamp); Db.SaveChanges(); success = true; model = btsEntryDataProvider.Get(bts.BTS_PK); } return(new SaveResult <BTSEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public void ValidateReturnsSingleValidationResultIfOneMemberNameIsSpecified() { // Arrange const string errorMessage = "A different error message"; ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType( () => new object(), typeof(object) ); ControllerContext context = new ControllerContext(); Mock <ValidationAttribute> attribute = new Mock <ValidationAttribute> { CallBase = true }; attribute .Protected() .Setup <ValidationResult>( "IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>() ) .Returns(new ValidationResult(errorMessage, new[] { "FirstName" })); var validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object); // Act IEnumerable <ModelValidationResult> results = validator.Validate(container: null); // Assert ModelValidationResult validationResult = Assert.Single(results); Assert.Equal(errorMessage, validationResult.Message); Assert.Equal("FirstName", validationResult.MemberName); }
private static ModelValidationResult ValidateNode(object?instance, string path, ModelValidationResult result, HashSet <object> visited) { if (instance is null || !IsComplex(instance.GetType()) || visited.Contains(instance)) { return(result); } visited.Add(instance); foreach (var property in instance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyPath = AppendProperty(path, property.Name); var value = property.GetValue(instance); foreach (var attribute in property.GetCustomAttributes <ValidationAttribute>(true)) { if (!attribute.IsValid(value)) { result.AddError(propertyPath, attribute.FormatErrorMessage(property.Name)); } } if (value is IEnumerable enumerable && IsComplex(property.PropertyType) && typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) { ValidateCollection(enumerable, propertyPath, result, visited); }
public void OnModelPropertyValidated(object sender, OnPropertyValidatedEventArgs e) { // immediate throw // temporary solution due to multiple provision of the same model //if (!e.Result.IsValid) //{ // throw new ContainerValidationResultException // { // Args = e, // Definition = e.Result.Tag as DefinitionBase // }; //} var existingModelResult = ModelValidations.FirstOrDefault(r => r.Model == e.Result.Tag); if (existingModelResult == null) { existingModelResult = new ModelValidationResult { Model = e.Result.Tag as DefinitionBase }; ModelValidations.Add(existingModelResult); } existingModelResult.Properties.Add(e.Result); }
public static async Task EnsureSuccessWithValidationSupportAsync(this HttpResponseMessage response) { // If BadRequest, see if it contains a validation payload if (response.StatusCode == HttpStatusCode.BadRequest) { ModelValidationResult result = null; try { var responseContent = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <ModelValidationResult>(responseContent); } catch { // Fall through logic will take care of it } if (result != null) { throw new ModelValidationException(result); } } if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(); } response.EnsureSuccessStatusCode(); // Will throw for any other service call errors }
public void Validate_ReturnsMemberName_IfItIsDifferentFromDisplayName() { // Arrange var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel)); var model = new SampleModel(); var attribute = new Mock<TestableValidationAttribute> { CallBase = true }; attribute .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>())) .Returns(new ValidationResult("Name error", new[] { "Name" })); var validator = new DataAnnotationsModelValidator( new ValidationAttributeAdapterProvider(), attribute.Object, stringLocalizer: null); var validationContext = new ModelValidationContext( actionContext: new ActionContext(), modelMetadata: metadata, metadataProvider: _metadataProvider, container: null, model: model); // Act var results = validator.Validate(validationContext); // Assert ModelValidationResult validationResult = Assert.Single(results); Assert.Equal("Name", validationResult.MemberName); }
public void ValidateReturnsMemberNameIfItIsDifferentFromDisplayName() { // Arrange ModelMetadata metadata = _metadataProvider.GetMetadataForType( () => new SampleModel(), typeof(SampleModel) ); Mock <ValidationAttribute> attribute = new Mock <ValidationAttribute> { CallBase = true }; attribute .Protected() .Setup <ValidationResult>( "IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>() ) .Returns(new ValidationResult("Name error", new[] { "Name" })); DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator( _noValidatorProviders, attribute.Object ); // Act IEnumerable <ModelValidationResult> results = validator.Validate( metadata, container: null ); // Assert ModelValidationResult validationResult = Assert.Single(results); Assert.Equal("Name", validationResult.MemberName); }
public void Validate_ReturnsSingleValidationResult_IfOneMemberNameIsSpecified() { // Arrange const string errorMessage = "A different error message"; var metadata = _metadataProvider.GetMetadataForType(typeof(object)); var model = new object(); var attribute = new Mock<TestableValidationAttribute> { CallBase = true }; attribute .Setup(p => p.IsValidPublic(It.IsAny<object>(), It.IsAny<ValidationContext>())) .Returns(new ValidationResult(errorMessage, new[] { "FirstName" })); var validator = new DataAnnotationsModelValidator( new ValidationAttributeAdapterProvider(), attribute.Object, stringLocalizer: null); var validationContext = new ModelValidationContext( actionContext: new ActionContext(), modelMetadata: metadata, metadataProvider: _metadataProvider, container: null, model: model); // Act var results = validator.Validate(validationContext); // Assert ModelValidationResult validationResult = Assert.Single(results); Assert.Equal(errorMessage, validationResult.Message); Assert.Equal("FirstName", validationResult.MemberName); }
public SaveResult <BTSEntryModel> Save(BTSDTO btsDTO, DateTime dateStamp) { foreach (var item in btsDTO.BTSTechnologies) { item.BTS_FK = btsDTO.BTS_PK; } ModelValidationResult validationResult = btsValidator.Validate(btsDTO); bool success = false; BTSEntryModel model = null; if (validationResult.IsValid) { success = true; UpdateBTS(btsDTO, dateStamp); UpdateBTSTechnologies(btsDTO, dateStamp); Db.SaveChanges(); model = btsEntryDataProvider.Get(btsDTO.BTS_PK); } return(new SaveResult <BTSEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully updated." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
private Response SaveSlackNotifications() { var settings = this.BindAndValidate <SlackNotificationSettings>(); if (!ModelValidationResult.IsValid) { return(Response.AsJson(ModelValidationResult.SendJsonError())); } var result = SlackSettings.SaveSettings(settings); if (settings.Enabled) { NotificationService.Subscribe(new SlackNotification(SlackApi, SlackSettings)); } else { NotificationService.UnSubscribe(new SlackNotification(SlackApi, SlackSettings)); } Log.Info("Saved slack settings, result: {0}", result); return(Response.AsJson(result ? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for Slack Notifications!" } : new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." })); }
private async Task <Response> SaveDiscordNotifications() { var settings = this.BindAndValidate <DiscordNotificationSettings>(); if (!ModelValidationResult.IsValid) { return(Response.AsJson(ModelValidationResult.SendJsonError())); } var result = await DiscordSettings.SaveSettingsAsync(settings); if (settings.Enabled) { NotificationService.Subscribe(new DiscordNotification(DiscordApi, DiscordSettings)); } else { NotificationService.UnSubscribe(new DiscordNotification(DiscordApi, DiscordSettings)); } Log.Info("Saved discord settings, result: {0}", result); return(Response.AsJson(result ? new JsonResponseModel { Result = true, Message = "Successfully Updated the Settings for Discord Notifications!" } : new JsonResponseModel { Result = false, Message = "Could not update the settings, take a look at the logs." })); }
public void ValidateReturnsSingleValidationResultIfMemberNameSequenceIsEmpty() { // Arrange const string errorMessage = "Some error message"; ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty( () => 15, typeof(string), "Length" ); ControllerContext context = new ControllerContext(); Mock <ValidationAttribute> attribute = new Mock <ValidationAttribute> { CallBase = true }; attribute .Protected() .Setup <ValidationResult>( "IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>() ) .Returns(new ValidationResult(errorMessage, memberNames: null)); var validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object); // Act IEnumerable <ModelValidationResult> results = validator.Validate(container: null); // Assert ModelValidationResult validationResult = Assert.Single(results); Assert.Equal(errorMessage, validationResult.Message); Assert.Empty(validationResult.MemberName); }
private void AssertIsNotValid(ModelValidationResult result, int count) { Assert.That(result, Is.Not.Null); Assert.That(result.IsValid, Is.False); Assert.That(result.InvalidProperties, Is.Not.Null); Assert.That(result.InvalidProperties.Count, Is.EqualTo(count)); }
private void AssertIsValid(ModelValidationResult model) { Assert.That(model, Is.Not.Null); Assert.That(model.IsValid, Is.True); Assert.That(model.InvalidProperties, Is.Not.Null); Assert.That(model.InvalidProperties.Count, Is.EqualTo(0)); }
public void PropertyValidator_Validate_IDataErrorInfoContainerWithError() { // Arrange DataErrorInfo1 container = new DataErrorInfo1(); container["SomeStringProperty"] = "This is an error message."; ModelMetadata metadata = _metadataProvider.GetMetadataForProperty( () => container, typeof(DataErrorInfo1), "SomeStringProperty" ); var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator( metadata, new ControllerContext() ); // Act ModelValidationResult[] result = validator.Validate(container).ToArray(); // Assert ModelValidationResult modelValidationResult = Assert.Single(result); Assert.Equal("This is an error message.", modelValidationResult.Message); }
/// <summary> /// Applies JSON patch operations on object and logs errors in <see cref="ModelStateDictionary"/>. /// </summary> /// <param name="patchDoc">The <see cref="JsonPatchDocument{T}"/>.</param> /// <param name="objectToApplyTo">The entity on which <see cref="JsonPatchDocument{T}"/> is applied.</param> /// <param name="modelValidationResult">The <see cref="ModelValidationResult"/> to add errors.</param> /// <param name="prefix">The prefix to use when looking up values in <see cref="ModelValidationResult"/>.</param> public static void ApplyTo <T>( this JsonPatchDocument <T> patchDoc, T objectToApplyTo, ModelValidationResult modelState, string prefix) where T : class { if (patchDoc == null) { throw new ArgumentNullException(nameof(patchDoc)); } if (objectToApplyTo == null) { throw new ArgumentNullException(nameof(objectToApplyTo)); } if (modelState == null) { throw new ArgumentNullException(nameof(modelState)); } patchDoc.ApplyTo(objectToApplyTo, jsonPatchError => { var affectedObjectName = jsonPatchError.AffectedObject.GetType().Name; var key = string.IsNullOrEmpty(prefix) ? affectedObjectName : prefix + "." + affectedObjectName; modelState.Errors.Add(key, jsonPatchError.ErrorMessage); }); }
protected async Task <TReturn> BaseInvokeCheckModelAsync <TReturn, TRequest>(TRequest request, Func <Task <TReturn> > func) where TReturn : BaseResult, new() { try { TrimStrings.Trim(request); ModelValidationResult modelValidationResult = ModelValidator.Validate(request); if (!modelValidationResult.Ok) { return(ResponseBuilder <TReturn> .Fail() .IsShowInfo(false) .SetErrors(modelValidationResult.Errors) .SetInfo("Model is not valid") .Build()); } return(await func()); } catch (Exception ex) { WriteLog(ex.Message); return(GetUnexpectedServerError <TReturn>(ex.StackTrace)); } }
public SaveResult <AreaEntryModel> Save(AreaDTO areaDTO, DateTime dateStamp) { ModelValidationResult validationResult = areaValidator.Validate(areaDTO); bool success = false; AreaEntryModel model = null; if (!validationResult.IsValid) { return(new SaveResult <AreaEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); } tblM_Area area = AddArea(areaDTO, dateStamp); Db.SaveChanges(); success = true; model = areaEntryDataProvider.Get(area.Area_PK); return(new SaveResult <AreaEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public SaveResult <MenuEntryModel> Save(MenuDTO menuDTO, DateTime dateStamp) { ModelValidationResult validationResult = menuValidator.Validate(menuDTO); bool success = false; MenuEntryModel model = null; if (!validationResult.IsValid) { return(new SaveResult <MenuEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); } tblM_Menu menu = AddMenu(menuDTO, dateStamp); Db.SaveChanges(); success = true; model = menuEntryDataProvider.Get(menu.Menu_PK); return(new SaveResult <MenuEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
private Response TestSlackNotification() { var settings = this.BindAndValidate <SlackNotificationSettings>(); if (!ModelValidationResult.IsValid) { return(Response.AsJson(ModelValidationResult.SendJsonError())); } var notificationModel = new NotificationModel { NotificationType = NotificationType.Test, DateTime = DateTime.Now }; try { NotificationService.Subscribe(new SlackNotification(SlackApi, SlackSettings)); settings.Enabled = true; NotificationService.Publish(notificationModel, settings); Log.Info("Sent slack notification test"); } catch (Exception e) { Log.Error(e, "Failed to subscribe and publish test Slack Notification"); } finally { NotificationService.UnSubscribe(new SlackNotification(SlackApi, SlackSettings)); } return(Response.AsJson(new JsonResponseModel { Result = true, Message = "Successfully sent a test Slack Notification! If you do not receive it please check the logs." })); }
/// <summary> /// When implemented in a derived class, validates the object. /// </summary> /// <param name="container">The container.</param> /// <returns> /// A list of validation results. /// </returns> public override IEnumerable <ModelValidationResult> Validate(object container) { var validator = (IValidatableObject)metadata.Model; var validationResults = validator.Validate(new ValidationContext(metadata.Model, null, null)); foreach (var validationResult in validationResults) { bool hasMemberNames = false; foreach (var memberName in validationResult.MemberNames) { hasMemberNames = true; var item = new ModelValidationResult { MemberName = memberName, Message = validationResult.ErrorMessage }; yield return(item); } if (!hasMemberNames) { yield return new ModelValidationResult { MemberName = string.Empty, Message = validationResult.ErrorMessage } } ; } } }
public SaveResult <POEntryModel> Save(PODTO pODTO, DateTime dateStamp) { if (pODTO.Status_FK == 0) { pODTO.Status_FK = 1; } ModelValidationResult validationResult = POValidator.Validate(pODTO); bool success = false; POEntryModel model = null; if (validationResult.IsValid) { tblT_PO po = Insert(pODTO, dateStamp); Db.SaveChanges(); pODTO.PO_PK = po.PO_PK; success = true; model = POEntryDataProvider.Get(pODTO.PO_PK); } return(new SaveResult <POEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public SaveResult <UserEntryModel> Save(UpdatePasswordDTO updatePasswordDTO, DateTime dateStamp) { var passwordHasher = new MD5PasswordHasher(); var user = Db.tblM_User.Find(User.User_PK); ModelValidationResult validationResult = validator.Validate(updatePasswordDTO); bool success = false; UserEntryModel model = null; if (validationResult.IsValid) { var hashedCurrentPassword = passwordHasher.Hash(updatePasswordDTO.CurrentPassword); if (hashedCurrentPassword != user.Password) { throw new Kairos.KairosException("Wrong current password."); } var hashedNewPassword = passwordHasher.Hash(updatePasswordDTO.NewPassword); user.Password = hashedNewPassword; Db.SaveChanges(); } return(new SaveResult <UserEntryModel> { Success = success, Message = validationResult.IsValid ? "Password has been changed." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public SaveResult <TipePekerjaanEntryModel> Save(TipePekerjaanDTO tipePekerjaanDTO, DateTime dateStamp) { ModelValidationResult validationResult = tipePekerjaanValidator.Validate(tipePekerjaanDTO); bool success = false; TipePekerjaanEntryModel model = null; if (!validationResult.IsValid) { return(new SaveResult <TipePekerjaanEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); } tblM_TipePekerjaan tipePekerjaan = AddTipePekerjaan(tipePekerjaanDTO, dateStamp); Db.SaveChanges(); success = true; model = tipePekerjaanEntryDataProvider.Get(tipePekerjaan.TipePekerjaan_PK); return(new SaveResult <TipePekerjaanEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public SaveResult <SOWEntryModel> Save(SOWDTO sowDTO, DateTime dateStamp) { ModelValidationResult validationResult = sowValidator.Validate(sowDTO); bool success = false; SOWEntryModel model = null; if (validationResult.IsValid) { tblT_SOW sow = Insert(sowDTO, dateStamp); SaveChanges(); sowDTO.SOW_PK = sow.SOW_PK; AddSowAssign(sowDTO, dateStamp); AddSowTrack(sowDTO, dateStamp); SaveChanges(); success = true; model = sowEntryDataProvider.Get(sow.SOW_PK); } return(new SaveResult <SOWEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public void ClassValidator_Validate_IDataErrorInfoModelWithError() { // Arrange DataErrorInfo1 model = new DataErrorInfo1() { Error = "This is an error message." }; ModelMetadata metadata = _metadataProvider.GetMetadataForType( () => model, typeof(DataErrorInfo1) ); var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoClassModelValidator( metadata, new ControllerContext() ); // Act ModelValidationResult[] result = validator.Validate(null).ToArray(); // Assert ModelValidationResult modelValidationResult = Assert.Single(result); Assert.Equal("This is an error message.", modelValidationResult.Message); }
public SaveResult <UserEntryModel> Save(UserDTO userDTO, DateTime dateStamp) { ModelValidationResult validationResult = userValidator.Validate(userDTO); bool success = false; UserEntryModel model = null; if (validationResult.IsValid) { UserDetailCreateHandler userDetailCreateHandler = new UserDetailCreateHandler(Db, User, new UserDetailValidator(), new UserDetailFactory(Db, User), new UserDetailQuery(), accessControl); var userDetailSaveResult = userDetailCreateHandler.Save(userDTO, dateStamp); if (userDetailSaveResult.Success) { userDTO.UserDetail_FK = userDetailSaveResult.Model.Model.UserDetail_PK; tblM_User user = Insert(userDTO, dateStamp); Db.SaveChanges(); success = true; model = userEntryDataProvider.Get(user.User_PK); } } return(new SaveResult <UserEntryModel> { Success = success, Message = validationResult.IsValid ? "Data successfully created." : "Validation error occured.", Model = model, ValidationResult = validationResult }); }
public override IEnumerable <ModelValidationResult> Validate( ModelMetadata metadata, object container ) { string memberName; if (_useLegacyValidationMemberName) { // Using member name from a Display or DisplayFormat attribute is generally incorrect. This // (configuration-controlled) override is provided only for corner cases where strict // back-compatibility is required. memberName = metadata.GetDisplayName(); } else { // MemberName expression matches GetDisplayName() except it ignores Display and DisplayName // attributes. ModelType fallback isn't great and can separate errors and attempted values in the // ModelState. But, expression matches MVC, avoids a null MemberName, and is mostly back-compatible. memberName = metadata.PropertyName ?? metadata.ModelType.Name; } // Per the WCF RIA Services team, instance can never be null (if you have // no parent, you pass yourself for the "instance" parameter). ValidationContext context = new ValidationContext(instance: container ?? metadata.Model) { DisplayName = metadata.GetDisplayName(), MemberName = memberName, }; ValidationResult result = Attribute.GetValidationResult(metadata.Model, context); if (result != ValidationResult.Success) { // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidationNode) to // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append the // returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want // (person.Name.Name). However the invoking validator does not have a way to distinguish between these two // cases. Consequently we'll only set MemberName if this validation returns a MemberName that is different // from the property being validated. string errorMemberName = result.MemberNames.FirstOrDefault(); if (String.Equals(errorMemberName, memberName, StringComparison.Ordinal)) { errorMemberName = null; } var validationResult = new ModelValidationResult { Message = result.ErrorMessage, MemberName = errorMemberName }; return(new ModelValidationResult[] { validationResult }); } return(Enumerable.Empty <ModelValidationResult>()); }
public static string GetDetailedErrorMessage(this ModelValidationResult modelValidationResult) { var formattedErrors = modelValidationResult.Errors .Select(x => new { Key = x.Key, Errors = x.Value.Select(y => y.ErrorMessage) }) .Select(x => $"Parameter = {x.Key}, Errors = ({string.Join(", ", x.Errors)})"); return($"Validation failed for Request Parameters: ({string.Join(", ", formattedErrors)})"); }
public void MemberNameProperty() { // Arrange ModelValidationResult result = new ModelValidationResult(); // Act & assert MemberHelper.TestStringProperty(result, "MemberName", String.Empty); }
public void MessageProperty() { // Arrange ModelValidationResult result = new ModelValidationResult(); // Act & assert MemberHelper.TestStringProperty(result, "Message", String.Empty); }
public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container) { // Per the WCF RIA Services team, instance can never be null (if you have // no parent, you pass yourself for the "instance" parameter). string memberName = metadata.GetDisplayName(); ValidationContext context = new ValidationContext(container ?? metadata.Model) { DisplayName = memberName, MemberName = memberName }; ValidationResult result = Attribute.GetValidationResult(metadata.Model, context); if (result != ValidationResult.Success) { // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidationNode) to // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append the // returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want // (person.Name.Name). However the invoking validator does not have a way to distinguish between these two // cases. Consequently we'll only set MemberName if this validation returns a MemberName that is different // from the property being validated. string errorMemberName = result.MemberNames.FirstOrDefault(); if (String.Equals(errorMemberName, memberName, StringComparison.Ordinal)) { errorMemberName = null; } var validationResult = new ModelValidationResult { Message = result.ErrorMessage, MemberName = errorMemberName }; return new ModelValidationResult[] { validationResult }; } return Enumerable.Empty<ModelValidationResult>(); }
// If any Model rules broken, set SelectedCommonDataType Errors collection // which are data bound to UI error textblocks. private void DisplayEntityErrorMessages(ModelValidationResult modelValidationResult) { var entityUpdateErrors = new Dictionary<string, ReadOnlyCollection<string>>(); // Property keys format: address.{Propertyname} foreach (var propkey in modelValidationResult.ModelState.Keys) { string propertyName = propkey.Substring(propkey.IndexOf('.') + 1); // strip off order. prefix // 'modelValidationResults.ModelState[propkey]' is the collection of string error messages // for the property. Later on in UILayer, FirstErrorConverter will display the one of the collection. // 'propertyName' will only occur once for each property in the Model so a new ReadOnlyCollection // can be created on each pass of the foreach loop. entityUpdateErrors.Add(propertyName, new ReadOnlyCollection<string>(modelValidationResult.ModelState[propkey])); } if (entityUpdateErrors.Count > 0) { SelectedEntity.Errors.SetAllErrors(entityUpdateErrors); } }