예제 #1
0
        public static AppResultBuilder MakeInvalidAccountRegistrationResults(ModelStateDictionary modelState)
        {
            var builder = new AppResultBuilder();

            if (modelState.ContainsKey("password") &&
                modelState["password"].ValidationState == ModelValidationState.Invalid)
            {
                builder.FailValidation(mess: "Invalid password");
            }
            if (modelState.ContainsKey("confirm_password") &&
                modelState["confirm_password"].ValidationState == ModelValidationState.Invalid)
            {
                builder.FailValidation(mess: "The password and confirm password are not matched");
            }
            if (modelState.ContainsKey("username") &&
                modelState["username"].ValidationState == ModelValidationState.Invalid)
            {
                builder.FailValidation(mess: "Invalid username");
            }
            if (modelState.ContainsKey("DuplicateUserName") &&
                modelState["DuplicateUserName"].ValidationState == ModelValidationState.Invalid)
            {
                builder.DuplicatedUsername();
            }
            return(builder);
        }
예제 #2
0
        public static AppResult MakeInvalidAccountRegistrationResults(ModelStateDictionary modelState)
        {
            var validationData = new ValidationData();

            if (modelState.ContainsKey("password") &&
                modelState["password"].ValidationState == ModelValidationState.Invalid)
            {
                validationData.Fail(mess: "Invalid password", code: Constants.AppResultCode.FailValidation);
            }
            if (modelState.ContainsKey("confirm_password") &&
                modelState["confirm_password"].ValidationState == ModelValidationState.Invalid)
            {
                validationData.Fail(mess: "The password and confirm password are not matched", code: Constants.AppResultCode.FailValidation);
            }
            if (modelState.ContainsKey("username") &&
                modelState["username"].ValidationState == ModelValidationState.Invalid)
            {
                validationData.Fail(mess: "Invalid username", code: Constants.AppResultCode.FailValidation);
            }
            if (modelState.ContainsKey("DuplicateUserName") &&
                modelState["DuplicateUserName"].ValidationState == ModelValidationState.Invalid)
            {
                return(AppResult.DuplicatedUsername());
            }
            var appResult = AppResult.FailValidation(data: validationData);

            return(appResult);
        }
예제 #3
0
        public void Question_is_required(string emptyQuestion)
        {
            // arrange
            _model.Question = emptyQuestion;

            // act
            _model.Validate(_modelState);

            // assert
            Assert.That(_modelState.Count, Is.EqualTo(1));
            Assert.That(_modelState.ContainsKey("QuestionNullOrEmpty"), Is.True);
        }
예제 #4
0
        public static void AddExcepition(ModelStateDictionary ModelState, Exception ex)
        {
            if (ex is ArgumentException)
            {
                var argEx = (ArgumentException) ex;
                if (!ModelState.ContainsKey(argEx.ParamName)) ModelState.Add(argEx.ParamName, new ModelState());
                var lines = Regex.Split(ex.Message, "\r\n");
                ModelState[argEx.ParamName].Errors.Add(new ModelError(ex, lines[0]));
                return;
            }

            if (!ModelState.ContainsKey("")) ModelState.Add("", new ModelState());

            ModelState[""].Errors.Add(new ModelError(ex, ex.Message));
        }
