Exemple #1
0
            public override IEnumerable <ModelValidationResult> Validate(object container)
            {
                bool propertiesValid = true;

                foreach (ModelMetadata propertyMetadata in Metadata.Properties)
                {
                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ControllerContext))
                    {
                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(Metadata.Model))
                        {
                            propertiesValid = false;
                            yield return(new ModelValidationResult
                            {
                                MemberName = DefaultModelBinder.CreateSubPropertyName(propertyMetadata.PropertyName, propertyResult.MemberName),
                                Message = propertyResult.Message
                            });
                        }
                    }
                }

                if (propertiesValid)
                {
                    foreach (ModelValidator typeValidator in Metadata.GetValidators(ControllerContext))
                    {
                        foreach (ModelValidationResult typeResult in typeValidator.Validate(container))
                        {
                            yield return(typeResult);
                        }
                    }
                }
            }
 public void SetUp()
 {
     binder = new DefaultModelBinder();
     controllerContext = new ControllerContext
     {
         HttpContext = MockRepository.GenerateStub<HttpContextBase>()
     };
     request = MockRepository.GenerateStub<HttpRequestBase>();
     controllerContext.HttpContext.Stub(x => x.Request).Return(request);
 }
Exemple #3
0
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     if (bindingContext.ModelType.IsInterface || bindingContext.ModelType.IsAbstract)
     {
         return Easy.Reflection.ClassAction.GetModel(ServiceLocator.Current.GetInstance(bindingContext.ModelType).GetType(), controllerContext.RequestContext.HttpContext.Request.Form);
     }
     else
     {
         DefaultModelBinder binder = new DefaultModelBinder();
         return binder.BindModel(controllerContext, bindingContext);
     }
 }
        public void all_parameters_are_bound()
        {
            var form = new FormCollection()
            {
                { "Name", "test_name" }
            };

            var context = new ModelBindingContext() { ValueProvider = form.ToValueProvider(), ModelType = typeof(CodeCamp) };

            var mb = new DefaultModelBinder();
            var codeCamp = (CodeCamp) mb.BindModel(null, context);

            Assert.That(codeCamp.Name, Is.EqualTo("test_name"));
        }
        public void ProceedAndWrapResultWithRuntimePolicyOnAndDefaultModelBinder(AlternateType<IModelBinder> alternateModelBinder, IAlternateMethodContext context, Type arg1, DefaultModelBinder returnValue, IModelBinder newModelBinder)
        {
            context.Setup(c => c.Arguments).Returns(new object[] { arg1 });
            context.Setup(c => c.ReturnValue).Returns(returnValue);
            alternateModelBinder.Setup(amb => amb.TryCreate(It.IsAny<IModelBinder>(), out newModelBinder, null, null)).Returns(true);

            var sut = new ModelBinderProvider.GetBinder(alternateModelBinder);
            sut.NewImplementation(context);

            context.TimerStrategy().Verify(t => t.Time(It.IsAny<Action>()));
            context.Verify(mb => mb.ReturnValue);
            context.Logger.Verify(l => l.Warn(It.IsAny<string>(), context.ReturnValue.GetType()), Times.Never());
            context.VerifySet(c => c.ReturnValue = newModelBinder);
            alternateModelBinder.Verify(amb => amb.TryCreate(It.IsAny<IModelBinder>(), out newModelBinder, null, null));
        }
        public string Get(ControllerContext controllerContext)
        {
            var defaultModelBinder = new DefaultModelBinder();

            var modelType = typeof(GiftCardInfo);
            var giftCardInfo = new GiftCardInfo();
            var metadataForType = ModelMetadataProviders.Current.GetMetadataForType(() => giftCardInfo, modelType);
            metadataForType.Model = giftCardInfo;
            var modelBindingContext = new ModelBindingContext
            {
                ModelMetadata = metadataForType,
                ValueProvider = new FormValueProvider(controllerContext)
            };
            var model = defaultModelBinder.BindModel(controllerContext, modelBindingContext) as GiftCardInfo;

            return model == null ? null : JsonConvert.SerializeObject(model);
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            DefaultModelBinder binder = new DefaultModelBinder();	// use the default model binder to do the dirty work

            ModelBindingContext listBindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => bindingContext.Model, bindingContext.ModelType),
                ModelName = bindingContext.ModelName,
                ModelState = bindingContext.ModelState,
                ValueProvider = bindingContext.ValueProvider,
                PropertyFilter = bindingContext.PropertyFilter
            };

            ImageList list = binder.BindModel(controllerContext, listBindingContext) as ImageList;

            return list;
        }
 private AccountController CreateAccountController(object ViewModel)
 {
     var accountController = new AccountController(MockingHelper.ApplicationManager);
     accountController.ControllerContext = MockingHelper.ControllerContext;
     if (ViewModel != null)
     {
         var modelBinder = new ModelBindingContext()
         {
             ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => ViewModel, ViewModel.GetType()),
             ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
         };
         var binder = new DefaultModelBinder().BindModel(accountController.ControllerContext, modelBinder);
         accountController.ModelState.Clear();
         accountController.ModelState.Merge(modelBinder.ModelState);
     }
     return accountController;
 }
