예제 #1
0
        public void ApplyCustomValidationSummaryOrdering_OneExtraRequested_ShouldIgnoreExtra()
        {
            var first      = "First";
            var second     = "Second";
            var third      = "Third";
            var missing    = "Missing";
            var firstPair  = new KeyValuePair <string, ModelState>(first, null);
            var secondPair = new KeyValuePair <string, ModelState>(second, null);
            var thirdPair  = new KeyValuePair <string, ModelState>(third, null);

            var modelState = new ModelStateDictionary();

            modelState.Add(thirdPair);
            modelState.Add(secondPair);
            modelState.Add(firstPair);

            modelState.ApplyCustomValidationSummaryOrdering(new List <string> {
                first, second, third, missing
            });

            Assert.Equal(3, modelState.Count);
            Assert.Equal(firstPair, modelState.First());
            Assert.Equal(secondPair, modelState.Skip(1).First());
            Assert.Equal(thirdPair, modelState.Skip(2).First());
        }
예제 #2
0
        public void ApplyCustomValidationSummaryOrdering_AllRequested_ShouldOrderAsRequested()
        {
            var first      = "First";
            var second     = "Second";
            var third      = "Third";
            var last       = "Last";
            var firstPair  = new KeyValuePair <string, ModelState>(first, null);
            var secondPair = new KeyValuePair <string, ModelState>(second, null);
            var thirdPair  = new KeyValuePair <string, ModelState>(third, null);
            var fourthPair = new KeyValuePair <string, ModelState>(last, null);

            var modelState = new ModelStateDictionary();

            modelState.Add(thirdPair);
            modelState.Add(secondPair);
            modelState.Add(fourthPair);
            modelState.Add(firstPair);

            modelState.ApplyCustomValidationSummaryOrdering(new List <string> {
                first, second, third, last
            });

            Assert.Equal(4, modelState.Count);
            Assert.Equal(firstPair, modelState.First());
            Assert.Equal(secondPair, modelState.Skip(1).First());
            Assert.Equal(thirdPair, modelState.Skip(2).First());
            Assert.Equal(fourthPair, modelState.Last());
        }
예제 #3
0
        public void DictionaryType_ValidationSuccessful()
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();

            modelStateDictionary.Add("items[0].Key", new ModelState());
            modelStateDictionary.Add("items[0].Value", new ModelState());
            modelStateDictionary.Add("items[1].Key", new ModelState());
            modelStateDictionary.Add("items[1].Value", new ModelState());

            var model = new Dictionary <string, string>()
            {
                { "FooKey", "FooValue" },
                { "BarKey", "BarValue" }
            };

            var testValidationContext = GetModelValidationContext(
                model,
                typeof(Dictionary <string, string>),
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List <IExcludeTypeValidationFilter>();

            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());
            testValidationContext.ExcludeFilters = excludeTypeFilters;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFilters,
                testValidationContext.ModelMetadataProvider);

            var topLevelValidationNode =
                new ModelValidationNode(
                    "items",
                    testValidationContext.ModelValidationContext.ModelExplorer.Metadata,
                    testValidationContext.ModelValidationContext.ModelExplorer.Model)
            {
                ValidateAllProperties = true
            };

            // Act
            validator.Validate(validationContext, topLevelValidationNode);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            Assert.Equal(4, validationContext.ModelState.Count);
            var modelState = validationContext.ModelState["items[0].Key"];

            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[0].Value"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[1].Key"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[1].Value"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
        }
예제 #4
0
        public void DictionaryType_ValidationSuccessful()
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();

            modelStateDictionary.Add("items[0].Key", new ModelState());
            modelStateDictionary.Add("items[0].Value", new ModelState());
            modelStateDictionary.Add("items[1].Key", new ModelState());
            modelStateDictionary.Add("items[1].Value", new ModelState());

            var model = new Dictionary <string, string>()
            {
                { "FooKey", "FooValue" },
                { "BarKey", "BarValue" }
            };

            var testValidationContext = GetModelValidationContext(
                model,
                typeof(Dictionary <string, string>),
                "items",
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List <IExcludeTypeValidationFilter>();

            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());

            var mockValidationExcludeFiltersProvider = new Mock <IValidationExcludeFiltersProvider>();

            mockValidationExcludeFiltersProvider
            .SetupGet(o => o.ExcludeFilters)
            .Returns(excludeTypeFilters);
            testValidationContext.ExcludeFiltersProvider = mockValidationExcludeFiltersProvider.Object;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFiltersProvider,
                testValidationContext.ModelMetadataProvider);

            // Act
            validator.Validate(validationContext);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            var modelState = validationContext.ModelState["items"];

            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);
            modelState = validationContext.ModelState["items[0].Key"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Skipped);
            modelState = validationContext.ModelState["items[0].Value"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Skipped);
            modelState = validationContext.ModelState["items[1].Key"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Skipped);
            modelState = validationContext.ModelState["items[1].Value"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Skipped);
        }
