public UserService(ModelStateDictionary modelState, 
     IUserRepository userRepository, IRoleRepository roleRepository)
 {
     _modelState = modelState;
     _users = userRepository;
     _roles = roleRepository;
 }
        // Cannot use 'SerializableError' here as 'RequiredAttribute' validation errors are added as exceptions
        // into the model state dictionary and 'SerializableError' sanitizes exceptions with generic error message.
        // Since the tests need to verify the messages, we are doing the following.
        private List<string> GetModelStateErrorMessages(ModelStateDictionary modelStateDictionary)
        {
            var allErrorMessages = new List<string>();
            foreach (var keyModelStatePair in modelStateDictionary)
            {
                var key = keyModelStatePair.Key;
                var errors = keyModelStatePair.Value.Errors;
                if (errors != null && errors.Count > 0)
                {
                    string errorMessage = null;
                    foreach (var modelError in errors)
                    {
                        if (string.IsNullOrEmpty(modelError.ErrorMessage))
                        {
                            if (modelError.Exception != null)
                            {
                                errorMessage = modelError.Exception.Message;
                            }
                        }
                        else
                        {
                            errorMessage = modelError.ErrorMessage;
                        }

                        if (errorMessage != null)
                        {
                            allErrorMessages.Add(string.Format("{0}:{1}", key, errorMessage));
                        }
                    }
                }
            }

            return allErrorMessages;
        }
        public async Task BindPropertyFromService_WithData_WithEmptyPrefix_GetsBound()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "Parameter1",
                BindingInfo = new BindingInfo(),
                ParameterType = typeof(Person)
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert

            // ModelBindingResult
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType<Person>(modelBindingResult.Model);
            Assert.NotNull(boundPerson);
            Assert.NotNull(boundPerson.Address.OutputFormatter);

            // ModelState
            Assert.True(modelState.IsValid);

            // For non user bound models there should be no entry in model state.
            Assert.Empty(modelState);
        }
        public async Task KeyValuePairModelBinder_SimpleTypes_WithNoKey_AddsError()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor
            {
                Name = "parameter",
                ParameterType = typeof(KeyValuePair<string, int>)
            };
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = new QueryString("?parameter.Value=10");
            });
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.False(modelBindingResult.IsModelSet);
            Assert.Equal(2, modelState.Count);

            Assert.False(modelState.IsValid);
            Assert.Equal(1, modelState.ErrorCount);

            var entry = Assert.Single(modelState, kvp => kvp.Key == "parameter.Key").Value;
            var error = Assert.Single(entry.Errors);
            Assert.Null(error.Exception);
            Assert.Equal("A value is required.", error.ErrorMessage);

            entry = Assert.Single(modelState, kvp => kvp.Key == "parameter.Value").Value;
            Assert.Empty(entry.Errors);
            Assert.Equal("10", entry.AttemptedValue);
            Assert.Equal("10", entry.RawValue);
        }
		internal void AddErrorsToModelState(IEnumerable<DbEntityValidationResult> errors, ModelStateDictionary state)
		{
			foreach (var val in errors)
			{
				AddErrorsToModelState(val, state);
			}
		}
Example #6
0
 public static bool ShowErrorMessage( this HtmlForm form, ModelStateDictionary modelStates, Func<IHtmlInputControl, IHtmlElement> inputControlFinder )
 {
     return new GenericMvcFormValidator( form, modelStates )
       {
     InputControlFinder = inputControlFinder
       }.ShowErrorMessage();
 }
        public ModelStateException(ModelStateDictionary modelState)
        {
            if (modelState == null)
            {
                throw new ArgumentNullException("modelState");
            }

            Errors = new Dictionary<string, string>();

            if (!modelState.IsValid)
            {
                StringBuilder errors;
                foreach (KeyValuePair<string, ModelState> state in modelState)
                {
                    if (state.Value.Errors.Count > 0)
                    {
                        errors = new StringBuilder();
                        foreach (ModelError err in state.Value.Errors)
                        {
                            errors.AppendLine(err.ErrorMessage);
                        }
                        Errors.Add(state.Key, errors.ToString());
                    }
                }
            }
        }
