public void CultureIsSetByBinderOverride()
        {
            // prepare - get ready test [fake] environment
            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
            var formCollection = new NameValueCollection
                    {
                        { "StringProperty", "something" }
                    };
            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DummyViewModel));
            var controllerContext = HttpMocks.GetControllerContextMock();
            controllerContext.Object.RequestContext.HttpContext.Request.Cookies.Add(new HttpCookie("_ui_culture", "fi-FI"));
            controllerContext.Object.RequestContext.HttpContext.Request.Cookies.Add(new HttpCookie("_culture", "fi-FI"));
            var bindingContext = new ModelBindingContext
            {
                ModelName = string.Empty,
                ValueProvider = valueProvider,
                ModelMetadata = modelMetaData,
            };

            var modelBinder = new CultureAwareModelBinder();
            var logger = modelBinder.GetType().GetProperty("Logger");
            if (logger != null)
            {
                logger.SetValue(modelBinder, new Mock<ILog>().Object);
            }
            modelBinder.BindModel(controllerContext.Object, bindingContext);

            Thread.CurrentThread.CurrentUICulture.Name.Should().Be("de-DE");  // Unchanged, as binder only sets CurrentCulture
            Thread.CurrentThread.CurrentCulture.Name.Should().Be("fi-FI");
        }
        public void CanBindToExpiry()
        {
            // Arrange
            var formCollection = new NameValueCollection {
                { "foo.CardNo", "9999999999999999" },
                { "foo.Code", "999" },
                { "Expiry.Value.Month", "7" },
                { "Expiry.Value.Year", "2014" }
            };     // not sure why it doesn't work with foo prefix on Expiry?

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Card));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "foo",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            ControllerContext controllerContext = new ControllerContext();
            CardModelBinder b = new CardModelBinder();

            // Act
            Card result = (Card)b.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreEqual(7, result.Expiry.Value.Month, "Incorrect value for Month");
            Assert.AreEqual(2014, result.Expiry.Value.Year, "Incorrect value for Year");
        }
        public void TrimModelBinder_TrimsStringValuesOnModel(
            string inserted,
            string expected)
        {
            // Arrange
            var formCollection = new NameValueCollection
            {
                ["model.Name"] = inserted,
            };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TestUserModel));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "model",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            var binder = new TrimModelBinder();
            var controllerContext = new ControllerContext();

            // Act
            var result = (TestUserModel)binder.BindModel(controllerContext, bindingContext);

            // Assert
            result.Name.Should().Be(expected);
        }
        public void ModelBinder()
        {
            var postData =
                new NameValueCollection()
                {
                    { "Class", "TempModelType" },
                    { "TestValue", "1234" },
                    { "Ignored", "IgnoredValue" },
                };

            var controllerContext = new ControllerContext();
            var valueProvider = new NameValueCollectionValueProvider(postData, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));

            var bindingContext =
                new ModelBindingContext()
                {
                    ValueProvider = valueProvider,
                    ModelMetadata = modelMetadata,
                };

            var result = (TempModelType)new OnlineController.Binder().BindModel(controllerContext, bindingContext);

            Assert.That(result, Is.Not.Null, "null model returned");
            Assert.That(result.TestValue, Is.EqualTo("1234"));
        }
        public void CanBindToMember()
        {
            // Arrange
            var formCollection = new NameValueCollection {
                { "foo.FirstName", "Fernando" },
                { "foo.LastName", "Alonso" }
            };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Member));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "foo",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            MemberModelBinder b = new MemberModelBinder();
            ControllerContext controllerContext = new ControllerContext();

            // Act
            Member result = (Member)b.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreEqual("Fernando", result.FirstName, "Incorrect value for FirstName");
            Assert.AreEqual("Alonso", result.LastName, "Incorrect value for LastName");
        }
 /// <summary>
 /// Converts a dictionary to an IValueProvider
 /// </summary>
 /// <param name="dictionary"></param>
 /// <returns></returns>
 public static IValueProvider ToValueProvider(this IDictionary<string, string> dictionary)
 {
     var collection = new NameValueCollection();
     foreach (var f in dictionary)
     {
         collection.Add(f.Key, f.Value);
     }
     var valProvider = new NameValueCollectionValueProvider(collection, CultureInfo.InvariantCulture);
     return valProvider;  
 }
        public void CanConvertLocaleDates(LocaleDateTimeBinder sut)
        {
            var collection = new NameValueCollection { { "foo", "20/12/2012" } };
            var dict = new NameValueCollectionValueProvider(collection, new CultureInfo("es-ES"));

            var modelBindingContext = new ModelBindingContext { ModelName = "foo", ValueProvider = dict };

            var model = sut.BindModel(null, modelBindingContext);

            model.Should().BeOfType<DateTime>();
            var modelDate = (DateTime)model;
            modelDate.Should().Be(new DateTime(2012, 12, 20));
        }