예제 #5
0
        public void EnumerableType_ValidationSuccessful(object model, Type type)
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();

            modelStateDictionary.Add("items[0]", new ModelState());
            modelStateDictionary.Add("items[1]", new ModelState());
            modelStateDictionary.Add("items[2]", new ModelState());

            var testValidationContext = GetModelValidationContext(
                model,
                type,
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List <IExcludeTypeValidationFilter>();

            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());
            testValidationContext.ExcludeFilters = excludeTypeFilters;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFilters,
                testValidationContext.ModelMetadataProvider);
            var topLevelValidationNode =
                new ModelValidationNode(
                    "items",
                    testValidationContext.ModelValidationContext.ModelExplorer.Metadata,
                    testValidationContext.ModelValidationContext.ModelExplorer.Model)
            {
                ValidateAllProperties = true
            };

            // Act
            validator.Validate(validationContext, topLevelValidationNode);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            Assert.Equal(3, validationContext.ModelState.Count);
            var modelState = validationContext.ModelState["items[0]"];

            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);

            modelState = validationContext.ModelState["items[1]"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);

            modelState = validationContext.ModelState["items[2]"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);
        }
예제 #6
0
        public void ValidateSum(double sum, double minSum, double maxSum, ModelStateDictionary modelState, bool isInitial = false)
        {
            if (sum < minSum)
            {
                modelState.Add(isInitial ? "request.InitialSum" : "request.Sum",
                    new ModelState() {Errors = {"—умма не может быть меньше минимальной."}});
            }

            if (sum > maxSum)
            {
                modelState.Add(isInitial ? "request.InitialSum" : "request.Sum", new ModelState() { Errors = { "—умма не может быть больше максимальной." } });
                //                throw BankClientException.ThrowSumMoreThanMax();
            }
        }
예제 #7
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));
        }
        public void element_without_error_renders_with_attempted_value()
        {
            stateDictionary.Add("Price", new ModelState()
            {
                Value = new ValueProviderResult("foo", "foo", CultureInfo.CurrentCulture)
            });

            expression = x => x.Price;
            var textbox = new TextBox(expression.GetNameFor(), expression.GetMemberExpression(), new List <IBehaviorMarker> {
                target
            });
            var element = textbox.ToString().ShouldHaveHtmlNode("Price");

            element.ShouldHaveAttribute(HtmlAttribute.Value).WithValue("foo");
        }
        public void Validate_CollectionType_DictionaryOfSimpleType_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState        = new ModelStateDictionary();
            var validationState   = new ValidationStateDictionary();

            var validator = CreateValidator(new SimpleTypesExcludeFilter());

            var model = new Dictionary <string, string>()
            {
                { "FooKey", "FooValue" },
                { "BarKey", "BarValue" }
            };

            modelState.Add("items[0].Key", new ModelState());
            modelState.Add("items[0].Value", new ModelState());
            modelState.Add("items[1].Key", new ModelState());
            modelState.Add("items[1].Value", new ModelState());
            validationState.Add(model, new ValidationStateEntry()
            {
                Key = "items"
            });

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

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "items[0].Key", "items[0].Value", "items[1].Key", "items[1].Value");

            var entry = modelState["items[0].Key"];

            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[0].Value"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1].Key"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1].Value"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
예제 #10
0
        /// <summary>
        /// Overrides default OnActionExecuted method.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //// Support for HtmlHelperExtensions.NamedValidationSummary().
            filterContext.Controller.ViewData[HtmlHelperExtensions.SubmittedFormName] = filterContext.Controller.TempData[HtmlHelperExtensions.SubmittedFormName];

            var modelState = filterContext.Controller.TempData[ModelStateTempDataTransferAttribute.Key] as ModelStateDictionary;

            if (modelState != null)
            {
                // Only Import if we are viewing
                if (filterContext.Result is ViewResult)
                {
                    if (this.ImportJustInvalidStates)
                    {
                        var invalidModelStates = new ModelStateDictionary();
                        foreach (var ms in modelState.Where(x => x.Value.Errors.Any()))
                        {
                            invalidModelStates.Add(ms);
                        }

                        modelState = invalidModelStates;
                    }

                    filterContext.Controller.ViewData.ModelState.Merge(modelState);
                }
                else
                {
                    // Otherwise remove it.
                    filterContext.Controller.TempData.Remove(ModelStateTempDataTransferAttribute.Key);
                }
            }

            base.OnActionExecuted(filterContext);
        }
        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);
                }
            }
        }
예제 #12
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);
                }
            }
        }