예제 #5
0
        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey)) return;

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
            if (fromTempData == null) return;

            foreach (var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (var error in pair.Value.Errors)
                    {
                        if (!modelState[pair.Key].Errors.Contains(error))
                            modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
예제 #6
0
        public void ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsFalse()
        {
            // Arrange
            ModelStateDictionary modelState           = CreateModelState();
            string     expectedModelStateKey          = "ModelStateKey";
            string     expectedModelStateErrorMessage = "ModelStateErrorMessage";
            ModelState originalModelStateItem         = new ModelState();

            originalModelStateItem.Errors.Add(new ModelError(new InvalidOperationException(),
                                                             expectedModelStateErrorMessage));
            modelState.Add(expectedModelStateKey, originalModelStateItem);
            bool includeErrorDetail = false;
            MediaTypeFormatter       expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue     expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,
                                                                                      expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable <MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock <IContentNegotiator> spy = new Mock <IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator,
                                                                  expectedRequest, expectedFormatters);

                // Act
                Task <HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
                    HttpContent content = response.Content;
                    Assert.IsType <ObjectContent <HttpError> >(content);
                    ObjectContent <HttpError> typedContent = (ObjectContent <HttpError>)content;
                    HttpError error = (HttpError)typedContent.Value;
                    Assert.NotNull(error);
                    HttpError modelStateError = error.ModelState;
                    Assert.NotNull(modelStateError);
                    Assert.True(modelState.ContainsKey(expectedModelStateKey));
                    object modelStateValue = modelStateError[expectedModelStateKey];
                    Assert.IsType(typeof(string[]), modelStateValue);
                    string[] typedModelStateValue = (string[])modelStateValue;
                    Assert.Equal(1, typedModelStateValue.Length);
                    Assert.Same(expectedModelStateErrorMessage, typedModelStateValue[0]);
                    Assert.Same(expectedFormatter, typedContent.Formatter);
                    Assert.NotNull(typedContent.Headers);
                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
예제 #7
0
        public static string[] ModelStateValue(ModelStateDictionary modelState, string name, bool isList)
        {
            if (!modelState.ContainsKey(name))
            {
                return(null);
            }

            var value = modelState[name];

            if (value == null)
            {
                return(null);
            }

            if (isList)
            {
                var enumerable = value.RawValue as IEnumerable;

                if (enumerable != null && !(enumerable is string))
                {
                    return(enumerable.Cast <object>().Select(o => Convert.ToString(o)).ToArray());
                }
            }

            return(new string[] { value.AttemptedValue });
        }
예제 #8
0
        /// <summary>
        /// Used to calculate Model filling status in percentage
        /// </summary>
        /// <param name="modelState">Model state that contains information about filled fields</param>
        /// <param name="prefix">Prefix that used to get full path to elemet returned from page</param>
        public int GetProgressPercentage(ModelStateDictionary modelState, string prefix)
        {
            var successCnt = 0;
            var errorCnt = 0;

            var formattedList = this.GetAllPropertyFormattedList(this).Select(s => prefix + s).ToList();

            foreach (var element in formattedList)
            {
                if (modelState.ContainsKey(element))
                {
                    if (modelState[element].Errors.Count == 0)
                    {
                        if (!string.IsNullOrEmpty(modelState[element].Value.AttemptedValue))
                        {
                            successCnt++;
                        }
                    }
                    else
                    {
                        errorCnt++;
                    }
                }
            }

            var totalCnt = successCnt + errorCnt;

            return totalCnt == 0 ? 100 : (successCnt * 100 / totalCnt);
        }
예제 #9
0
        public async Task ReadAsync_WhenSuppressJsonDeserializationExceptionMessagesIsTrue_DoesNotWrapJsonInputExceptions()
        {
            // Arrange
            var logger    = GetLogger();
            var formatter = new JsonInputFormatter(
                logger, _serializerSettings, ArrayPool <char> .Shared, _objectPoolProvider,
                suppressInputFormatterBuffering: false, suppressJsonDeserializationExceptionMessages: true);
            var contentBytes  = Encoding.UTF8.GetBytes("{");
            var modelStateKey = string.Empty;

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider    = new EmptyModelMetadataProvider();
            var metadata    = provider.GetMetadataForType(typeof(User));
            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.True(result.HasError);
            Assert.True(!modelState.IsValid);
            Assert.True(modelState.ContainsKey(modelStateKey));

            var modelError = modelState[modelStateKey].Errors.Single();

            Assert.IsNotType <InputFormatterException>(modelError.Exception);
            Assert.Empty(modelError.ErrorMessage);
        }
예제 #10
0
        /// <summary>
        /// Stores the errors in a ValidationResult object to the specified modelstate dictionary.
        /// </summary>
        /// <param name="result">The validation result to store</param>
        /// <param name="modelState">The ModelStateDictionary to store the errors in.</param>
        /// <param name="prefix">An optional prefix. If ommitted, the property names will be the keys. If specified, the prefix will be concatenatd to the property name with a period. Eg "user.Name"</param>
        public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState, string prefix)
        {
            if (!result.IsValid)
            {
                foreach (var error in result.Errors)
                {
                    string key = string.IsNullOrEmpty(prefix)
                                                ? error.PropertyName
                                                : string.IsNullOrEmpty(error.PropertyName)
                                                        ? prefix
                                                        : prefix + "." + error.PropertyName;

                    if (modelState.ContainsKey(key))
                    {
                        modelState[key].Errors.Add(error.ErrorMessage);
                    }
                    else
                    {
                        modelState.AddModelError(key, error.ErrorMessage);
                        //To work around an issue with MVC: SetModelValue must be called if AddModelError is called.
                        modelState.SetModelValue(key, new ValueProviderResult(error.AttemptedValue ?? "", (error.AttemptedValue ?? "").ToString(), CultureInfo.CurrentCulture));
                    }
                }
            }
        }
예제 #11
0
        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content      = "{name: 'Person Name', Age: 'not-an-age'}";
            var logger       = GetLogger();
            var formatter    = new JsonInputFormatter(logger);
            var contentBytes = Encoding.UTF8.GetBytes(content);

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

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

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

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);

            Assert.IsType <TooManyModelErrorsException>(error.Exception);
        }
        private void CopyTempDataToModelState(ModelStateDictionary modelState,
                                              TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            ModelStateDictionary fromTempData = tempData[TempDataKey]
                                                    as ModelStateDictionary;
            if (fromTempData == null)
            {
                return;
            }

            foreach (KeyValuePair<string, ModelState> pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (ModelError error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
        private void AddErrorsToModel(IdentityResult identityResult, ModelStateDictionary modelState)
        {
            foreach (var currentError in identityResult.Errors)
            {
                string currentKey = string.Empty;


                if (currentError.Code.Contains("Email"))
                {
                    currentKey = $"Email";
                }
                else if (currentError.Code.Contains("Password"))
                {
                    currentKey = $"password";
                }
                else
                {
                    currentKey = $"UserName";
                }

                if (modelState.ContainsKey(currentKey))
                {
                    if (modelState[currentKey].Errors.Count == 0)
                    {
                        modelState.AddModelError(currentKey, currentError.Description);
                    }
                }
            }
        }
예제 #14
0
        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content      = "{name: 'Person Name', Age: 'not-an-age'}";
            var formatter    = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);

            var context = new InputFormatterContext(httpContext, modelState, typeof(User));

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

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

            // Assert
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);

            Assert.IsType <TooManyModelErrorsException>(error.Exception);
        }