Beispiel #8
0
        public ActionResult Index()
        {
            NameValueCollection datasource = new NameValueCollection();

            datasource.Add("first[0].Name", "Foo");
            datasource.Add("first[0].PhoneNo", "123456789");
            datasource.Add("first[0].EmailAddress", "*****@*****.**");

            datasource.Add("first[1].Name", "Bar");
            datasource.Add("first[1].PhoneNo", "987654321");
            datasource.Add("first[1].EmailAddress", "*****@*****.**");

            NameValueCollectionValueProvider valueProvider =new NameValueCollectionValueProvider(datasource,CultureInfo.InvariantCulture);
            return View(valueProvider);
        }
        public void CanBindToCard()
        {
            //  Arrange:
            //  Set up the BindingContext
            //  1.  Set up a NameValueCollection that represents the FormData (all string values)
            var formCollection = new NameValueCollection {
                { "myCard.CardNo", "12345678" },
                { "myCard.Code", "719" },
                { "myCard.Expiry", "01/09/2012" }
            };
            //  2.  Set up a valueProvider, containing the formData.
            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            //  3.  Set up the meta data for the type Card
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Card));
            //  4.  Create the bindingContext for the model
            var bindingContext = new ModelBindingContext
            {
                ModelName = "myCard",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };
            //  Set up the ControllerContext
            //  1.  We must mock the HttpContext, using 'Moq' NuGet package
            var mockHttpContext = new Mock<HttpContextBase>();
            //  2.  Set up the value to be returned by the mockHttpContext
            mockHttpContext
                .Setup(c => c.Request["Expiry.Value.Month"])
                .Returns(() => "7");
            mockHttpContext
                .Setup(c => c.Request["Expiry.Value.Year"])
                .Returns(() => "2014");
            //  3.  Create the controllerContext, using the mockHttpContext.Object
            ControllerContext controllerContext = new ControllerContext()
            {
                HttpContext = mockHttpContext.Object
            };

            //  Create an instance of the CardModelBinder
            var binder = new CardModelBinder();

            //  Act:
            Card result = (Card)binder.BindModel(controllerContext, bindingContext);

            //  Assert:
            Assert.AreEqual(result.CardNo, "12345678", "Expected the CardNo: '12345678'");
            Assert.AreEqual(result.Code, "719", "Expected the Code: '719'");
            Assert.AreEqual(result.Expiry, DateTime.Parse("01/07/2014"), "Expected Expiry date: '01/07/2014', the mocked value.");
        }