예제 #13
0
        private static ModelStateDictionary ValidateObject(object value)
        {
            var modelState = new ModelStateDictionary();

            var objectProperties = value.GetType().GetProperties();

            foreach (var objectProperty in objectProperties)
            {
                var validationAttributes = objectProperty
                                           .GetCustomAttributes()
                                           .Where(type => type is ValidationSisAttribute)
                                           .Cast <ValidationSisAttribute>()
                                           .ToList();

                foreach (var validationAttribute in validationAttributes)
                {
                    if (validationAttribute.IsValid(objectProperty.GetValue(value)))
                    {
                        continue;
                    }

                    modelState.Add(objectProperty.Name, validationAttribute.ErrorMessage);
                }
            }

            return(modelState);
        }
예제 #14
0
 public void AddErrors(ModelStateDictionary modelState)
 {
     foreach (var state in modelState)
     {
         ModelState.Add(state);
     }
 }
        public void Errors_FromModelState()
        {
            modelState.AddModelError("Empty", "");
            modelState.AddModelError("Error", "Error");
            modelState.AddModelError("EmptyErrors", "");
            modelState.AddModelError("EmptyErrors", "E");
            modelState.Add("NoErrors", new ModelState());
            modelState.AddModelError("TwoErrors", "Error1");
            modelState.AddModelError("TwoErrors", "Error2");
            modelState.AddModelError("NullError", (String)null);
            modelState.AddModelError("NullErrors", (String)null);
            modelState.AddModelError("NullErrors", "NotNullError");
            modelState.AddModelError("WhitespaceErrors", "       ");
            modelState.AddModelError("WhitespaceErrors", "Whitespace");

            Dictionary <String, String> actual = modelState.Errors();

            Assert.Equal("       ", actual["WhitespaceErrors"]);
            Assert.Equal("NotNullError", actual["NullErrors"]);
            Assert.Equal("Error1", actual["TwoErrors"]);
            Assert.Equal("E", actual["EmptyErrors"]);
            Assert.Equal("Error", actual["Error"]);
            Assert.Null(actual["NullError"]);
            Assert.Equal(7, actual.Count);
            Assert.Null(actual["Empty"]);
        }
예제 #16
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);
                }
            }
        }
예제 #17
0
        private void ValidateListModelState <T>(List <T> consoles) where T : GameConsole
        {
            var dictinory = new ModelStateDictionary();

            for (int entityPosition = 0; entityPosition < consoles.Count; entityPosition++)
            {
                TryValidateModel(consoles[entityPosition]);

                for (int i = 0; i < ModelState.Keys.Count; i++)
                {
                    dictinory.Add($"[{entityPosition}].{ModelState.Keys.ToList()[i]}", ModelState.Values.ToList()[i]);
                }

                var entityStateDictionary = consoles[entityPosition].State;

                entityStateDictionary.ToList().ForEach(x =>
                {
                    dictinory.AddModelError($"[{entityPosition}].{x.Key}", x.Value);
                });

                ModelState.Clear();
            }

            for (int i = 0; i < dictinory.Keys.Count; i++)
            {
                ModelState.Add(dictinory.Keys.ToList()[i], dictinory.Values.ToList()[i]);
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ControllerBase controller = filterContext.Controller as ControllerBase;

              if (controller != null)
              {
            string serializedModelState = controller.TempData[Key] as string;

            if (!string.IsNullOrEmpty(serializedModelState))
            {
              IEnumerable<ModelStateWrapper> modelStateWrappers = JsonConvert.DeserializeObject<IEnumerable<ModelStateWrapper>>(serializedModelState, new JsonSerializerSettings() { Error = DeserializationErrorHandler });

              if (modelStateWrappers != null)
              {
            ModelStateDictionary modelState = new ModelStateDictionary();

            foreach (ModelStateWrapper modelStateWrapper in modelStateWrappers)
            {
              ModelState ms = new ModelState();

              ms.ValidationState = modelStateWrapper.ValidationState;
              ms.Value = new ValueProviderResult(modelStateWrapper.Value, modelStateWrapper.Value, null);
              modelState.Add(modelStateWrapper.Key, ms);
            }

            if (filterContext.Result is ViewResult)
              controller.ViewData.ModelState.Merge(modelState);

            else controller.TempData.Remove(Key);
              }
            }
              }

              base.OnActionExecuted(filterContext);
        }
예제 #19
0
        private static ModelStateDictionary ValidateObject(object value)
        {
            ModelStateDictionary modelStateDictionary = new ModelStateDictionary();

            var objectProperties = value.GetType().GetProperties();

            foreach (var prop in objectProperties)
            {
                var validationAttributes = prop.GetCustomAttributes()
                                           .Where(attribute => attribute is BaseValidationAttribute)
                                           .Cast <BaseValidationAttribute>()
                                           .ToList();

                foreach (var validationAttribure in validationAttributes)
                {
                    if (validationAttribure.IsValid(prop.GetValue(value)))
                    {
                        continue;
                    }

                    modelStateDictionary.Add(prop.Name, validationAttribure.ErrorMessage);
                }
            }

            return(modelStateDictionary);
        }
예제 #20
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);
                }
            }
        }