예제 #15
0
        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;

            if (fromTempData == null)
            {
                return;
            }

            foreach (var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (var error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
예제 #16
0
 public static void ResetModelValue(this ModelStateDictionary modelStateDictionary, string key)
 {
     if (modelStateDictionary.ContainsKey(key))
     {
         modelStateDictionary.SetModelValue(key, new ValueProviderResult(null, null, null));
     }
 }
예제 #17
0
        public async Task ReadAsync_RegistersJsonInputExceptionsAsInputFormatterException(
            string content,
            string modelStateKey,
            string expectedMessage)
        {
            // Arrange
            var logger    = GetLogger();
            var formatter =
                new JsonInputFormatter(logger, _serializerSettings, ArrayPool <char> .Shared, _objectPoolProvider);
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider    = new EmptyModelMetadataProvider();
            var metadata    = provider.GetMetadataForType(typeof(User));
            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.True(result.HasError);
            Assert.True(!modelState.IsValid);
            Assert.True(modelState.ContainsKey(modelStateKey));

            var modelError = modelState[modelStateKey].Errors.Single();

            Assert.Equal(expectedMessage, modelError.ErrorMessage);
        }
예제 #18
0
        public static bool IsValidEditableFieldsOnly <T>(ModelStateDictionary modelState, T model)
        {
            var isValid = modelState.IsValid;

            if (isValid)
            {
                return(true);
            }

            //If it is not valid, check if there are any errors
            var props = typeof(T).GetProperties();

            foreach (var propertyInfo in props)
            {
                if (modelState.ContainsKey(propertyInfo.Name) && modelState[propertyInfo.Name].Errors.Any() &&
                    ConditionMetForChangeVisually(propertyInfo, model, props))
                {
                    //There were errors for this property, but it was not editable so remove them
                    modelState[propertyInfo.Name].Errors.Clear();
                }
            }

            //re-evaluate validity after potentially having removed some errors
            return(modelState.IsValid);
        }
예제 #19
0
        public static string GetErrorClass(this HtmlHelper htmlHelper, string propertyName, ModelStateDictionary modelState)
        {
            if (modelState.IsValid == false)
            {
                return(modelState.ContainsKey(propertyName) && modelState[propertyName].Errors.Count > 0 ? "govuk-form-group--error" : string.Empty);
            }

            return(string.Empty);
        }
        /// <summary>
        /// Clears the validation messages and exceptions associated with a model property,
        /// making the value in that property valid.
        /// </summary>
        /// <param name="modelState">ModelState object from which the model property will be removed, and thus be considered as valid.</param>
        /// <param name="expression">Expression tree that goes to the property that should be made valid.</param>
        public static void ClearPropertyErrors(this ModelStateDictionary modelState, Expression <Func <object> > expression)
        {
            var propertyInfo = MemberExpressionHelper.GetPropertyInfo(expression);

            if (modelState.ContainsKey(propertyInfo.Name))
            {
                modelState[propertyInfo.Name].Errors.Clear();
            }
        }
예제 #21
0
 public static ModelStateDictionary ClearError(this ModelStateDictionary m, string fieldName)
 {
     if (m.ContainsKey(fieldName))
     {
         m[fieldName].Errors.Clear();
         m[fieldName].ValidationState = ModelValidationState.Valid;
     }
     return(m);
 }
    /// <summary>
    ///
    /// </summary>
    /// <param name="modelState"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static bool IsValid(this ModelStateDictionary modelState, string key)
    {
        if (modelState.ContainsKey(key))
        {
            return(modelState[key] !.ValidationState == ModelValidationState.Valid);
        }

        return(true);
    }
예제 #23
0
 public static void HasErrors(ModelStateDictionary dict, string key, params ModelError[] errors)
 {
     Assert.True(dict.ContainsKey(key));
     var state = dict[key];
     Assert.Equal(
         // Tuples have an Equals override. ModelError doesn't :(
         errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray(),
         state.Errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray());
 }
        public static void HasErrors(ModelStateDictionary dict, string key, params ModelError[] errors)
        {
            Assert.True(dict.ContainsKey(key));
            var state = dict[key];

            Assert.Equal(
                // Tuples have an Equals override. ModelError doesn't :(
                errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray(),
                state.Errors.Select(e => Tuple.Create(e.Exception, e.ErrorMessage)).ToArray());
        }
예제 #25
0
 private void RemoveModelStateError(ModelStateDictionary ModelState, string key)
 {
     if (!string.IsNullOrEmpty(key))
     {
         if (ModelState.ContainsKey(key))
         {
             ModelState[key].Errors.Clear();
         }
     }
 }
    private static void RemovePropertyState <TModel, TProperty>(HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression)
    {
        string text     = ExpressionHelper.GetExpressionText(expression);
        string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(text);
        ModelStateDictionary modelState = htmlHelper.ViewContext.ViewData.ModelState;

        if (modelState.ContainsKey(fullName))
        {
            modelState.Remove(fullName);
        }
    }
        public void ShouldCopyAllErrorsWithPrefix()
        {
            // arrange
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("Email", "Invalid");
            nvc.Add("Email", "Mising");
            nvc.Add("Password", "Mising");

            ValidationException ex = new ValidationException { Errors = nvc };
            ModelStateDictionary modelState = new ModelStateDictionary();

            // act
            ex.ToModelErrors(modelState, "credentials");

            // assert
            Assert.IsFalse(modelState.ContainsKey("Email"));
            Assert.IsFalse(modelState.ContainsKey("Password"));
            Assert.AreEqual(2, modelState["credentials.Email"].Errors.Count);
            Assert.AreEqual(1, modelState["credentials.Password"].Errors.Count);
        }
 public static void AddModelErrorSafety(this ModelStateDictionary errors, string key, string message)
 {
     if (errors.ContainsKey(key))
     {
         errors[key].Errors.Add(message);
     }
     else
     {
         errors.AddModelError(key, message);
     }
 }
예제 #29
0
 public static void AddFirstToKey(this ModelStateDictionary controller, string key, string message)
 {
     if (!controller.ContainsKey(key))
     {
         controller.AddModelError(key, message);
     }
     else
     {
         controller[key].Errors.Insert(0, new ModelError(message));
     }
 }
 private object GetValueFromModelState(ModelStateDictionary modelStateDictionary, string column)
 {
     if (modelStateDictionary.ContainsKey(column))
     {
         return(modelStateDictionary[column].Value.AttemptedValue);
     }
     else
     {
         return(DBNull.Value);
     }
 }
예제 #31
0
        protected ModelValidationResult GetModelValidationResult(ModelStateDictionary modelState)
        {
            if (modelState.Count == 0)
            {
                return(new ModelValidationResult()
                {
                    IsValid = true
                });
            }

            var modelErrors = new List <IModelValidationError>();

            if (modelState.ContainsKey(string.Empty))
            {
                modelErrors.AddRange(modelState[string.Empty].Errors.Select(x => new ModelValidationError(x.ErrorMessage)));
            }
            if (modelState.ContainsKey(WarningSpecialField))
            {
                modelErrors.AddRange(modelState[WarningSpecialField].Errors.Select(x => new ModelValidationError(x.ErrorMessage, true)));
            }

            var propertyErrors = new Dictionary <string, IEnumerable <IModelValidationError> >();

            foreach (var modelError in modelState)
            {
                if (string.IsNullOrEmpty(modelError.Key) || WarningSpecialField == modelError.Key)
                {
                    continue;
                }
                var list = new List <IModelValidationError>();
                list.AddRange(modelError.Value.Errors.Select(x => new ModelValidationError(x.ErrorMessage)));
                propertyErrors[modelError.Key] = list;
            }

            return(new ModelValidationResult()
            {
                IsValid = false,
                ModelErrors = modelErrors,
                PropertyErrors = propertyErrors
            });
        }
예제 #32
0
        /// <summary>
        /// Adds a generic culture error for use in displaying the culture validation error in the save/publish/etc... dialogs
        /// </summary>
        /// <param name="modelState"></param>
        /// <param name="culture"></param>
        /// <param name="segment"></param>
        /// <param name="errMsg"></param>
        internal static void AddVariantValidationError(this ModelStateDictionary modelState,
                                                       string culture, string segment, string errMsg)
        {
            var key = "_content_variant_" + (culture.IsNullOrWhiteSpace() ? "invariant" : culture) + "_" + (segment.IsNullOrWhiteSpace() ? "null" : segment) + "_";

            if (modelState.ContainsKey(key))
            {
                return;
            }

            modelState.AddModelError(key, errMsg);
        }
        public void LogErrorAddsErrorToModelState()
        {
            ModelStateDictionary modelState = new ModelStateDictionary();
            string prefix = "prefix";
            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);

            formatterLogger.LogError("property", "error");

            Assert.True(modelState.ContainsKey("prefix.property"));
            Assert.Equal(1, modelState["prefix.property"].Errors.Count);
            Assert.Equal("error", modelState["prefix.property"].Errors[0].ErrorMessage);
        }
        public void LogErrorAddsErrorToModelState()
        {
            ModelStateDictionary modelState  = new ModelStateDictionary();
            string           prefix          = "prefix";
            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);

            formatterLogger.LogError("property", "error");

            Assert.True(modelState.ContainsKey("prefix.property"));
            Assert.Equal(1, modelState["prefix.property"].Errors.Count);
            Assert.Equal("error", modelState["prefix.property"].Errors[0].ErrorMessage);
        }