Beispiel #10
0
        public ActionResult Index()
        {
            NameValueCollection datasource = new NameValueCollection();

            datasource.Add("foo.Name", "Foo");
            datasource.Add("foo.PhoneNo", "123456789");
            datasource.Add("foo.EmailAddress", "*****@*****.**");

            datasource.Add("foo.Address.Province", "江苏");
            datasource.Add("foo.Address.City", "苏州");
            datasource.Add("foo.Address.District", "工业园区");
            datasource.Add("foo.Address.Street", "星湖街328号");

            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(datasource, CultureInfo.InvariantCulture);
            return View(valueProvider);
        }
        public void DecimalCustomModelBinderTest1()
        {
            //method parameter name we expect
            //ie:  public ActionResult TestDecimal(decimal DecimalToTest)
            //{
            //return Json("ResultValue");
            //}

            //parameter name into the controller method that we are binding too
            const string ParameterName = "DecimalToTest";

            //the value we are testing
            const int DecimalValueToTest = 2;

            //let's set the parameters we pass into the method
            var MethodParameters = new NameValueCollection
                                    {
                                        { ParameterName, DecimalValueToTest.ToString() }
                                    };

            //let's create the value Provider with the methood parameters that we are going to pass in
            var ValueProviderForMethod = new NameValueCollectionValueProvider(MethodParameters, null);

            //let's declare the type we are expecting. This method is expecting a decimal type
            var MetaDataForMethod = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(decimal));

            //let's create a new binding context
            var BindingContext = new ModelBindingContext
            {
                ModelName = ParameterName,
                ValueProvider = ValueProviderForMethod,
                ModelMetadata = MetaDataForMethod
            };

            //let's create a new controller context
            var ControllerContext = new ControllerContext();

            //let's crewate the new decimal model binder
            var ModelBinder = new DecimalModelBinder();

            //let's try to go bind this guy
            var Result = (decimal)ModelBinder.BindModel(ControllerContext, BindingContext);

            //let's make sure we have a value
            Assert.Equal(DecimalValueToTest, Result);
        }
        public void TakeSurveyBinderOKWithValidData()
        {
            //  Arrange
            //  1   Set up a name/value collection containing all view input values
            var formCollection = _mockData.SetTakeSurveyFormDataCompletedOK();
            //  2   Set up a ValueProvider for the name/value collection
            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            //  3   Get the Metadata from the ViewModel or class being bound
            var metaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TakeSurveyViewModel));
            //  4   Instantiate the bindingContext for the model binder
            var bindingContext = new ModelBindingContext()
            {
                ModelName = "TakeSurvey",
                ValueProvider = valueProvider,
                ModelMetadata = metaData
            };

            //  5   Set up a mock Httpcontext and populate the Request["fieldname"].Return values
            var mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(c => c.Request["SurveyId"]).Returns("3");
            mockHttpContext.Setup(c => c.Request["item.QId_SeqNo"]).Returns("1_1,2_2");
            mockHttpContext.Setup(c => c.Request["LikertScaleNumber_1_1"]).Returns("2");
            mockHttpContext.Setup(c => c.Request["LikertScaleNumber_2_2"]).Returns("3");

            //  6   Set up the ControllerContext, containing the HttpContext as as HttpContext property of the controllercontext
            //      Don't think we need to do this bit here, the formcollection has everything needed already, nothing needs to
            //      be supplied in addition.
            ControllerContext controllerContext = new ControllerContext();
            controllerContext.HttpContext = mockHttpContext.Object;

            //  7   Instantiate the model Binder taking the ControllerContext and BindingContext as its parameters
            var binder = new TakeSurveyModelbinder();

            //  Act
            //  8   Execute the bindingContext BindModel method to test the binder
            var result = (TakeSurveyViewModel) binder.BindModel(controllerContext, bindingContext);

            //  Assert
            //  9   Check the values of the output viewModel / class
            Assert.AreEqual(3, result.SurveyId, "Expected Survey3 to be returned");
            Assert.AreEqual("2", result.Questions.First().Answer, "Expected question1 to have answer 2");
            Assert.AreEqual("1_1", result.Questions.First().QId_SeqNo, "Expected question1 to have QId_seqNo of '1_1'");
            Assert.AreEqual("3", result.Questions.Last().Answer, "Expected question2 to have answer 3");
            Assert.AreEqual("2_2", result.Questions.Last().QId_SeqNo, "Expected question2 to have QId_SeqNo of '2_2'");
        }
        public void CanBindToExpiry()
        {
            // Arrange
            var formCollection = new NameValueCollection {
                { "foo.CardNo", "123456789" },
                { "foo.Code", "123" }
            };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Card));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "foo",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            var mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext
                .SetupGet(c => c.Request["Expiry.Value.Month"])
                .Returns(() => "7");
            mockHttpContext
                .SetupGet(c => c.Request["Expiry.Value.Year"])
                .Returns(() => "2014");

            ControllerContext controllerContext = new ControllerContext()
            {
                HttpContext = mockHttpContext.Object
            };

            CardModelBinder b = new CardModelBinder();

            // Act
            Card result = (Card)b.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreEqual("123456789", result.CardNo, "Incorrect value for CardNo");
            Assert.AreEqual("123", result.Code, "Incorrect value for Code");

            Assert.AreEqual(7, result.Expiry.Value.Month, "Incorrect value for Month");
            Assert.AreEqual(2014, result.Expiry.Value.Year, "Incorrect value for Year");
        }
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var commandName = filterContext.HttpContext.Request.Form["partName"];

			if (filterContext.HttpContext.Request.Params == null)
			{
				throw new NullReferenceException("filterContext.HttpContext.Request.Params");
			}

			var valueProvider = new NameValueCollectionValueProvider(
				filterContext.HttpContext.Request.Params, CultureInfo.CurrentCulture);

			var inputModel = CompositeApp.GetInputModelFromCommandName(commandName, valueProvider, filterContext.HttpContext.Request.Files);

			var command = CompositeApp.GetCommandForInputModel(inputModel);

			var publicationId = Publisher.PublishMessage(command);

			filterContext.ActionParameters["publicationId"] = publicationId;
		}
        public void It_should_throw_if_no_value_found()
        {
            var formCollection = new NameValueCollection { { "foo", "2" } };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TheEntity));

            var bindingContext = new ModelBindingContext
            {
                ModelName = string.Empty,
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            var modelBinder = new GetFromContextModelBinder();
            var controllerContext = new ControllerContext();

            modelBinder.Invoking(x => x.BindModel(controllerContext, bindingContext))
                       .ShouldThrow<BackstageException>()
                       .WithMessage("*id*");
        }