Example #8
0
        public void StartRegistrationForFamilyMember(int id, ModelStateDictionary modelState)
        {
            modelState.Clear(); // ensure we pull form fields from our model, not MVC's
            HistoryAdd("Register");
            int index = List.Count - 1;
            var p = LoadExistingPerson(id, index);

            if(p.NeedsToChooseClass())
                return;

            p.ValidateModelForFind(modelState, id, selectFromFamily: true);
            if (!modelState.IsValid)
                return;

            List[index] = p;

            if (p.ManageSubscriptions() && p.Found == true)
                return;

            if (p.org != null && p.Found == true)
            {
                if (!SupportMissionTrip)
                    p.IsFilled = p.org.RegLimitCount(DbUtil.Db) >= p.org.Limit;
                if (p.IsFilled)
                    modelState.AddModelError(this.GetNameFor(mm => mm.List[List.IndexOf(p)].Found),
                        "Sorry, but registration is filled.");
                if (p.Found == true)
                    p.FillPriorInfo();
                return;
            }
            if (p.org == null && p.ComputesOrganizationByAge())
                modelState.AddModelError(this.GetNameFor(mm => mm.List[id].Found), p.NoAppropriateOrgError);
        }
Example #9
0
 public static void MapBrokenRules(ModelStateDictionary modelState, Csla.Core.BusinessBase businessObject)
 {
     foreach (var brokenRule in businessObject.BrokenRulesCollection)
     {
         modelState.AddModelError(brokenRule.Property, brokenRule.Description);
     }
 }
        public void Validate_SimpleReferenceType_Valid_WithPrefix()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)"test";

            modelState.SetModelValue("parameter", "test", "test");
            validationState.Add(model, new ValidationStateEntry() { Key = "parameter" });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, "parameter", model);

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "parameter");

            var entry = modelState["parameter"];
            Assert.Equal(ModelValidationState.Valid, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
        public void Validate_SimpleType_MaxErrorsReached()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator();

            var model = (object)"test";

            modelState.MaxAllowedErrors = 1;
            modelState.AddModelError("other.Model", "error");
            modelState.SetModelValue("parameter", "test", "test");
            validationState.Add(model, new ValidationStateEntry() { Key = "parameter" });

            // Act
            validator.Validate(validatorProvider, modelState, validationState, "parameter", model);

            // Assert
            Assert.False(modelState.IsValid);
            AssertKeysEqual(modelState, string.Empty, "parameter");

            var entry = modelState["parameter"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
        public async Task GenericModelBinder_BindsCollection_ElementTypeFromGreedyModelBinder_EmptyPrefix_Success()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "parameter",
                ParameterType = typeof(List<IFormCollection>)
            };
            // Need to have a key here so that the GenericModelBinder will recurse to bind elements.
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.QueryString = new QueryString("?index=10");
            });

            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert
            Assert.NotNull(modelBindingResult);
            Assert.True(modelBindingResult.IsModelSet);

            var model = Assert.IsType<List<IFormCollection>>(modelBindingResult.Model);
            Assert.Equal(1, model.Count);
            Assert.NotNull(model[0]);

            Assert.Equal(0, modelState.Count);
            Assert.Equal(0, modelState.ErrorCount);
            Assert.True(modelState.IsValid);
        }
        public async Task InvalidModelStateResult_WritesHttpError()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = CreateServices();

            var stream = new MemoryStream();
            httpContext.Response.Body = stream;

            var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            var modelState = new ModelStateDictionary();
            modelState.AddModelError("product.Name", "Name is required.");

            var expected =
                "{\"Message\":\"The request is invalid.\"," +
                "\"ModelState\":{\"product.Name\":[\"Name is required.\"]}}";

            var result = new InvalidModelStateResult(modelState, includeErrorDetail: false);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(0, SeekOrigin.Begin);
                var content = reader.ReadToEnd();
                Assert.Equal(expected, content);
            }
        }
 internal static HtmlHelper Create(ModelStateDictionary modelStateDictionary = null, ValidationHelper validationHelper = null)
 {
     modelStateDictionary = modelStateDictionary ?? new ModelStateDictionary();
     var httpContext = new Mock<HttpContextBase>();
     validationHelper = validationHelper ?? new ValidationHelper(httpContext.Object, modelStateDictionary);
     return new HtmlHelper(modelStateDictionary, validationHelper);
 }
        public async Task BindParameter_WithModelBinderType_NoData_ReturnsNull()
        {
            // Arrange
            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder();
            var parameter = new ParameterDescriptor()
            {
                Name = "Parameter1",
                BindingInfo = new BindingInfo()
                {
                    BinderType = typeof(NullModelNotSetModelBinder)
                },

                ParameterType = typeof(string)
            };

            // No data is passed.
            var operationContext = ModelBindingTestHelper.GetOperationBindingContext();
            var modelState = new ModelStateDictionary();

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, modelState, operationContext);

            // Assert

            // ModelBindingResult
            Assert.Null(modelBindingResult);

            // ModelState (not set unless inner binder sets it)
            Assert.True(modelState.IsValid);
            Assert.Empty(modelState);
        }