예제 #35
0
        private void OnValidationError(string property, IReadOnlyCollection <ValidationFailure> errors, ModelStateDictionary modelState)
        {
            if (!modelState.ContainsKey(property))
            {
                modelState.Add(property, new ModelState());
            }
            ModelState modelStateErrors = modelState[property];

            foreach (var failure in errors)
            {
                modelStateErrors.Errors.Add(failure.ErrorMessage);
            }
        }
예제 #36
0
            public void will_consider_nocaptcha_invalid_when_response_is_missing()
            {
                var stubHttpContext = CreateHttpContext(noCaptchaChallenge: "1234");
                var modelState      = new ModelStateDictionary();
                var attribute       = new ValidateSpamPreventionAttribute();

                attribute.Authorize(
                    stubHttpContext.Object,
                    modelState,
                    new Mock <ICaptchaValidator>().Object);

                Assert.True(modelState.ContainsKey(Const.ModelStateKey));
            }
예제 #37
0
            public void will_add_a_model_state_error_when_both_the_nocaptcha_and_captcha_response_is_invalid()
            {
                var stubHttpContext = CreateHttpContext();
                var modelState      = new ModelStateDictionary();
                var attribute       = new ValidateSpamPreventionAttribute();

                attribute.Authorize(
                    stubHttpContext.Object,
                    modelState,
                    new Mock <ICaptchaValidator>().Object);

                Assert.True(modelState.ContainsKey(Const.ModelStateKey));
            }
        public void CreateUser_would_report_error_if_user_name_is_null_or_empty()
        {
            var modelError = new ModelStateDictionary();
            _userAuthenticationServiceSUT.Create(null, _userName, modelError);

            Assert.True(modelError.ContainsKey(UserAuthenticationService.PROP_USERNAME));
            Assert.True(modelError.ContainsError(UserAuthenticationService.PROP_USERNAME, AccountString.UserNameCanNotBeNull));
        }
        public void MergeDoesNothingIfParameterIsNull()
        {
            // Arrange
            ModelStateDictionary fooDict = new ModelStateDictionary() { { "foo", new ModelState() } };

            // Act
            fooDict.Merge(null);

            // Assert
            Assert.Single(fooDict);
            Assert.True(fooDict.ContainsKey("foo"));
        }
        public void CreateUser_would_report_error_if_password_not_valid()
        {
            SetUpEmptyUserExpectationForNonExistingUser();

            var modelError = new ModelStateDictionary();
            _userAuthenticationServiceSUT.Create(new User { UserName = _nonExistignUserName, Password = "******" }, _userName, modelError);

            Assert.True(modelError.ContainsKey(UserAuthenticationService.PROP_PASSWORD));
            Assert.True(modelError.ContainsError(UserAuthenticationService.PROP_PASSWORD, AccountString.NotMatchPasswordRule));
        }