예제 #21
0
        /// <summary>
        /// Home which is the main landing page.
        /// </summary>
        //[Menu("Home")]
        // OutputCache not working in environment
        // http://stackoverflow.com/questions/5371773/asp-net-mvc-outputcache-vary-by-and-vary-by-user-cookie
        // http://blogs.msdn.com/b/tmarq/archive/2008/08/27/using-iis-7-0-dynamic-compression-with-asp-net-output-cache.aspx
        //[OutputCache(Duration = 60, VaryByParam = "*", VaryByCustom = "user", Location = OutputCacheLocation.Client)]
        public ActionResult Index()
        {
            PageTitle = "Home";

            // Only show noticeboard messages if the user has a Diary role
            var viewModel = new IndexViewModel {
                ShowNoticeboardMessages = false
            };                                                                     //UserService.IsInRole(new [] { "DIA", "DIU", "DIV" })

            if (viewModel.ShowNoticeboardMessages)
            {
                try
                {
                    viewModel.NoticeboardMessages = NoticeboardService.GetSpecificMessages(UserService.SiteCode, UserService.DateTime).ToMessageViewModelList(); //   MappingEngine.Map<IEnumerable<MessageViewModel>>(NoticeboardService.GetSpecificMessages(UserService.SiteCode, UserService.DateTime));
                }
                catch (ServiceValidationException se)
                {
                    ModelStateDictionary modelStateDictionary = new ModelStateDictionary();
                    foreach (var item in se.Errors)
                    {
                        var modelState = new ModelState();
                        modelState.Value = new ValueProviderResult(item.Value, item.Value, System.Globalization.CultureInfo.InvariantCulture);
                        modelStateDictionary.Add(new KeyValuePair <string, ModelState>(item.Key, modelState));
                    }
                    ModelState.Merge(modelStateDictionary);
                }
            }

            return(View(viewModel));
        }
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.Add(
                "key1",
                new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.InvariantCulture) });
            modelState.Add(
                "key2",
                new ModelState() { Value = new ValueProviderResult("bar", "bar", CultureInfo.InvariantCulture) });

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
예제 #23
0
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.Add(
                "key1",
                new ModelStateEntry());
            modelState.Add(
                "key2",
                new ModelStateEntry());

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
예제 #24
0
 /// <summary>
 /// Add an element that has the specified key and the value to the model-state dictionary
 /// </summary>
 /// <typeparam name="TModel">The type of the model.</typeparam>
 /// <param name="modelStateDictionary">The model state dictionary.</param>
 /// <param name="expression">The expression tree representing a property to add an error in its state.</param>
 /// <param name="value">The value of the element to add.</param>
 public static void Add <TModel>(this ModelStateDictionary modelStateDictionary, Expression <Func <TModel, object> > expression, ModelState value)
 {
     if (expression == null)
     {
         throw new ArgumentNullException("expression");
     }
     modelStateDictionary.Add(ExpressionHelper.GetExpressionText(expression), value);
 }
 public void Should_skip_properties_without_errors()
 {
     var msd = new ModelStateDictionary();
     msd.Add("item.Property1", new ModelState());
     msd.AddModelError("item.Property2", "Error");
     ValidationHelpers.PropertyError pe = ValidationHelpers.MakeHierarchical(msd);
     Assert.That(pe["item"].Properties.Count, Is.EqualTo(1));
 }
        public IHttpActionResult GetBadRequestWithModelState()
        {
            ModelStateDictionary dic = new ModelStateDictionary();

            dic.Add("a", ModelState["abc"]);
            dic.AddModelError("err", "hello");
            return(BadRequest(dic));
        }
예제 #27
0
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();

            modelState.Add(
                "key1",
                new ModelStateEntry());
            modelState.Add(
                "key2",
                new ModelStateEntry());

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
예제 #28
0
        public void ValidateMonthCount(int monthCount, int minMonthPeriod, int maxMonthPeriod, ModelStateDictionary modelState)
        {
            if (monthCount < minMonthPeriod)
            {
                modelState.Add("request.MonthCount", new ModelState()
                {
                    Errors = { " оличество мес¤цев не может быть меньше минимального." }
                });
                //                throw BankClientException.ThrowMonthLessThanMin();
            }

            if (monthCount > maxMonthPeriod)
            {
                modelState.Add("request.MonthCount", new ModelState()
                {
                    Errors = { " оличество мес¤цев не может быть больше максимального." }
                });
            }
        }