Exemple #9
0
        public static object ConvertToObject(this FormDataCollection formDataCollection, Type type)
        {
            try
            {
                DefaultModelBinder binder = new DefaultModelBinder();
                ModelBindingContext modelBindingContext = new ModelBindingContext()
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, type),
                    ValueProvider = new FormValueProvider(formDataCollection.ReadAsNameValueCollection())
                };
                return binder.BindModel(new ControllerContext(), modelBindingContext);
            }
            catch (Exception)
            {

                return null;
            }
        }
        public static ModelStateDictionary ReturnModelState(this TestModel model)
        {
            var testController = new TestController();

            var modelBinder = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                                  () => model, model.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(
                                    new NameValueCollection(), CultureInfo.InvariantCulture)
            };
            var binder = new DefaultModelBinder().BindModel(
                             new ControllerContext(), modelBinder);
            testController.ModelState.Clear();
            testController.ModelState.Merge(modelBinder.ModelState);

            var viewResult = (ViewResult) testController.ValidDateTestModel(model);
            return viewResult.ViewData.ModelState;
        }
        public void BindComplexModelCanBindArrays() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;

            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int[]),
                PropertyFilter = _ => false,
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "foo[0]", null }, { "foo[1]", null }, { "foo[2]", null } }
            };

            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();
            mockInnerBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(int), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.PropertyFilter, bc.PropertyFilter, "PropertyFilter was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockInnerBinder.Object }
                }
            };

            // Act
            object newModel = binder.BindComplexModel(controllerContext, bindingContext);

            // Assert
            Assert.IsInstanceOfType(newModel, typeof(int[]));
            int[] newIntArray = (int[])newModel;

            Assert.AreEqual(3, newIntArray.Length, "Model is not of correct length.");
            Assert.AreEqual(0, newIntArray[0]);
            Assert.AreEqual(1, newIntArray[1]);
            Assert.AreEqual(2, newIntArray[2]);
        }
        public void BindSimpleModelCanReturnArrayTypes() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(42, null, null);
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int[])
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);

            // Assert
            Assert.IsInstanceOfType(returnedValue, typeof(int[]), "Returned value was of incorrect type.");

            int[] returnedValueAsIntArray = (int[])returnedValue;
            Assert.AreEqual(1, returnedValueAsIntArray.Length);
            Assert.AreEqual(42, returnedValueAsIntArray[0]);
        }
        public void BindModelReturnsNullIfSimpleTypeNotFound() {
            // DevDiv 216165: ModelBinders should not try and instantiate simple types

            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "prefix",
                ModelType = typeof(string),
                ValueProvider = new ValueProviderDictionary(null) {
                    { "prefix.foo", new ValueProviderResult("foo", "foo", null) },
                    { "prefix.bar", new ValueProviderResult("bar", "bar", null) }
                }
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object updatedModel = binder.BindModel(null, bindingContext);

            // Assert
            Assert.IsNull(updatedModel);
        }
        public void BindModelWithPrefixReturnsNullIfFallbackNotSpecifiedAndValueProviderContainsNoEntries() {
            // Arrange
            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute() {
                Foo = "FooPreValue",
                Bar = "BarPreValue",
                Baz = "BazPreValue",
            };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = "prefix",
                ModelType = typeof(ModelWithoutBindAttribute),
                ValueProvider = new ValueProviderDictionary(null) {
                    { "foo", new ValueProviderResult("FooPostValue", "FooPostValue", null) },
                    { "bar", new ValueProviderResult("BarPostValue", "BarPostValue", null) }
                }
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object updatedModel = binder.BindModel(null, bindingContext);

            // Assert
            Assert.IsNull(updatedModel);
        }
        public void BindComplexModelCanBindDictionaries() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;

            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelType = typeof(IDictionary<int, string>),
                ModelName = "foo",
                PropertyFilter = _ => false,
                ValueProvider = new Dictionary<string, ValueProviderResult>() {
                    { "foo[0].key", null }, { "foo[0].value", null },
                    { "foo[1].key", null }, { "foo[1].value", null },
                    { "foo[2].key", null }, { "foo[2].value", null }
                }
            };

            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            mockIntBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(int), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(new ModelBindingContext().PropertyFilter, bc.PropertyFilter, "PropertyFilter should not have been set.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10;
                    });

            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();
            mockStringBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(string), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.PropertyFilter, bc.PropertyFilter, "PropertyFilter was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + "Value";
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockIntBinder.Object },
                    { typeof(string), mockStringBinder.Object }
                }
            };

            // Act
            object newModel = binder.BindComplexModel(controllerContext, bindingContext);

            // Assert
            Assert.IsInstanceOfType(newModel, typeof(IDictionary<int, string>));
            IDictionary<int, string> modelAsDictionary = (IDictionary<int, string>)newModel;

            Assert.AreEqual(3, modelAsDictionary.Count, "Model is not of correct length.");
            Assert.AreEqual("10Value", modelAsDictionary[10]);
            Assert.AreEqual("11Value", modelAsDictionary[11]);
            Assert.AreEqual("12Value", modelAsDictionary[12]);
        }
        public void BindSimpleModelChecksValueProviderResultRawValueType() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(new MemoryStream(), null, null);
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(Stream)
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);

            // Assert
            Assert.AreEqual(result, bindingContext.ModelState["foo"].Value, "ModelState should have been set.");
            Assert.AreSame(result.RawValue, returnedValue, "Should have returned the RawValue since it was of the correct type.");
        }
        public void UpdateCollectionCreatesDefaultEntriesForInvalidElements() {
            // Arrange
            List<int> model = new List<int>() { 4, 5, 6, 7, 8 };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = "foo",
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "foo[0]", null }, { "foo[1]", null }, { "foo[2]", null } }
            };

            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();
            mockInnerBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        int fooIdx = Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);
                        return (fooIdx == 1) ? (object)null : fooIdx;
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockInnerBinder.Object }
                }
            };

            // Act
            object updatedModel = binder.UpdateCollection(null, bindingContext, typeof(int));

            // Assert
            Assert.AreEqual(3, model.Count, "Model is not of correct length.");
            Assert.AreEqual(false, bindingContext.ModelState.IsValidField("foo[1]"), "Conversion should have failed.");
            Assert.AreEqual("A value is required.", bindingContext.ModelState["foo[1]"].Errors[0].ErrorMessage, "Error message did not propagate correctly.");
            Assert.AreEqual(0, model[0]);
            Assert.AreEqual(0, model[1]);
            Assert.AreEqual(2, model[2]);
        }
        public void BindModelCanBindObjects() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;

            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute() {
                Foo = "FooPreValue",
                Bar = "BarPreValue",
                Baz = "BazPreValue",
            };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelType = typeof(ModelWithoutBindAttribute),
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "Foo", null }, { "Bar", null } }
            };

            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();
            mockInnerBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "Value provider was not forwarded correctly.");
                        return bc.ModelName + "PostValue";
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(string), mockInnerBinder.Object }
                }
            };

            // Act
            object updatedModel = binder.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.AreSame(model, updatedModel, "Should have returned same instance of the model.");
            Assert.AreEqual("FooPostValue", model.Foo, "Foo property should have been updated.");
            Assert.AreEqual("BarPostValue", model.Bar, "Bar property should have been updated.");
            Assert.AreEqual("BazPreValue", model.Baz, "Baz property shouldn't have been updated since it wasn't part of the request.");
        }
        public void BindComplexModelReturnsNullArrayIfNoValuesProvided() {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int[]),
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "foo", null } }
            };

            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();
            mockInnerBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockInnerBinder.Object }
                }
            };

            // Act
            object newModel = binder.BindComplexModel(null, bindingContext);

            // Assert
            Assert.IsNull(newModel, "Method should have returned null.");
        }
        public void UpdateDictionarySkipsInvalidKeys() {
            // Arrange
            Dictionary<int, string> model = new Dictionary<int, string>{
                { 1, "one" },
                { 2, "two" }
            };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = "foo",
                ValueProvider = new Dictionary<string, ValueProviderResult>() {
                    { "foo[0].key", null }, { "foo[0].value", null },
                    { "foo[1].key", null }, { "foo[1].value", null },
                    { "foo[2].key", null }, { "foo[2].value", null }
                }
            };

            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            mockIntBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        int fooIdx = Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);
                        return (fooIdx == 1) ? (object)null : fooIdx;
                    });

            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();
            mockStringBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + "Value";
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockIntBinder.Object },
                    { typeof(string), mockStringBinder.Object }
                }
            };

            // Act
            object updatedModel = binder.UpdateDictionary(null, bindingContext, typeof(int), typeof(string));

            // Assert
            Assert.AreEqual(2, model.Count, "Model is not of correct length.");
            Assert.AreEqual(false, bindingContext.ModelState.IsValidField("foo[1].key"), "Conversion should have failed.");
            Assert.AreEqual("A value is required.", bindingContext.ModelState["foo[1].key"].Errors[0].ErrorMessage, "Error message did not propagate correctly.");
            Assert.AreEqual("10Value", model[0]);
            Assert.AreEqual("12Value", model[2]);
        }
        public void UpdateDictionaryReturnsNullIfNoValidElementsFound() {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ValueProvider = new Dictionary<string, ValueProviderResult>()
            };
            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object updatedModel = binder.UpdateDictionary(null, bindingContext, typeof(object), typeof(object));

            // Assert
            Assert.IsNull(updatedModel, "Method should return null if no values exist as part of the request.");
        }
        public void UpdateDictionaryReturnsModifiedDictionaryOnSuccess() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;

            Dictionary<int, string> model = new Dictionary<int, string>{
                { 1, "one" },
                { 2, "two" }
            };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = "foo",
                PropertyFilter = _ => false,
                ValueProvider = new Dictionary<string, ValueProviderResult>() {
                    { "foo[0].key", null }, { "foo[0].value", null },
                    { "foo[1].key", null }, { "foo[1].value", null },
                    { "foo[2].key", null }, { "foo[2].value", null }
                }
            };

            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            mockIntBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(int), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(new ModelBindingContext().PropertyFilter, bc.PropertyFilter, "PropertyFilter should not have been set.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10;
                    });

            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();
            mockStringBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(string), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.PropertyFilter, bc.PropertyFilter, "PropertyFilter was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + "Value";
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockIntBinder.Object },
                    { typeof(string), mockStringBinder.Object }
                }
            };

            // Act
            object updatedModel = binder.UpdateDictionary(controllerContext, bindingContext, typeof(int), typeof(string));

            // Assert
            Assert.AreSame(model, updatedModel, "Should have updated the provided model object.");
            Assert.AreEqual(3, model.Count, "Model is not of correct length.");
            Assert.AreEqual("10Value", model[10]);
            Assert.AreEqual("11Value", model[11]);
            Assert.AreEqual("12Value", model[12]);
        }
        public void BindSimpleModelCanReturnCollectionTypes() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(new string[] { "42", "82" }, null, null);
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(IEnumerable<int>)
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);

            // Assert
            Assert.IsInstanceOfType(returnedValue, typeof(IEnumerable<int>), "Returned value was of incorrect type.");
            List<int> returnedValueAsList = ((IEnumerable<int>)returnedValue).ToList();

            Assert.AreEqual(2, returnedValueAsList.Count);
            Assert.AreEqual(42, returnedValueAsList[0]);
            Assert.AreEqual(82, returnedValueAsList[1]);
        }
        public void BindSimpleModelCanReturnStrings() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult(new object[] { "42" }, null, null);
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(string)
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);

            // Assert
            Assert.AreEqual("42", returnedValue);
        }
        public void BindModelReturnsNullIfKeyNotFound() {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int),
                ValueProvider = new Dictionary<string, ValueProviderResult>()
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedModel = binder.BindModel(null, bindingContext);

            // Assert
            Assert.IsNull(returnedModel);
        }
        public void BindSimpleModelPropagatesErrorsOnFailure() {
            // Arrange
            ValueProviderResult result = new ValueProviderResult("invalid", null, null);
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int)
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);

            // Assert
            Assert.IsFalse(bindingContext.ModelState.IsValidField("foo"), "Foo should be an invalid field.");
            Assert.IsInstanceOfType(bindingContext.ModelState["foo"].Errors[0].Exception, typeof(InvalidOperationException));
            Assert.AreEqual("The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information.", bindingContext.ModelState["foo"].Errors[0].Exception.Message);
            Assert.IsNull(returnedValue, "Should have returned null on failure.");
        }
        public void BindModelThrowsIfBindingContextIsNull() {
            // Arrange
            DefaultModelBinder binder = new DefaultModelBinder();

            // Act & assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    binder.BindModel(null, null);
                }, "bindingContext");
        }