예제 #41
0
        public void ContainsKey_ReturnsFalse_IfNodeHasNotBeenMutated(string key)
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.AddModelError("foo.bar", "some error");

            // Act
            var result = dictionary.ContainsKey(key);

            // Assert
            Assert.False(result);
        }
예제 #42
0
        public void ContainsKey_ReturnsTrue_IfNodeHasBeenMutated(string key)
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.MarkFieldSkipped(key);

            // Act
            var result = dictionary.ContainsKey(key);

            // Assert
            Assert.True(result);
        }
예제 #43
0
        public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("foo.bar", "Some existing error.");

            var modelMetadata = GetMetadataForType(typeof(Person));
            var validationNode = new ModelValidationNode(modelMetadata, "foo");
            var validationContext = new ModelValidationContext(new DataAnnotationsModelMetadataProvider(),
                                                               Enumerable.Empty<IModelValidatorProvider>(),
                                                               modelState,
                                                               modelMetadata,
                                                               null);
            var e = new ModelValidatedEventArgs(validationContext, parentNode: null);

            // Act
            var handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, incomingValue: null);
            handler(validationNode, e);

            // Assert
            Assert.False(modelState.ContainsKey("foo"));
        }
예제 #44
0
        public void NullCheckFailedHandler_ModelStateValid_AddsErrorString()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            var modelMetadata = GetMetadataForType(typeof(Person));
            var validationNode = new ModelValidationNode(modelMetadata, "foo");
            var validationContext = new ModelValidationContext(new DataAnnotationsModelMetadataProvider(),
                                                               Enumerable.Empty<IModelValidatorProvider>(),
                                                               modelState,
                                                               modelMetadata,
                                                               null);
            var e = new ModelValidatedEventArgs(validationContext, parentNode: null);

            // Act
            var handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, incomingValue: null);
            handler(validationNode, e);

            // Assert
            Assert.True(modelState.ContainsKey("foo"));
            Assert.Equal("A value is required.", modelState["foo"].Errors[0].ErrorMessage);
        }
    	public void Should_add_to_modelstate_without_prefix()
    	{
			var thing = new Thing();
			var form = new FormCollection 
			{
				{ "Age", "not a number" }
			};

			var modelState = new ModelStateDictionary();
			try 
			{
				validatingBinder.UpdateFrom(thing, form, modelState);
			}
			catch {}
			finally 
			{
				modelState.ContainsKey("Age").ShouldBeTrue();
			}
    	}