예제 #29
0
 public static void CopyRelevantNonEmptyErrors(ModelStateDictionary destination, ModelStateDictionary origin, string prefix)
 {
     foreach (KeyValuePair <string, ModelState> pair in origin)
     {
         if (pair.Key.StartsWith(prefix) && pair.Value.Errors.Count > 0)
         {
             destination.Add(pair);
         }
     }
 }
예제 #30
0
        public void EnumerableType_ValidationSuccessful(object model, Type type)
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();

            modelStateDictionary.Add("items[0]", new ModelState());
            modelStateDictionary.Add("items[1]", new ModelState());
            modelStateDictionary.Add("items[2]", new ModelState());

            var testValidationContext = GetModelValidationContext(
                model,
                type,
                "items",
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List <IExcludeTypeValidationFilter>();

            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());

            var mockValidationExcludeFiltersProvider = new Mock <IValidationExcludeFiltersProvider>();

            mockValidationExcludeFiltersProvider
            .SetupGet(o => o.ExcludeFilters)
            .Returns(excludeTypeFilters);
            testValidationContext.ExcludeFiltersProvider = mockValidationExcludeFiltersProvider.Object;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFiltersProvider,
                testValidationContext.ModelMetadataProvider);

            // Act
            validator.Validate(validationContext);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            var modelState = validationContext.ModelState["items"];

            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);
        }
예제 #31
0
        public void ValidateSum(double sum, double minSum, double maxSum, ModelStateDictionary modelState, bool isInitial = false)
        {
            if (sum < minSum)
            {
                modelState.Add(isInitial ? "request.InitialSum" : "request.Sum",
                               new ModelState()
                {
                    Errors = { "—умма не может быть меньше минимальной." }
                });
            }

            if (sum > maxSum)
            {
                modelState.Add(isInitial ? "request.InitialSum" : "request.Sum", new ModelState()
                {
                    Errors = { "—умма не может быть больше максимальной." }
                });
                //                throw BankClientException.ThrowSumMoreThanMax();
            }
        }
        public void Should_convert_model_state_exception_to_text()
        {
            var modelState = new ModelStateDictionary();

            var ms1 = new ModelState();

            ms1.Errors.Add(new Exception("v1"));
            ms1.Errors.Add(new Exception("v2"));
            modelState.Add("k", ms1);

            var ms2 = new ModelState();

            ms2.Errors.Add(new Exception("v3"));
            ms2.Errors.Add(new Exception("v4"));
            modelState.Add("k1", ms2);

            var actual = modelState.GetModelStateErrors();

            Assert.Equal("\"v1\", \"v2\", \"v3\", \"v4\"", actual);
        }
예제 #33
0
        public void GivenAnErrorWhenAddingAComment_WhenIGetThePostWithTheComment_ThenTheViewDataIsUpdateWithTheError()
        {
            var controller = new PostController(_postServiceMock.Object, _dashboardServiceMock, _blogService.Object, null);
            var tempData = new ModelStateDictionary();
            tempData.Add("key", new ModelState());
            controller.TempData["comment"] = tempData;
            controller.Show(new PostLinkViewModel());

            Assert.That(controller.ViewData, Is.Not.Null);
            Assert.That(controller.ViewData.ModelState, Is.Not.Null);
            Assert.That(controller.ViewData.ModelState["key"], Is.Not.Null);
        }
예제 #34
0
        public void ModelErrorWithExceptionIntoJson()
        {
            var modelState = new ModelStateDictionary();
            modelState.Add("FirstName", new ModelState { Errors = { new InvalidOperationException("Cannot operate") } });

            var jsonResult = ControllerExtensions.ToJson(modelState);

            var data = jsonResult.Data;
            Assert.That(data, Has.Property("State").Not.Empty);
            Assert.That(data, Has.Property("State").With.Some.Property("Name").EqualTo("FirstName"));
            Assert.That(data, Has.Property("State").With.Some.Property("Errors").With.Some.EqualTo("Cannot operate"));
        }
예제 #35
0
        public void SimpleModelErrorIntoJson()
        {
            var modelState = new ModelStateDictionary();
            modelState.Add("FirstName", new ModelState { Errors = { "First name is a required field" } });

            var jsonResult = ControllerExtensions.ToJson(modelState);

            var data = jsonResult.Data;
            Assert.That(data, Has.Property("State").Not.Empty);
            Assert.That(data, Has.Property("State").With.Some.Property("Name").EqualTo("FirstName"));
            Assert.That(data, Has.Property("State").With.Some.Property("Errors").With.Some.EqualTo("First name is a required field"));
        }
        public void Validate_IndexedCollectionTypes_Valid(object model, Type type)
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState        = new ModelStateDictionary();
            var validationState   = new ValidationStateDictionary();

            var validator = CreateValidator(new SimpleTypesExcludeFilter());

            modelState.Add("items[0]", new ModelState());
            modelState.Add("items[1]", new ModelState());
            modelState.Add("items[2]", new ModelState());
            validationState.Add(model, new ValidationStateEntry()
            {
                Key = "items",

                // Force the validator to treat it as the specified type.
                Metadata = MetadataProvider.GetMetadataForType(type),
            });

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

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "items[0]", "items[1]", "items[2]");

            var entry = modelState["items[0]"];

            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1]"];
            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);

            entry = modelState["items[2]"];
            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);
        }