Exemple #28
0
        protected void Application_Start()
        {
            _Logger = _Kernel.Get<ILogger>();

            _Logger.Info("Application Started");

            // Inject account repository into our custom membership & role providers.
            _Kernel.Inject(Membership.Provider);
            _Kernel.Inject(Roles.Provider);

            LocalisationDynamicNodeProvider.RegisterKernel(_Kernel);
            ModelFactory.RegisterKernel(_Kernel);
            PaymentHandlerFactory.RegisterKernel(_Kernel);

            InitialiseAdmin();

            //Inject
            ControllerBuilder.Current.SetControllerFactory(new NinjectControlerFactory(_Kernel));

            //routes
            AreaRegistration.RegisterAllAreas();
            XmlSiteMapController.RegisterRoutes(RouteTable.Routes);
            GlobalFilters.Filters.Add(new RedirectMobileDevicesToMobileAreaAttribute(), 1);
            RegisterRoutes(RouteTable.Routes);
            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

            //model binder
            var defaultBinder = new DefaultModelBinder();
            ModelBinders.Binders.DefaultBinder = defaultBinder;
            ModelBinders.Binders.Add(typeof(Localisation), new LocalisationBinder(defaultBinder));
            ModelBinders.Binders.Add(typeof(Rental), new RentalBinder(defaultBinder));
            ModelBinders.Binders.Add(typeof(Offer), new OfferBinder(defaultBinder));
            ModelBinders.Binders.Add(typeof(LocalisationCart), new LocalisationCartBinder(defaultBinder));

            //resources
            DefaultModelBinder.ResourceClassKey = "Messages";
        }
        public void BindModelWithPrefixAndFallback() {
            // Arrange
            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute() {
                Foo = "FooPreValue",
                Bar = "BarPreValue",
                Baz = "BazPreValue",
            };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                FallbackToEmptyPrefix = true,
                Model = model,
                ModelName = "prefix",
                ModelType = typeof(ModelWithoutBindAttribute),
                ValueProvider = new ValueProviderDictionary(null) {
                    { "foo", new ValueProviderResult("FooPostValue", "FooPostValue", null) },
                    { "bar", new ValueProviderResult("BarPostValue", "BarPostValue", null) }
                }
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object updatedModel = binder.BindModel(null, bindingContext);

            // Assert
            Assert.AreSame(model, updatedModel, "Should have returned same instance of the model.");
            Assert.AreEqual("FooPostValue", model.Foo, "Foo property should have been updated.");
            Assert.AreEqual("BarPostValue", model.Bar, "Bar property should have been updated.");
            Assert.AreEqual("BazPreValue", model.Baz, "Baz property shouldn't have been updated since it wasn't part of the request.");
        }
        public void BindModelCanBindSimpleTypes() {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext() {
                ModelName = "foo",
                ModelType = typeof(int),
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "foo", new ValueProviderResult("42", "42", null) } }
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            // Act
            object updatedModel = binder.BindModel(null, bindingContext);

            // Assert
            Assert.AreEqual(42, updatedModel);
        }
        public void UpdateCollectionReturnsModifiedCollectionOnSuccess() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;

            List<int> model = new List<int>() { 4, 5, 6, 7, 8 };
            ModelBindingContext bindingContext = new ModelBindingContext() {
                Model = model,
                ModelName = "foo",
                PropertyFilter = _ => false,
                ValueProvider = new Dictionary<string, ValueProviderResult>() { { "foo[0]", null }, { "foo[1]", null }, { "foo[2]", null } }
            };

            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();
            mockInnerBinder
                .Expect(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ModelBindingContext bc) {
                        Assert.AreEqual(controllerContext, cc, "ControllerContext was not forwarded correctly.");
                        Assert.AreEqual(typeof(int), bc.ModelType, "ModelType was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ModelState, bc.ModelState, "ModelState was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.PropertyFilter, bc.PropertyFilter, "PropertyFilter was not forwarded correctly.");
                        Assert.AreEqual(bindingContext.ValueProvider, bc.ValueProvider, "ValueProvider was not forwarded correctly.");
                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);
                    });

            DefaultModelBinder binder = new DefaultModelBinder() {
                Binders = new ModelBinderDictionary() {
                    { typeof(int), mockInnerBinder.Object }
                }
            };

            // Act
            object updatedModel = binder.UpdateCollection(controllerContext, bindingContext, typeof(int));

            // Assert
            Assert.AreSame(model, updatedModel, "Should have updated the provided model object.");
            Assert.AreEqual(3, model.Count, "Model is not of correct length.");
            Assert.AreEqual(0, model[0]);
            Assert.AreEqual(1, model[1]);
            Assert.AreEqual(2, model[2]);
        }