Example #16
0
        public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails()
        {
            // Arrange
            var binders = new IModelBinder[]
            {
                new TypeConverterModelBinder(),
                new ComplexModelDtoModelBinder(),
                new MutableObjectModelBinder()
            };

            var validator = new DataAnnotationsModelValidatorProvider();
            var model = new MyModel();
            var modelStateDictionary = new ModelStateDictionary();
            var values = new Dictionary<string, object>
            {
                { "", null }
            };
            var valueProvider = new DictionaryBasedValueProvider(values);

            // Act
            var result = await ModelBindingHelper.TryUpdateModelAsync(
                                                    model,
                                                    "",
                                                    Mock.Of<HttpContext>(),
                                                    modelStateDictionary,
                                                    new DataAnnotationsModelMetadataProvider(),
                                                    GetCompositeBinder(binders),
                                                    valueProvider,
                                                    new[] { validator });

            // Assert
            Assert.False(result);
            Assert.Equal("The MyProperty field is required.",
                         modelStateDictionary["MyProperty"].Errors[0].ErrorMessage);
        }
Example #17
0
        public void Validate(ModelStateDictionary mdlState)
        {
            base.Validate();

            foreach (var tags in _nameTags)
            {
                var error = tags.Value.ValidationError;
                if (error != null)
                {
                    var strError = string.Join(", ", error.Errors);
                    if (!string.IsNullOrWhiteSpace(strError))
                    {
                        if (tags.Value is DataObjectViewModel)
                        {
                            // Special case DatObject: remove any key
                            mdlState.AddModelError("", strError);
                        }
                        else
                        {
                            mdlState.AddModelError(tags.Key, strError);
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseTestBuilderWithModelError"/> class.
 /// </summary>
 /// <param name="testContext"><see cref="ActionTestContext"/> containing data about the currently executed assertion chain.</param>
 /// <param name="modelState">Optional <see cref="ModelStateDictionary"/> to use the test builder with. Default is controller's <see cref="ModelStateDictionary"/>.</param>
 protected BaseTestBuilderWithModelError(
     ActionTestContext testContext,
     ModelStateDictionary modelState = null)
     : base(testContext)
 {
     this.ModelState = modelState ?? testContext.ModelState;
 }
Example #19
0
 public static void AddErrorsToModelState(ModelStateDictionary modelState, IEnumerable<ValidationError> errors, string parameterName)
 {
     foreach(ValidationError invalidValue in errors)
     {
         modelState.AddModelError(parameterName + "." + invalidValue.PropertyPath, invalidValue.Message);
     }
 }
        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var logger = GetLogger();
            var formatter = new JsonPatchInputFormatter(logger);
            var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
                "{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
            Assert.Equal("remove", patchDoc.Operations[1].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
        }
Example #21
0
	    public Order OrderFromCheckoutViewData(CheckoutViewData checkoutViewData, ModelStateDictionary modelState)
	    {
            if (EmailAddressesDoNotMatch(checkoutViewData, modelState)) return null;

            var basket = basketRepository.GetById(checkoutViewData.BasketId);
            userService.CurrentUser.EnsureCanView(basket);

            var order = new Order
            {
                Email = checkoutViewData.Email,
                AdditionalInformation = checkoutViewData.AdditionalInformation,
                ContactMe = checkoutViewData.ContactMe,
                Card = GetCardFromViewData(checkoutViewData, modelState),
                CardContact = GetCardContactFromViewData(checkoutViewData, modelState),
                CreatedDate = DateTime.Now,
                DeliveryContact = GetDeliveryContactFromViewData(checkoutViewData, modelState),
                DispatchedDate = DateTime.Now,
                OrderStatus = OrderStatus.Pending,
                UseCardHolderContact = checkoutViewData.UseCardholderContact,
                PayByTelephone = checkoutViewData.PayByTelephone,
                User = userService.CurrentUser
            };

            AddOrderLinesFromBasket(order, basket);
	        CalcuatePostage(order, basket);
            return order;
        }
Example #22
0
        public ModelStateDictionary SendEmails(DefaultContext db)
        {
            var modelStateDictionary = new ModelStateDictionary();
            UserProfile[] userProfiles = UserProfileCache.GetIndex(db);
            bool success = true;
            foreach (UserProfile userProfile in userProfiles.Where(up => !String.IsNullOrEmpty(up.Email1)))
            {
                bool partialSuccess = Mail.SendEmail(userProfile.Email1, Subject, Body, true, true);
                if (partialSuccess)
                {
                    string logMessage = String.Format("Email for user {0} with address {1} was successfully sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetLog(logMessage);
                }
                else
                {
                    string errorMessage = String.Format("Email for user {0} with address {1} was not sent.", userProfile.FullName, userProfile.Email1);
                    Logger.SetErrorLog(errorMessage);
                }

                success &= partialSuccess;
            }

            if (!success)
            {
                modelStateDictionary.AddModelError(BaseCache.EmptyField, ValidationResource.BulkMail_SomeEmailWasNotSent_ErrorMessage);
            }

            return modelStateDictionary;
        }
Example #23
0
        public JsonData(ModelStateDictionary modelDic)
            : this()
        {
            List<string> errorList = new List<string>();
            List<string> keyList = new List<string>();
            List<int> errorIndexList = new List<int>();

            int i = 0;
            foreach (ModelState state in modelDic.Values) {
                if (state.Errors.Count > 0) {
                    string error = state.Errors[0].ErrorMessage;
                    errorList.Add(error);
                    errorIndexList.Add(i);
                }
                i++;
            }

            int j = 0;
            foreach (string key in modelDic.Keys) {
                if (errorIndexList.Any(x => x == j)) {
                    keyList.Add(key.Replace(".", "_"));
                }
                j++;
            }

            for (int x = 0; x <= errorList.Count - 1; x++) {
                ErrorList.Add(new FormFiledError(keyList[x], errorList[x]));
            }

            if (errorList.Count > 0) this.HasFormError = true;
        }
        public bool Update(UsersExt model, ModelStateDictionary modelState, Controller ctrl)
        {
            bool status = true;
            //Wrap it all in a transaction
            TransactionOptions transOptions = SetTransactionTimeoutForDebugging(HttpContext.Current);

            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transOptions))
            {
                //if (db.tblUsers.Any(u => u.UserID != model.UserID && u.Username.ToLower().Equals(model.Username)))
                //{
                //    status = false;
                //    modelState.AddModelError("Username", "Username already Exists.");
                //}
                //else
                //{
                //    //TODO: Map to DB Object
                //    tblUsers tbluser = Map(model);

                //    tbluser.Password = SecurityUtils.EncryptText(tbluser.Password);

                //    db.tblUsers.Attach(tbluser);
                //    db.Entry(tbluser).State = System.Data.Entity.EntityState.Modified;
                //    db.SaveChanges();

                //    //TOD: Add to Audit Log
                //    SecurityUtils.AddAuditLog("User Details has been Updated. User FullName = " + model.Fullname, ctrl);

                //    //To get here, everything must be OK, so commit the transaction
                //    transaction.Complete();
                //}
            }

            return status;
        }
Example #25
0
 public virtual void Delete(SysEventViewModel sys, ModelStateDictionary modelState)
 {
     var entity = sys.ToEntity();
     db.SysEvents.Attach(entity);
     db.SysEvents.Remove(entity);
     db.SaveChanges();
 }
        public static string ModelStateToString(ModelStateDictionary modelState)
        {
            Contract.Assert(modelState != null);

            if (modelState.IsValid)
            {
                return String.Empty;
            }

            StringBuilder modelStateBuilder = new StringBuilder();
            foreach (string key in modelState.Keys)
            {
                ModelState state = modelState[key];
                if (state.Errors.Count > 0)
                {
                    foreach (ModelError error in state.Errors)
                    {
                        string errorString = Error.Format(SRResources.TraceModelStateErrorMessage, 
                                                           key,
                                                           error.ErrorMessage);
                        if (modelStateBuilder.Length > 0)
                        {
                            modelStateBuilder.Append(',');
                        }

                        modelStateBuilder.Append(errorString);
                    }
                }
            }

            return modelStateBuilder.ToString();
        }
        public bool Create(UsersExt model, ModelStateDictionary modelState, Controller ctrl)
        {
            bool status = true;
            //Wrap it all in a transaction

            TransactionOptions transOptions = SetTransactionTimeoutForDebugging(HttpContext.Current);

            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transOptions))
            {
                //if (db.tblUsers.Any(u => u.Username.ToLower().Equals(model.Username)))
                //{
                //    status = false;
                //    modelState.AddModelError("Username", "Username already Exists.");

                //}
                //else
                //{

                //    tblUsers tbluser = Map(model);

                //    tbluser.Password = SecurityUtils.EncryptText(tbluser.Password);

                //    db.tblUsers.Add(tbluser);
                //    db.SaveChanges();

                //    // UserID = tbluser.UserID;
                //    //Add to Audit Log
                //    SecurityUtils.AddAuditLog("User has been Added. User FullName = " + model.Fullname, ctrl);
                //    transaction.Complete();
                //}
            }
            return status;
        }
		public void ShouldCopyToModelState()
		{
			var modelstate = new ModelStateDictionary();

			const string property = "";

			var validator = new Validator
            {
            	() => property.Label("Property 1").IsRequired(),
            	() => property.Label("Property 2").IsRequired(),
            	() => property.Label("Property 3").IsRequired()
            };

			try
			{
				validator.Validate();
			}
			catch (ValidationException ex)
			{
				ex.CopyToModelState(modelstate, "foo");
			}

			modelstate.Count.ShouldEqual(3);
			modelstate["foo.Property 1"].ShouldNotBeNull();
			modelstate["foo.Property 2"].ShouldNotBeNull();
			modelstate["foo.Property 3"].ShouldNotBeNull();

		}
Example #29
0
        public void ValidateModelForNew(ModelStateDictionary modelstate, int i)
        {
            modelState = modelstate;
            Index = i;
            IsValidForNew = true; // Assume true until proven false
            IsValidForContinue = true; // Assume true until proven false

            ValidateBasic();
            ValidateBirthdate();
            if (!IsValidForNew)
                return;
            ValidateBirthdayRange(selectFromFamily: false);
            ValidatePhone();
            ValidateEmailForNew();
            if (!CanProceedWithThisAddress())
            {
                IsValidForContinue = false;
                return;
            }
            ValidateCampus();
            ValidateGender();
            ValidateMarital();
            ValidateMembership();
            IsValidForContinue = IsValidForNew = modelState.IsValid;
        }
 public static List<string> GetErrorList(ModelStateDictionary modelState)
 {
     var errorList = from state in modelState.Values
                     from error in state.Errors
                     select error.ErrorMessage;
     return errorList.ToList();
 }
 public ApiErrorResp(ModelStateDictionary modelState)
 {
     Errors = modelState.Values.SelectMany(modelErrorCollection => modelErrorCollection.Errors).Select(modelError => modelError.ErrorMessage);
 }
 public ModelStateDictionaryWrapper(ModelStateDictionary source)
 {
     _state = source;
 }
 protected BaseValidator(IUnitOfWork unitOfWork)
 {
     ModelState = new ModelStateDictionary();
     Alerts     = new AlertsContainer();
     UnitOfWork = unitOfWork;
 }
        public void EditProfilePostShouldReturnModelErrors(FakeSiteContext siteContext, ModelStateDictionary modelState, string profileItemId, IEnumerable <string> interests, [Substitute] EditProfile editProfile, IUserProfileService userProfileService)
        {
            var user = Substitute.For <User>("extranet/John", true);

            user.Profile.Returns(Substitute.For <UserProfile>());
            user.Profile.ProfileItemId = profileItemId;
            userProfileService.GetUserDefaultProfileId().Returns(profileItemId);
            userProfileService.GetInterests().Returns(interests);
            userProfileService.ValidateProfile(Arg.Any <EditProfile>(), Arg.Do <ModelStateDictionary>(x => x.AddModelError("key", "error"))).Returns(false);

            using (new SiteContextSwitcher(siteContext))
                using (new UserSwitcher(user))
                {
                    var accounController = new AccountsController(null, null, null, userProfileService);
                    var result           = accounController.EditProfile(editProfile);
                    result.Should().BeOfType <ViewResult>().Which.ViewData.ModelState.Should().ContainKey("key").WhichValue.Errors.Should().Contain(e => e.ErrorMessage == "error");
                }
        }
Example #35
0
        public static IEnumerable <string> Errors(this ModelStateDictionary modelState)
        {
            var allErrors = modelState.Values.SelectMany(v => v.Errors);

            return(allErrors.Select(e => e.ErrorMessage));
        }
Example #36
0
        public static async Task <byte[]> ProcessFormFile <T>(IFormFile formFile,
                                                              ModelStateDictionary modelState, IEnumerable <string> permittedExtensions,
                                                              long sizeLimit)
        {
            if (formFile == null)
            {
                throw new ArgumentNullException(nameof(formFile));
            }
            var fieldDisplayName = string.Empty;
            var property         = typeof(T).GetProperty(formFile.Name.Substring(formFile.Name.IndexOf(".", StringComparison.Ordinal) + 1));

            if (property != null)
            {
                if (property.GetCustomAttribute(typeof(DisplayAttribute)) is
                    DisplayAttribute displayAttribute)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            var trustedFileNameForDisplay = WebUtility.HtmlEncode(
                formFile.FileName);

            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");

                return(new byte[0]);
            }

            if (formFile.Length > sizeLimit)
            {
                var megabyteSizeLimit = sizeLimit / 1048576;
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) exceeds " +
                                         $"{megabyteSizeLimit:N1} MB.");

                return(new byte[0]);
            }

            try
            {
                await using var memoryStream = new MemoryStream();
                await formFile.CopyToAsync(memoryStream);

                if (memoryStream.Length == 0)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"{fieldDisplayName}({trustedFileNameForDisplay}) is empty.");
                }

                if (!IsValidFileExtensionAndSignature(
                        formFile.FileName, memoryStream, permittedExtensions))
                {
                    modelState.AddModelError(formFile.Name,
                                             $"{fieldDisplayName}({trustedFileNameForDisplay}) file " +
                                             "type isn't permitted or the file's signature " +
                                             "doesn't match the file's extension.");
                }
                else
                {
                    return(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                modelState.AddModelError(formFile.Name,
                                         $"{fieldDisplayName}({trustedFileNameForDisplay}) upload failed. " + $"Please contact the Help Desk for support. Error: {ex.HResult}");
            }

            return(new byte[0]);
        }