Beispiel #16
0
        public void CanBindModelWithCollection()
        {
            int id = 2;
            string employeeName = "Michael";
            //string employee2Id = "3";
            //string employee2Name = "Alec";

            // Arrange
            var formCollection = new NameValueCollection
                                     {
                                         {"Employee.Id", id.ToString()},
                                         {"Employee.Name", employeeName},
                                         {"Employee.Reports", "3"},
                                         {"Employee.Reports", "4"},
                                         {"Employee.Manager", "12"}
                                     };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Employee));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "Employee",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            DefaultModelBinder target = new SharpModelBinder();

            ControllerContext controllerContext = new ControllerContext();

            // Act
            Employee result = (Employee)target.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreEqual(id, result.Id);
            Assert.AreEqual(employeeName, result.Name);
            Assert.AreEqual(2,result.Reports.Count);
        }
Beispiel #17
0
        public void Should_add_model_error_for_invalid_sort_value()
        {
            var idParser = new AlwaysTrueIdParser();
            var binder = new RestRequestModelBinder(null, null);

            var valueProvider = new NameValueCollectionValueProvider(
                new NameValueCollection {
                    { ":sort", "foo|asdf" },
                    { "id", idParser.FetchAllIdValue }
                },
                CultureInfo.InvariantCulture
            );

            var bindingContext = new ModelBindingContext {
                ValueProvider = valueProvider
            };

            var controllerContext = CreateControllerContext();
            var model = binder.BindModel(controllerContext, bindingContext);
            Assert.That(model, Is.TypeOf<RestRequest>());

            Assert.That(controllerContext.IsValid(), Is.False);
        }
Beispiel #18
0
        public void DecimalValidateTest()
        {

            var formCollection = new NameValueCollection { 
                    { "value", "2" }
            };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(decimal));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "decimal",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };
            DecimalModelBinder b1 = new DecimalModelBinder();
            ControllerContext controllerContext = new ControllerContext();

            var result = (decimal)b1.BindModel(controllerContext, bindingContext);

            //Assert.IsFalse(state.IsValid);
        }
        public void It_should_call_current_context_GetById_and_convert_type(string idParameterNameInput, string idParameterNameModelBinder)
        {
            var formCollection = new NameValueCollection { { idParameterNameInput, "2" } };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TheEntity));

            var bindingContext = new ModelBindingContext
            {
                ModelName = string.Empty,
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            var modelBinder = new GetFromContextModelBinder(idParameterNameModelBinder, typeof(int));
            var controllerContext = new ControllerContext();

            var returnedObject = new TheEntity();
            this.contextProviderMock.Setup(x => x.GetById(typeof(TheEntity), 2)).Returns(returnedObject);

            var result = modelBinder.BindModel(controllerContext, bindingContext);

            result.Should().Be(returnedObject);
        }
 private ModelBindingContext GetBindingContext()
 {
     var valueProvider = new NameValueCollectionValueProvider(_form, null);
     var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DataCollectionViewModelStep2));
     return new ModelBindingContext { ModelName = "", ModelMetadata = metadata, ValueProvider = valueProvider };
 }