예제 #46
0
        public void MergeDoesNothingIfParameterIsNull()
        {
            // Arrange
            var dictionary = new ModelStateDictionary() { { "foo", new ModelStateEntry() } };

            // Act
            dictionary.Merge(null);

            // Assert
            Assert.Single(dictionary);
            Assert.True(dictionary.ContainsKey("foo"));
        }
        public void CreateUser_would_report_error_if_user_exist_already()
        {
            SetUpUserExpectationForExistingUser();

            var modelError = new ModelStateDictionary();
            _userAuthenticationServiceSUT.Create(new User { UserName = _userName }, _userName, modelError);

            Assert.True(modelError.ContainsKey(UserAuthenticationService.PROP_USERNAME));
            Assert.True(modelError.ContainsError(UserAuthenticationService.PROP_USERNAME, AccountString.UserAlreadyExist));
        }
        public void CreateUser_would_report_error_if_the_creator_has_no_rights()
        {
            SetUpEmptyUserExpectationForCreateNewAccountWithValidConditions();

            var modelError = new ModelStateDictionary();
            _userAuthenticationServiceSUT.Create(null, _nonExistignUserName, modelError);

            Assert.True(modelError.ContainsKey(string.Empty));
            Assert.True(modelError.ContainsError(string.Empty, AccountString.CreatorLackOfRight));
        }