Example #37
0
 protected override InvalidModelStateResult BadRequest(ModelStateDictionary modelState)
 {
     return(base.BadRequest(modelState));
 }
Example #38
0
 public ModelStateWrapper(ModelStateDictionary modelState)
 {
     ModelState = modelState;
 }
 public ModelValidateFailResponse(ModelStateDictionary modelState)
 {
     this._modelState = modelState;
     this.code        = (int)HttpStatusCode.BadRequest;
     GenErrorMsg();
 }
        /// <summary>
        /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> representing an error
        /// with an instance of <see cref="ObjectContent{T}"/> wrapping an <see cref="HttpError"/> for model state <paramref name="modelState"/>.
        /// If no formatter is found, this method returns a response with status 406 NotAcceptable.
        /// </summary>
        /// <remarks>
        /// This method requires that <paramref name="request"/> has been associated with an instance of
        /// <see cref="HttpConfiguration"/>.
        /// </remarks>
        /// <param name="request">The request.</param>
        /// <param name="statusCode">The status code of the created response.</param>
        /// <param name="modelState">The model state.</param>
        /// <returns>An error response for <paramref name="modelState"/> with status code <paramref name="statusCode"/>.</returns>
        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, ModelStateDictionary modelState)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            return(request.CreateErrorResponse(statusCode, includeErrorDetail => new HttpError(modelState, includeErrorDetail)));
        }