Beispiel #21
0
        public void ModelValidateTestPointNautral()
        {
            const string pointDecSeparator = ".";
            const string modelName = "Weight";
            var formCollection = new NameValueCollection { 
                    { modelName, "2.12" }
            };


            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(MessageModel));

            var bindingContext = new ModelBindingContext
            {
                ModelName = modelName,
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            
            Thread.CurrentThread.CurrentCulture = GetNeutralCulture(pointDecSeparator);

            ControllerContext controllerContext = new ControllerContext();
            DecimalModelBinder b1 = new DecimalModelBinder();
            var result = b1.BindModel(controllerContext, bindingContext);


            Assert.IsNotNull(result);
            Assert.IsTrue(result is decimal);
            Assert.IsTrue((decimal)result == (decimal)2.12);

            var state = bindingContext.ModelState;
            Assert.IsTrue(state.IsValid);
            Assert.IsTrue(state.IsValidField(modelName));
            

        }
Beispiel #22
0
        public void CanBindModelWithNestedEntities()
        {
            int id = 2;
            string employeeName = "Michael";
            string managerName = "Tobias";
            string managerManagerName = "Scott";

            // Arrange
            var formCollection = new NameValueCollection
                                     {
                                         {"Employee.Id", id.ToString()},
                                         {"Employee.Name", employeeName},
                                         {"Employee.Manager.Name", managerName},
                                         {"Employee.Manager.Manager.Name", managerManagerName}
                                     };

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Employee));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "Employee",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };

            DefaultModelBinder target = new SharpModelBinder();

            ControllerContext controllerContext = new ControllerContext();

            // Act
            Employee result = (Employee)target.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreEqual(id, result.Id);
            Assert.AreEqual(employeeName, result.Name);
            Assert.AreEqual(managerName, result.Manager.Name);
            Assert.AreEqual(managerManagerName, result.Manager.Manager.Name);
        }
        public void TakeSurveySetsModelStateToFalseWithInvalidData()
        {
            //  Arrange
            //  1   Set up a name/value collection containing all view input values
            var formCollection = _mockData.SetTakeSurveyFormDataCompletedOK();
            //  2   Set up a ValueProvider for the name/value collection
            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            //  3   Get the Metadata from the ViewModel or class being bound
            var metaData = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TakeSurveyViewModel));
            //  4   Instantiate the bindingContext for the model binder
            var bindingContext = new ModelBindingContext()
            {
                ModelName = "TakeSurvey",
                ValueProvider = valueProvider,
                ModelMetadata = metaData
            };

            //  5   Set up a mock Httpcontext and populate the Request["fieldname"].Return values
            //          with no response for question 1
            var mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(c => c.Request["SurveyId"]).Returns("3");
            mockHttpContext.Setup(c => c.Request["item.QId_SeqNo"]).Returns("1_1,2_2");
            //            mockHttpContext.Setup(c => c.Request["LikertScaleNumber_1_1"]).Returns("2");
            mockHttpContext.Setup(c => c.Request["LikertScaleNumber_2_2"]).Returns("3");

            //  6   Set up the ControllerContext, containing the HttpContext as as HttpContext property of the controllercontext
            //      Don't think we need to do this bit here, the formcollection has everything needed already, nothing needs to
            //      be supplied in addition.
            ControllerContext controllerContext = new ControllerContext();
            controllerContext.HttpContext = mockHttpContext.Object;

            //  7   Instantiate the model Binder taking the ControllerContext and BindingContext as its parameters
            var binder = new TakeSurveyModelbinder();

            //  Act
            //  8   Execute the bindingContext BindModel method to test the binder
            var result = (TakeSurveyViewModel)binder.BindModel(controllerContext, bindingContext);

            //  Assert
            //  9   Check the values of the output viewModel / class
            Assert.AreEqual(3, result.SurveyId, "Expected Survey3 to be returned");
            Assert.AreEqual("3", result.Questions.Last().Answer, "Expected question2 to have answer 3");
            Assert.AreEqual("2_2", result.Questions.Last().QId_SeqNo, "Expected question2 to have QId_SeqNo of '2_2'");

            //  Check the contents of the ModelState.
            var modelErrors = bindingContext.ModelState.Values.First();     //  Gives the Model level errors, if any
            Assert.IsFalse(bindingContext.ModelState.IsValid, "Expected the ModelState to be invalid");
            Assert.AreEqual(1, modelErrors.Errors.Count(), "Expected one Model Error (key='') in the ModelState");
            var theError = modelErrors.Errors.First();      // OK as we only have one error anyway, confirmed by previous Assert.
            Assert.AreEqual("You have not answered question 1", theError.ErrorMessage, "Expected message 'You have not answered question 1'");
        }