예제 #37
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);
            }
        }
예제 #38
0
        public static void ApplyCustomValidationSummaryOrdering(this ModelStateDictionary modelState, IEnumerable <string> modelStateKeys)
        {
            var result = new ModelStateDictionary();

            foreach (string key in modelStateKeys)
            {
                if (modelState.ContainsKey(key) && !result.ContainsKey(key))
                {
                    result.Add(key, modelState[key]);
                }
            }

            foreach (string key in modelState.Keys)
            {
                if (!result.ContainsKey(key))
                {
                    result.Add(key, modelState[key]);
                }
            }

            modelState.Clear();
            modelState.Merge(result);
        }
예제 #39
0
        /// <summary>
        /// Gets the warnings.
        /// </summary>
        /// <param name="modelStateDictionary">The model state dictionary.</param>
        /// <returns></returns>
        public static ModelStateDictionary GetWarnings(this ModelStateDictionary modelStateDictionary)
        {
            var msd = new ModelStateDictionary();

            foreach (var ms in from ms in modelStateDictionary
                     let extendedModelState = ms.Value as ExtendedModelState
                                              where extendedModelState != null
                                              where extendedModelState.Warnings.Count != 0
                                              select ms)
            {
                msd.Add(ms);
            }
            return(msd);
        }
예제 #40
0
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();

            modelState.Add(
                "key1",
                new ModelState()
            {
                Value = new ValueProviderResult("foo", "foo", CultureInfo.InvariantCulture)
            });
            modelState.Add(
                "key2",
                new ModelState()
            {
                Value = new ValueProviderResult("bar", "bar", CultureInfo.InvariantCulture)
            });

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
예제 #41
0
        public void Does_Not_Overwrite_Any_Existing_ModelState_Value()
        {
            // Arrange
            object rawValue = new object();
            var someValue = new ModelState { Value = new ValueProviderResult(rawValue, null, null)};
            var ex = new RulesException("myProp", "myError");
            var modelState = new ModelStateDictionary();
            modelState.Add("myProp", someValue);

            // Act
            ex.AddModelStateErrors(modelState, null);

            // Assert
            Assert.Equal(1, modelState.Keys.Count());
            Assert.Same(rawValue, modelState["myProp"].Value.RawValue);
        }
        public void ReturnsCorrectly()
        {
            string key = "Key";
            string value = "Value";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult( value, value, CultureInfo.InvariantCulture );

            var modelStateDictionary = new ModelStateDictionary();
            modelStateDictionary.Add( key, modelState );

            ModelState modelStateResult;
            var result = modelStateDictionary.GetModelStateValue( key, value.GetType(), out modelStateResult );

            Assert.AreEqual( result, value );
            Assert.AreSame( modelStateResult, modelState );
        }
        public void WithKeyNotFoundReturnsCorrectly()
        {
            string key = "Key";
            string value = "Value";

            var modelState = new ModelState();
            modelState.Value = new ValueProviderResult( value, value, CultureInfo.InvariantCulture );

            var modelStateDictionary = new ModelStateDictionary();
            modelStateDictionary.Add( key, modelState );

            ModelState modelStateResult;
            var result = modelStateDictionary.GetModelStateValue( "KeyNotFound", typeof( string ), out modelStateResult );

            Assert.IsNull( result );
            Assert.IsNull( modelStateResult );
        }
        private static void CreateModelValidationNodeRecursive(object o, ModelValidationNode parentNode, ModelMetadataProvider metadataProvider, ModelMetadata metadata, ModelStateDictionary modelStateDictionary, string modelStateKey, HashSet<object> visited)
        {
            if (visited.Contains(o))
            {
                return;
            }
            visited.Add(o);

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(o))
            {
                // append the current property name to the model state path
                string propertyKey = modelStateKey;
                if (propertyKey.Length > 0)
                {
                    propertyKey += ".";
                }
                propertyKey += property.Name;

                // create the node for this property and add to the parent node
                object propertyValue = property.GetValue(o);
                metadata = metadataProvider.GetMetadataForProperty(() =>
                {
                    return propertyValue;
                }, o.GetType(), property.Name);
                ModelValidationNode childNode = new ModelValidationNode(metadata, propertyKey);
                parentNode.ChildNodes.Add(childNode);

                // add the property node to model state
                ModelState modelState = new ModelState();
                modelState.Value = new ValueProviderResult(propertyValue, null, CultureInfo.CurrentCulture);
                modelStateDictionary.Add(propertyKey, modelState);

                if (propertyValue != null)
                {
                    CreateModelValidationNodeRecursive(propertyValue, childNode, metadataProvider, metadata, modelStateDictionary, propertyKey, visited);
                }
            }
        }
        public void RemoveAll_ForSingleExpression_RemovesModelStateKeys()
        {
            // Arrange
            var state = new ModelState();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("Text", new ModelState());
            dictionary.Add("Text.Length", new ModelState());

            // Act
            dictionary.RemoveAll<TestModel>(model => model.Text);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
예제 #46
0
        public void DictionaryType_ValidationSuccessful()
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();
            modelStateDictionary.Add("items[0].Key", new ModelState());
            modelStateDictionary.Add("items[0].Value", new ModelState());
            modelStateDictionary.Add("items[1].Key", new ModelState());
            modelStateDictionary.Add("items[1].Value", new ModelState());

            var model = new Dictionary<string, string>()
            {
                { "FooKey", "FooValue" },
                { "BarKey", "BarValue" }
            };

            var testValidationContext = GetModelValidationContext(
                model,
                typeof(Dictionary<string, string>),
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List<IExcludeTypeValidationFilter>();
            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());
            testValidationContext.ExcludeFilters = excludeTypeFilters;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFilters,
                testValidationContext.ModelMetadataProvider);

            var topLevelValidationNode =
                new ModelValidationNode(
                    "items",
                    testValidationContext.ModelValidationContext.ModelExplorer.Metadata,
                    testValidationContext.ModelValidationContext.ModelExplorer.Model)
                {
                    ValidateAllProperties = true
                };

            // Act
            validator.Validate(validationContext, topLevelValidationNode);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            Assert.Equal(4, validationContext.ModelState.Count);
            var modelState = validationContext.ModelState["items[0].Key"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[0].Value"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[1].Key"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
            modelState = validationContext.ModelState["items[1].Value"];
            Assert.Equal(ModelValidationState.Skipped, modelState.ValidationState);
        }