Example #41
0
 //AddErrorToModelState
 public static ModelStateDictionary AddErrorToModelState(string code, string description, ModelStateDictionary modelState)
 {
     modelState.TryAddModelError(code, description);
     return(modelState);
 }
Example #42
0
        public static async Task <string> ProcessFormFile(IFormFile formFile, ModelStateDictionary modelState)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(FileUpload).GetProperty(formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

            if (property != null)
            {
                var displayAttribute =
                    property.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;

                if (displayAttribute != null)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Use Path.GetFileName to obtain the file name, which will
            // strip any path information passed as part of the
            // FileName property. HtmlEncode the result in case it must
            // be returned in an error message.
            var fileName = WebUtility.HtmlEncode(Path.GetFileName(formFile.FileName));

            if (formFile.ContentType.ToLower() != "text/plain")
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) must be a text file.");
            }

            // Check the file length and don't bother attempting to
            // read it if the file contains no content. This check
            // doesn't catch files that only have a BOM as their
            // content, so a content length check is made later after
            // reading the file's content to catch a file that only
            // contains a BOM.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) is empty.");
            }
            else if (formFile.Length > 1048576)
            {
                modelState.AddModelError(formFile.Name, $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB.");
            }
            else
            {
                try
                {
                    string fileContents;

                    // The StreamReader is created to read files that are UTF-8 encoded.
                    // If uploads require some other encoding, provide the encoding in the
                    // using statement. To change to 32-bit encoding, change
                    // new UTF8Encoding(...) to new UTF32Encoding().
                    using (
                        var reader =
                            new StreamReader(
                                formFile.OpenReadStream(),
                                new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),
                                detectEncodingFromByteOrderMarks: true))
                    {
                        fileContents = await reader.ReadToEndAsync();

                        // Check the content length in case the file's only
                        // content was a BOM and the content is actually
                        // empty after removing the BOM.
                        if (fileContents.Length > 0)
                        {
                            return(fileContents);
                        }
                        else
                        {
                            modelState.AddModelError(formFile.Name,
                                                     $"The {fieldDisplayName}file ({fileName}) is empty.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"The {fieldDisplayName}file ({fileName}) upload failed. " +
                                             $"Please contact the Help Desk for support. Error: {ex.Message}");
                    // Log the exception
                }
            }

            return(string.Empty);
        }
 public static IEnumerable <Error> ConvertModelStateToErrors(ModelStateDictionary modelState)
 => modelState.SelectMany(entry =>
Example #44
0
 public UnprocessableEntityObjectResult(ModelStateDictionary modelState)
     : base(new SerializableError(modelState))
 {
     StatusCode = 422;
 }
Example #45
0
 public static IEnumerable <ValidationError> AllErrors(this ModelStateDictionary modelState)
 {
     return(modelState.Keys.SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage))).ToList());
 }