Beispiel #24
0
        public void Should_parse_sort_info()
        {
            var idParser = new AlwaysTrueIdParser();
            var binder = new RestRequestModelBinder(null, null);

            var valueProvider = new NameValueCollectionValueProvider(
                new NameValueCollection {
                    { ":sort", "foo|asc,bar|DeSC,baz|ascending,bat|descending" },
                    { "id", idParser.FetchAllIdValue }
                },
                CultureInfo.InvariantCulture
            );

            var bindingContext = new ModelBindingContext {
                ValueProvider = valueProvider
            };

            var model = binder.BindModel(CreateControllerContext(), bindingContext);
            Assert.That(model, Is.TypeOf<RestRequest>());
            var request = (RestRequest)model;

            Assert.That(request.SortInfo, Has.Count.EqualTo(4));
            Assert.That(request.SortInfo[0].Field, Is.EqualTo("foo"));
            Assert.That(request.SortInfo[0].Order, Is.EqualTo(SortOrder.Ascending));
            Assert.That(request.SortInfo[1].Field, Is.EqualTo("bar"));
            Assert.That(request.SortInfo[1].Order, Is.EqualTo(SortOrder.Descending));
            Assert.That(request.SortInfo[2].Field, Is.EqualTo("baz"));
            Assert.That(request.SortInfo[2].Order, Is.EqualTo(SortOrder.Ascending));
            Assert.That(request.SortInfo[3].Field, Is.EqualTo("bat"));
            Assert.That(request.SortInfo[3].Order, Is.EqualTo(SortOrder.Descending));
        }
Beispiel #25
0
        public void ModelValidateDecTestFailRussian()
        {
            
            const string modelName = "Weight";
            var formCollection = new NameValueCollection { 
                    { modelName, "123qwe" }
            };


            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(MessageModel));

            var bindingContext = new ModelBindingContext
            {
                ModelName = modelName,
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };


            Thread.CurrentThread.CurrentCulture = GetRussianCulture();

            ControllerContext controllerContext = new ControllerContext();
            DecimalModelBinder b1 = new DecimalModelBinder();
            var result = b1.BindModel(controllerContext, bindingContext);


            Assert.IsNull(result);
            var state = bindingContext.ModelState;
            Assert.IsFalse(state.IsValid);
            Assert.IsFalse(state.IsValidField(modelName));


        }
Beispiel #26
0
        public void ModelValidateDecTestCommaInRussian()
        {
            var formCollection = new NameValueCollection { 
                    { "Weight", "2,12" }
            };


            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(MessageModel));

            var bindingContext = new ModelBindingContext
            {
                ModelName = "Weight",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            };
            Thread.CurrentThread.CurrentCulture = GetRussianCulture();

            ControllerContext controllerContext = new ControllerContext();
            DecimalModelBinder b1 = new DecimalModelBinder();
            var result = b1.BindModel(controllerContext, bindingContext);


            Assert.IsNotNull(result);
            Assert.IsTrue(result is decimal);
            Assert.IsTrue((decimal)result == (decimal)2.12);

            var state = bindingContext.ModelState;
            Assert.IsTrue(state.IsValid);

        }