예제 #49
0
        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var logger = GetLogger();
            var formatter =
                new JsonInputFormatter(logger, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
            var contentBytes = Encoding.UTF8.GetBytes(content);

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

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

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

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
        }
예제 #50
0
		public void IsPasswordValidFalse()
		{
			var service = GetMockedUserService();
			var modelState = new ModelStateDictionary();
			var result = service.IsPasswordValid("12345", modelState);
			Assert.False(result);
			Assert.AreEqual(1, modelState.Count);
			Assert.True(modelState.ContainsKey("Password"));
		}
예제 #51
0
        private void SetLogo(EditEventViewModel viewModel, ModelStateDictionary modelState)
        {
            bool hasLogo = Session[CurrentLogoKey] != null;

            if(hasLogo)
            {
                viewModel.Logo = (byte[])Session[CurrentLogoKey];
                viewModel.IsLogoSetted = true;
                viewModel.HasLogo = true;
                if(modelState.ContainsKey("HasLogo"))
                    modelState.Remove("HasLogo");
            }
        }
예제 #52
0
        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(User));

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

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

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
        }
예제 #53
0
        public void ContainsKey_ReturnsFalse_IfNodeHasBeenRemoved(string key)
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.AddModelError(key, "some error");

            // Act
            var remove = dictionary.Remove(key);
            var containsKey = dictionary.ContainsKey(key);

            // Assert
            Assert.True(remove);
            Assert.False(containsKey);
        }