Example #46
0
        //AddErrorsToModelState
        public static ModelStateDictionary AddErrorsToModelState(IdentityResult identityResult, ModelStateDictionary modelState)
        {
            foreach (var e in identityResult.Errors)
            {
                modelState.TryAddModelError(e.Code, e.Description);
            }

            return(modelState);
        }
Example #47
0
 public static Dictionary <string, string[]> ToDictionary(this ModelStateDictionary modelState)
 {
     return(modelState.Where(kvp => kvp.Value.Errors.Count > 0).ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()));
 }
 public ValidationErrorResult(ModelStateDictionary modelState)
     : base(modelState)
 {
 }
Example #49
0
 internal static CustomActionResult getNullException(ModelStateDictionary modelState)
 {
     return(new CustomActionResult(HttpStatusCode.NotAcceptable, "ERR-VALIDATION-01: validation failed.object is null"));
 }
 public static string ErrorsAsString(this ModelStateDictionary modelStateDic)
 {
     return(string.Join("; ", modelStateDic.Values
                        .SelectMany(x => x.Errors).Select(x => x.ErrorMessage)));
 }
Example #51
0
 public TestClass3()
 {
     Prop1 = new ModelStateDictionary <string>();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidationResults"/> class.
 /// </summary>
 /// <param name="modelState">State of the model.</param>
 public ValidationResults(ModelStateDictionary modelState = null)
 {
     this.modelStateDictionary = modelState ?? new ModelStateDictionary();
 }
 public static bool IsInvalid(this ModelStateDictionary modelState)
 => !modelState.IsValid;
Example #54
0
 internal static CustomActionResult getModelValidationException(ModelStateDictionary modelState)
 {
     return(new CustomActionResult(HttpStatusCode.NotAcceptable, "ERR-VALIDATION-00: validation failed.value required"));
 }
Example #55
0
 public static List <string> GetErrorMessages(this ModelStateDictionary dictionary)
 {
     return(dictionary.SelectMany(m => m.Value.Errors)
            .Select(m => m.ErrorMessage)
            .ToList());
 }
Example #56
0
 public static IEnumerable <string> ToEnumerableString(this ModelStateDictionary modelState)
 {
     return(modelState.Values.Where(e => e.Errors.Count > 0)
            .SelectMany(e => e.Errors)
            .Select(e => e.ErrorMessage));
 }
 public ValidationErrorWrapper(ModelStateDictionary modelState)
 {
     Message = ErrorMessage;
     SerializeModelState(modelState);
 }
Example #58
0
        public void DateIsWithinTheSeason(Func <DateTimeOffset?> dateToValidate, Season season, ModelStateDictionary modelState, string fieldName, string dateOfWhat)
        {
            if (dateToValidate is null)
            {
                throw new ArgumentNullException(nameof(dateToValidate));
            }

            if (modelState is null)
            {
                throw new ArgumentNullException(nameof(modelState));
            }

            if (dateToValidate().HasValue&& season != null)
            {
                var seasonForMatch = _seasonEstimator.EstimateSeasonDates(dateToValidate().Value);
                if (seasonForMatch.fromDate.Year != season.FromYear || seasonForMatch.untilDate.Year != season.UntilYear)
                {
                    modelState.AddModelError(fieldName, $"The {dateOfWhat} date is not in the {season.SeasonFullName()}");
                }
            }
        }
 public static ApiModel <TValue> AsApiModel <TValue>(this ModelStateDictionary modelState, TValue val)
     where TValue : class
 {
     return(new ApiModel <TValue>(val, AsApiResult(modelState)));
 }
 public ValidationErrorWrapper(string message, ModelStateDictionary modelState)
 {
     Message = message;
     SerializeModelState(modelState);
 }