예제 #47
0
        public void EnumerableType_ValidationSuccessful(object model, Type type)
        {
            // Arrange
            var modelStateDictionary = new ModelStateDictionary();
            modelStateDictionary.Add("items[0]", new ModelState());
            modelStateDictionary.Add("items[1]", new ModelState());
            modelStateDictionary.Add("items[2]", new ModelState());

            var testValidationContext = GetModelValidationContext(
                model,
                type,
                excludedTypes: null,
                modelStateDictionary: modelStateDictionary);

            var excludeTypeFilters = new List<IExcludeTypeValidationFilter>();
            excludeTypeFilters.Add(new SimpleTypesExcludeFilter());
            testValidationContext.ExcludeFilters = excludeTypeFilters;

            var validationContext = testValidationContext.ModelValidationContext;

            var validator = new DefaultObjectValidator(
                testValidationContext.ExcludeFilters,
                testValidationContext.ModelMetadataProvider);
            var topLevelValidationNode =
                new ModelValidationNode(
                    "items",
                    testValidationContext.ModelValidationContext.ModelExplorer.Metadata,
                    testValidationContext.ModelValidationContext.ModelExplorer.Model)
                {
                    ValidateAllProperties = true
                };

            // Act
            validator.Validate(validationContext, topLevelValidationNode);

            // Assert
            Assert.True(validationContext.ModelState.IsValid);
            Assert.Equal(3, validationContext.ModelState.Count);
            var modelState = validationContext.ModelState["items[0]"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);

            modelState = validationContext.ModelState["items[1]"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);

            modelState = validationContext.ModelState["items[2]"];
            Assert.Equal(modelState.ValidationState, ModelValidationState.Valid);
        }
        public void ModelStatePropertyGetterWorks()
        {
            // Arrange
            ApiController controller = new Mock<ApiController>().Object;

            // Act
            ModelStateDictionary expected = new ModelStateDictionary();
            expected.Add("a", new ModelState() { Value = new ValueProviders.ValueProviderResult("result", "attempted", CultureInfo.InvariantCulture) });

            controller.ModelState.Add("a", new ModelState() { Value = new ValueProviders.ValueProviderResult("result", "attempted", CultureInfo.InvariantCulture) });

            // Assert
            Assert.Equal(expected.Count, controller.ModelState.Count);
        }
        public void Remove_ForRelationExpression_RemovesModelStateKey()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.Add("Child.Text", new ModelStateEntry());

            // Act
            dictionary.Remove<TestModel>(model => model.Child.Text);

            // Assert
            Assert.Empty(dictionary);
        }
        public void Remove_ForNotModelsExpression_RemovesModelStateKey()
        {
            // Arrange
            var variable = "Test";
            var dictionary = new ModelStateDictionary();
            dictionary.Add("variable", new ModelStateEntry());

            // Act
            dictionary.Remove<TestModel>(model => variable);

            // Assert
            Assert.Empty(dictionary);
        }
        public void Remove_ForImplicitlyCastedToObjectExpression_RemovesModelStateKey()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            dictionary.Add("Child.Value", new ModelStateEntry());

            // Act
            dictionary.Remove<TestModel>(model => model.Child.Value);

            // Assert
            Assert.Empty(dictionary);
        }
        public void RemoveAll_ForImplicitlyCastedToObjectExpression_RemovesModelStateKeys()
        {
            // Arrange
            var state = new ModelStateEntry();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Child", state);
            dictionary.Add("Child.Value", new ModelStateEntry());

            // Act
            dictionary.RemoveAll<TestModel>(model => model.Child.Value);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Child", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
        public void Validate_CollectionType_DictionaryOfSimpleType_Invalid()
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator(new SimpleTypesExcludeFilter());

            var model = new Dictionary<string, string>()
            {
                { "FooKey", "FooValue" },
                { "BarKey", "BarValue" }
            };

            modelState.Add("items[0].Key", new ModelStateEntry());
            modelState.Add("items[0].Value", new ModelStateEntry());
            modelState.Add("items[1].Key", new ModelStateEntry());
            modelState.Add("items[1].Value", new ModelStateEntry());
            validationState.Add(model, new ValidationStateEntry() { Key = "items" });

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

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "items[0].Key", "items[0].Value", "items[1].Key", "items[1].Value");

            var entry = modelState["items[0].Key"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[0].Value"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1].Key"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1].Value"];
            Assert.Equal(ModelValidationState.Skipped, entry.ValidationState);
            Assert.Empty(entry.Errors);
        }
        public void Validate_IndexedCollectionTypes_Valid(object model, Type type)
        {
            // Arrange
            var validatorProvider = CreateValidatorProvider();
            var modelState = new ModelStateDictionary();
            var validationState = new ValidationStateDictionary();

            var validator = CreateValidator(new SimpleTypesExcludeFilter());

            modelState.Add("items[0]", new ModelStateEntry());
            modelState.Add("items[1]", new ModelStateEntry());
            modelState.Add("items[2]", new ModelStateEntry());
            validationState.Add(model, new ValidationStateEntry()
            {
                Key = "items",
                
                // Force the validator to treat it as the specified type.
                Metadata = MetadataProvider.GetMetadataForType(type),
            });

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

            // Assert
            Assert.True(modelState.IsValid);
            AssertKeysEqual(modelState, "items[0]", "items[1]", "items[2]");

            var entry = modelState["items[0]"];
            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);

            entry = modelState["items[1]"];
            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);

            entry = modelState["items[2]"];
            Assert.Equal(entry.ValidationState, ModelValidationState.Valid);
            Assert.Empty(entry.Errors);
        }
        public void RemoveAll_ForNotModelsExpression_RemovesModelStateKeys()
        {
            // Arrange
            var variable = "Test";
            var state = new ModelStateEntry();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("variable", new ModelStateEntry());
            dictionary.Add("variable.Text", new ModelStateEntry());
            dictionary.Add("variable.Value", new ModelStateEntry());

            // Act
            dictionary.RemoveAll<TestModel>(model => variable);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
        public void RemoveAll_ForModelExpression_RemovesModelPropertyKeys()
        {
            // Arrange
            var state = new ModelStateEntry();
            var dictionary = new ModelStateDictionary();

            dictionary.Add("Key", state);
            dictionary.Add("Text", new ModelStateEntry());
            dictionary.Add("Child", new ModelStateEntry());
            dictionary.Add("Child.Text", new ModelStateEntry());
            dictionary.Add("Child.NoValue", new ModelStateEntry());

            // Act
            dictionary.RemoveAll<TestModel>(model => model);

            // Assert
            var modelState = Assert.Single(dictionary);

            Assert.Equal("Key", modelState.Key);
            Assert.Same(state, modelState.Value);
        }
예제 #57
-1
        public void ValidateMonthCount(int monthCount, int minMonthPeriod, int maxMonthPeriod, ModelStateDictionary modelState)
        {
            if (monthCount < minMonthPeriod)
            {
                modelState.Add("request.MonthCount", new ModelState() { Errors = { " оличество мес¤цев не может быть меньше минимального." } });
                //                throw BankClientException.ThrowMonthLessThanMin();
            }

            if (monthCount > maxMonthPeriod)
            {
                modelState.Add("request.MonthCount", new ModelState() { Errors = { " оличество мес¤цев не может быть больше максимального." } });
            }
        }