public void Constuct(IProxyFactory proxyFactory) { var sut = new ModelBinder(proxyFactory); Assert.NotNull(sut); Assert.IsAssignableFrom<AlternateType<IModelBinder>>(sut); }
private void SetupModelBinders(IInspectorContext context) { var alternateModelBinder = new ModelBinder(context.ProxyFactory); var binders = ModelBinders.Binders; var keys = binders.Keys.ToArray(); for (int i = 0; i < keys.Length; i++) { var type = keys[i]; var originalBinder = binders[type]; IModelBinder newBinder; if (alternateModelBinder.TryCreate(originalBinder, out newBinder)) { context.Logger.Info(Resources.ModelBinderInspectorSetupReplacedModelBinder, originalBinder.GetType()); binders[type] = newBinder; } } // handle default binder var originalDefaultBinder = ModelBinders.Binders.DefaultBinder as DefaultModelBinder; IModelBinder newDefaultBinder; if (originalDefaultBinder != null && alternateModelBinder.TryCreate(originalDefaultBinder, out newDefaultBinder)) { context.Logger.Info(Resources.ModelBinderInspectorSetupReplacedModelBinder, originalDefaultBinder.GetType()); ModelBinders.Binders.DefaultBinder = newDefaultBinder; } }
public void Bind() { if (Model != null) { ModelBinder mb = new ModelBinder(Model); RequestBinder = mb; } }
public void ProceedAndReturnWithRuntimePolicyOff(ModelBinder.BindModel sut, IAlternateMethodContext context) { context.Setup(c => c.RuntimePolicyStrategy).Returns(() => RuntimePolicy.Off); sut.NewImplementation(context); context.Verify(c => c.Proceed()); context.MessageBroker.Verify(mb => mb.Publish(It.IsAny<object>()), Times.Never()); }
public void ProceedPublishMessageWithRuntimePolicyOn(ModelBinder.BindModel sut, IAlternateMethodContext context, ControllerContext arg1, ModelBindingContext arg2) { context.Setup(c => c.Arguments).Returns(new object[] { arg1, arg2 }); sut.NewImplementation(context); context.TimerStrategy().Verify(t => t.Time(It.IsAny<Action>())); context.MessageBroker.Verify(mb => mb.Publish(It.IsAny<ModelBinder.BindModel.Message>())); }
public void ProceedAndPublishMessageWithRuntimePolicyOn(ModelBinder.BindProperty sut, IAlternateMethodContext context, ControllerContext controllerContext, ModelBindingContext modelBindingContext, PropertyDescriptor propertyDescriptor) { context.Setup(c => c.Arguments).Returns(new object[] { controllerContext, modelBindingContext, propertyDescriptor }); sut.NewImplementation(context); context.TimerStrategy().Verify(c => c.Time(It.IsAny<Action>())); context.MessageBroker.Verify(mb => mb.Publish(It.IsAny<ModelBinder.BindProperty.Message>())); }
public void Setup(IInspectorContext context) { var originalDefaultBinder = ModelBinders.Binders.DefaultBinder; IModelBinder newDefaultBinder; var alternateModelBinder = new ModelBinder(context.ProxyFactory); if (originalDefaultBinder != null && alternateModelBinder.TryCreate(originalDefaultBinder, out newDefaultBinder)) { context.Logger.Info(Resources.ModelBinderInspectorSetupReplacedModelBinder, originalDefaultBinder.GetType()); ModelBinders.Binders.DefaultBinder = newDefaultBinder; } }
public void Awake() { uManager = BaseGameManager.Instance; BaseGameManager.SetInstance(uManager); _commandMap = uManager.commandMap; _modelMap = uManager.modelMap; _mediatorMap = uManager.mediatorMap; _dispatcher = uManager.dispatcher; Init(); Bindings(); }
public void Types_having_constructors_accepting_a_single_string_are_bound_using_the_handler_parameter_name() { var tempPath = Path.GetTempPath(); var option = new Option("--value") { Argument = new Argument <DirectoryInfo>() }; var command = new Command("the-command"); command.AddOption(option); var binder = new ModelBinder(typeof(ClassWithCtorParameter <DirectoryInfo>)); var bindingContext = new BindingContext(command.Parse($"--value \"{tempPath}\"")); var instance = (ClassWithCtorParameter <DirectoryInfo>)binder.CreateInstance(bindingContext); instance.Value.FullName.Should().Be(tempPath); }
public IEnumerable <Document> GetDocuments() { var documentsEntities = _queryProcessor.GetDocuments(); if (documentsEntities != null) { var documentsList = new List <Document>(); foreach (var entity in documentsEntities) { documentsList.Add(ModelBinder.CreateDocumentModel(entity)); } return(documentsList); } else { throw new RootObjectNotFoundException("Documents not found"); } }
public void Explicitly_configured_default_values_can_be_bound_by_name_to_property_setters() { var argument = new Argument <string>("the default"); var option = new Option("--value", argument: argument); var command = new Command("the-command"); command.AddOption(option); var binder = new ModelBinder(typeof(ClassWithSetter <string>)); var parser = new Parser(command); var bindingContext = new BindingContext(parser.Parse("")); var instance = (ClassWithSetter <string>)binder.CreateInstance(bindingContext); instance.Value.Should().Be("the default"); }
public void Explicitly_configured_default_values_can_be_bound_by_name_to_constructor_parameters() { var option = new Option("--string-option") { Argument = new Argument <string>(() => "the default") }; var command = new Command("the-command"); command.AddOption(option); var binder = new ModelBinder(typeof(ClassWithMultiLetterCtorParameters)); var parser = new Parser(command); var bindingContext = new BindingContext(parser.Parse("")); var instance = (ClassWithMultiLetterCtorParameters)binder.CreateInstance(bindingContext); instance.StringOption.Should().Be("the default"); }
public void Explicit_model_binder_binds_only_to_configured_properties() { var intOption = new Option <int>("--int-property"); var stringOption = new Option <string>("--string-property"); var parser = new Parser(intOption, stringOption); var bindingContext = new BindingContext(parser.Parse("--int-property 42 --string-property Hello")); var binder = new ModelBinder <ClassWithMultiLetterSetters> { EnforceExplicitBinding = true }; binder.BindMemberFromValue(obj => obj.IntOption, intOption); var instance = binder.CreateInstance(bindingContext) as ClassWithMultiLetterSetters; instance.Should().NotBeNull(); instance.IntOption.Should().Be(42); instance.StringOption.Should().BeNull(); }
public void PropertyInfo_can_be_bound_to_option() { var command = new Command("the-command"); var option = new Option <int>("--fred"); command.Add(option); var type = typeof(ClassWithMultiLetterSetters); var binder = new ModelBinder(type); var propertyInfo = type.GetProperties()[0]; binder.BindMemberFromValue(propertyInfo, option); var bindingContext = new BindingContext(command.Parse("the-command --fred 42")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(42); }
public void PropertyExpression_can_be_bound_to_option() { var command = new Command("the-command"); var option = new Option <int>("--fred"); command.AddOption(option); var binder = new ModelBinder <ClassWithMultiLetterSetters>(); binder.BindMemberFromValue( i => i.IntOption, option); var bindingContext = new BindingContext(command.Parse("the-command --fred 42")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(42); }
public IEnumerable <File> GetFiles() { var filesEntities = _allFilesQueryProcessor.GetFiles(); if (filesEntities != null) { var filesList = new List <File>(); foreach (var entity in filesEntities) { filesList.Add(ModelBinder.CreateFileModel(entity)); } return(filesList); } else { throw new RootObjectNotFoundException("Files not found."); } }
public void PropertyExpression_can_be_bound_to_argument() { var command = new Command("the-command"); var argument = new Argument <int> { Arity = ArgumentArity.ExactlyOne }; command.AddArgument(argument); var binder = new ModelBinder <ClassWithMultiLetterSetters>(); binder.BindMemberFromValue(i => i.IntOption, argument); var bindingContext = new BindingContext(command.Parse("the-command 42")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(42); }
public void Init_WhenGivenValidXml_ShouldReturnItemsInCorrectOrder() { var xml = "<items><item id=\"3\" sortOrder=\"3\"><documentName nodeName=\"\" nodeType=\"0\">Manual</documentName><documentUrl nodeName=\"\" nodeType=\"0\">http://jotul.com/no/produkter.xml/_attachment/6306?_download=true&_ts=13ab17f5a82</documentUrl></item><item id=\"0\" sortOrder=\"1\"><documentName nodeName=\"\" nodeType=\"0\">Manual</documentName><documentUrl nodeName=\"\" nodeType=\"0\">http://jotul.com/no/produkter.xml/_attachment/6306?_download=true&_ts=13ab17f5a82</documentUrl></item><item id=\"1\" sortOrder=\"2\"><documentName nodeName=\"\" nodeType=\"0\">FDV dokumentasjon</documentName><documentUrl nodeName=\"\" nodeType=\"0\">http://jotul.com/no/produkter.xml/_attachment/6305?_download=true&_ts=13ab17f1573</documentUrl></item><item id=\"4\" sortOrder=\"0\"><documentName nodeName=\"\" nodeType=\"0\">FDV dokumentasjon</documentName><documentUrl nodeName=\"\" nodeType=\"0\">http://jotul.com/no/produkter.xml/_attachment/6305?_download=true&_ts=13ab17f1573</documentUrl></item></items>"; var modelBinder = new ModelBinder(); object o; var result = modelBinder.Init(0, xml, out o); Assert.IsTrue(result); var c = (GridRowCollection)o; Assert.IsTrue(c[0].SortOrder == 0); Assert.IsTrue(c[1].SortOrder == 1); Assert.IsTrue(c[2].SortOrder == 2); Assert.IsTrue(c[3].SortOrder == 3); }
public void Values_from_parent_command_arguments_are_bound_by_name_by_default() { var parentCommand = new Command("parent-command") { new Argument <int> { Name = nameof(ClassWithMultiLetterSetters.IntOption) }, new Command("child-command") }; var binder = new ModelBinder <ClassWithMultiLetterSetters>(); var parseResult = parentCommand.Parse("parent-command 123 child-command"); var bindingContext = new BindingContext(parseResult); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(123); }
public void stdio_command_working_dir_can_be_specified() { // StartupOptions.WorkingDir is of type DirectoryInfo which normalizes paths to OS type and ensures that // they're rooted. To ensure proper testing behavior we have to give an os-specific path. var workingDir = Environment.OSVersion.Platform switch { PlatformID.Win32NT => "C:\\some\\dir", _ => "/some/dir" }; var result = _parser.Parse($"stdio --working-dir {workingDir}"); var binder = new ModelBinder <StartupOptions>(); var options = (StartupOptions)binder.CreateInstance(new BindingContext(result)); options.WorkingDir.FullName .Should() .Be(workingDir); }
public void Property_setters_with_no_default_value_and_no_matching_option_are_not_called() { var command = new Command("the-command") { new Option("--string-option") { Argument = new Argument <string>() } }; var binder = new ModelBinder(typeof(ClassWithSettersAndCtorParametersWithDifferentNames)); var parser = new Parser(command); var bindingContext = new BindingContext( parser.Parse("")); var instance = (ClassWithSettersAndCtorParametersWithDifferentNames)binder.CreateInstance(bindingContext); instance.StringOption.Should().Be("the default"); }
public void CamelCase_WithoutDrawWithoutValidation() { // Arrange var binder = new ModelBinder(); var modelBindingContext = TestHelper.MockModelBindingContextWithCamelCase(null, "13", "99", "mockSearchValue", "true"); var options = new Options().DisableDrawValidation(); // Act //var model = (Core.IDataTablesRequest)binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters).Model; binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters); var model = modelBindingContext.Result.IsModelSet ? (Core.IDataTablesRequest)modelBindingContext.Result.Model : null; // Assert Assert.Equal(0, model.Draw); Assert.Equal(13, model.Length); Assert.Equal(99, model.Start); Assert.Equal("mockSearchValue", model.Search.Value); Assert.Equal(true, model.Search.IsRegex); }
public void Values_from_options_on_parent_commands_can_be_bound_regardless_of_naming() { var childCommand = new Command("child-command"); var option = new Option <int>("-x"); var parentCommand = new Command("parent-command") { option, childCommand }; var binder = new ModelBinder <ClassWithMultiLetterSetters>(); binder.BindMemberFromValue(c => c.IntOption, option); var bindingContext = new BindingContext( parentCommand.Parse("parent-command -x 123 child-command") ); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(123); }
public void Should_get_entity_from_repository_by_id_on_query_string() { Guid guid = Guid.NewGuid(); var repository = MockRepository.GenerateMock <TRepository>(); var entity = new TEntity(); repository.Stub(r => r.GetById(guid)).Return(entity); var binder = new ModelBinder <TEntity, TRepository>(repository); ControllerContext controllerContext1 = GetControllerContext("fooId", guid.ToString()); //capitalize ControllerContext controllerContext2 = GetControllerContext("barid", guid.ToString()); //lowercase ModelBindingContext modelBindingContext = CreateBindingContext("fooid", guid.ToString()); var result = binder.BindModel(controllerContext1, modelBindingContext); Assert.That(result.Value, Is.EqualTo(entity)); ModelBindingContext modelBindingContext2 = CreateBindingContext("barid", guid.ToString()); result = binder.BindModel(controllerContext2, modelBindingContext2); Assert.That(result.Value, Is.EqualTo(entity)); }
public void PropertyInfo_can_be_bound_to_command() { var command = new Command("the-command"); var argument = new Argument <int>(); command.Argument = argument; var type = typeof(ClassWithMultiLetterSetters); var binder = new ModelBinder(type); var propertyInfo = type.GetProperties().First(); binder.BindMemberFromValue( propertyInfo, command); var bindingContext = new BindingContext(command.Parse("the-command 42")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(42); }
public void Option_arguments_are_bound_by_name_to_constructor_parameters( Type type, string commandLine, object expectedValue) { var targetType = typeof(ClassWithCtorParameter <>).MakeGenericType(type); var binder = new ModelBinder(targetType); var command = new Command("the-command") { new Option("--value", argumentType: type) }; var bindingContext = new BindingContext(command.Parse(commandLine)); var instance = binder.CreateInstance(bindingContext); object valueReceivedValue = ((dynamic)instance).Value; valueReceivedValue.Should().Be(expectedValue); }
public void Values_from_parent_command_arguments_can_be_bound_regardless_of_naming() { var childCommand = new Command("child-command"); var parentCommand = new Command("parent-command", argument: new Argument <int>()) { childCommand }; var binder = new ModelBinder <ClassWithMultiLetterSetters>(); binder.BindMemberFromCommand( c => c.IntOption, parentCommand); var bindingContext = new BindingContext(parentCommand.Parse("parent-command 123 child-command")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(123); }
public void PropertyInfo_can_be_bound_to_argument() { var command = new Command("the-command"); var argument = new Argument <int> { Arity = ArgumentArity.ExactlyOne }; command.AddArgument(argument); var type = typeof(ClassWithMultiLetterSetters); var binder = new ModelBinder(type); var propertyInfo = type.GetProperty(nameof(ClassWithMultiLetterSetters.IntOption)); binder.BindMemberFromValue(propertyInfo, argument); var bindingContext = new BindingContext(command.Parse("the-command 42")); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(42); }
public void Default_values_from_options_on_parent_commands_are_bound_by_name_by_default() { var parentCommand = new Command("parent-command") { new Option("--int-option") { Argument = new Argument <int>(() => 123) }, new Command("child-command") }; var binder = new ModelBinder <ClassWithMultiLetterSetters>(); var parseResult = parentCommand.Parse("parent-command child-command"); var bindingContext = new BindingContext(parseResult); var instance = (ClassWithMultiLetterSetters)binder.CreateInstance(bindingContext); instance.IntOption.Should().Be(123); }
public async Task <int> InvokeAsync(InvocationContext context) { var bindingContext = context.BindingContext; var(boundValues, _) = ModelBinder.GetBoundValues( invokeArgumentBindingSources, bindingContext, _methodDescriptor.ParameterDescriptors, _enforceExplicitBinding); var invocationArguments = boundValues .Select(x => x.Value) .ToArray(); object result; if (_handlerDelegate is null) { var invocationTarget = _invocationTarget ?? bindingContext.ServiceProvider.GetService(_handlerMethodInfo !.DeclaringType); if (invocationTarget is { })
public void Command_arguments_are_bound_by_name_to_property_setters( Type type, string commandLine, object expectedValue) { var targetType = typeof(ClassWithSetter <>).MakeGenericType(type); var binder = new ModelBinder(targetType); var command = new Command("the-command") { ArgumentBuilder.CreateArgument(type) }; var parser = new Parser(command); var bindingContext = new InvocationContext(parser.Parse(commandLine)).BindingContext; var instance = binder.CreateInstance(bindingContext); object valueReceivedValue = ((dynamic)instance).Value; valueReceivedValue.Should().Be(expectedValue); }
public void CamelCase_WithAditionalParametersWithoutEnableAditionalParameters() { // Arrange var binder = new ModelBinder(); var modelBindingContext = TestHelper.MockModelBindingContextWithCamelCase("3", "13", "99", "mockSearchValue", "true", new Dictionary <string, object>() { { "firstParameter", "firstValue" }, { "secondParameter", 7 } }); var options = new Options(); // Act //var model = (Core.IDataTablesRequest)binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters).Model; binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters); var model = modelBindingContext.Result.IsModelSet ? (Core.IDataTablesRequest)modelBindingContext.Result.Model : null; // Assert Assert.Equal(3, model.Draw); Assert.Equal(null, model.AdditionalParameters); }
public void Explicit_model_binder_binds_only_to_configured_ctor_parameters() { var intOption = new Option <int>("-a"); var stringOption = new Option <string>("-b"); var parser = new Parser(intOption, stringOption); var ctor = typeof(ClassWithMultiLetterCtorParameters) .GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0]; var paramInfo = ctor.GetParameters()[0]; var bindingContext = new BindingContext(parser.Parse("-a 42 -b Hello")); var binder = new ModelBinder <ClassWithMultiLetterCtorParameters> { EnforceExplicitBinding = true }; binder.BindConstructorArgumentFromValue(paramInfo, intOption); var instance = binder.CreateInstance(bindingContext) as ClassWithMultiLetterCtorParameters; instance.Should().NotBeNull(); instance.IntOption.Should().Be(42); instance.StringOption.Should().Be("the default"); }
public ObjectBinder( TModel target, string cmdName, IRootObjectModel parentModel = null, string cmdDescription = null ) { if (string.IsNullOrEmpty(cmdName) && parentModel != null) { throw new ArgumentException( $"If you specify an {nameof(IObjectModel)} you must also specify a {nameof(cmdName)}"); } if (target == null) { throw new NullReferenceException(nameof(target)); } Command = parentModel == null ? new RootCommand(cmdDescription) : new Command(cmdName, cmdDescription); Target = target; ModelBinder = new ModelBinder <TModel>(); }
public void Command_arguments_are_bound_by_name_to_complex_constructor_parameters( Type type, string commandLine) { var targetType = typeof(ClassWithCtorParameter <>).MakeGenericType(type); var binder = new ModelBinder(targetType); var command = new Command("the-command") { ArgumentBuilder.CreateArgument(type) }; var bindingContext = new InvocationContext(command.Parse(commandLine)).BindingContext; var instance = binder.CreateInstance(bindingContext); object valueReceivedValue = ((dynamic)instance).Value; var expectedValue = new FileInfo(commandLine); valueReceivedValue.Should().BeOfType <FileInfo>(); var fileInfoValue = valueReceivedValue as FileInfo; fileInfoValue.FullName.Should().Be(expectedValue.FullName); }
public void HungarianNotation_CompleteValues() { // Arrange var binder = new ModelBinder(); var modelBindingContext = TestHelper.MockModelBindingContextWithHungarianNotation("3", "13", "99", "mockSearchValue", "true"); var options = new Options().UseHungarianNotation(); // Act //var model = (Core.IDataTablesRequest)binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters).Model; binder.BindModel(modelBindingContext, options, TestHelper.ParseAdditionalParameters); var model = modelBindingContext.Result.IsModelSet ? (Core.IDataTablesRequest)modelBindingContext.Result.Model : null; // Assert Assert.Equal(3, model.Draw); Assert.Equal(13, model.Length); Assert.Equal(99, model.Start); Assert.Equal("mockSearchValue", model.Search.Value); Assert.Equal(true, model.Search.IsRegex); Assert.Equal(0, model.Columns.Count()); }
public void ImplementTwoMethods(ModelBinder sut) { Assert.Equal(2, sut.AllMethods.Count()); }
/// <summary> /// Разбирает массив аргументов и привязывает его к объекту указанного типа. /// </summary> /// <typeparam name="TOptions">Тип объекта для привязки аргументов командной строки.</typeparam> /// <param name="args">Массив переданных аргументов.</param> TOptions ParseAndBindTo <TOptions>(params string[] args) where TOptions : new() { var cmdargs = parser.Parse(args); return(ModelBinder.BindTo <TOptions>(cmdargs, CultureInfo.InvariantCulture)); }
public void ImplementProperMethod(ModelBinder.BindModel sut) { Assert.Equal("BindModel", sut.MethodToImplement.Name); }
public System.Threading.Tasks.Task Handle(IHttpContext context, Func <System.Threading.Tasks.Task> next) { var model = new ModelBinder(new ObjectActivator()).Get <MyModel>(context.Request.QueryString); return(Task.Factory.GetCompleted()); }
public System.Threading.Tasks.Task Handle(IHttpContext context, Func<System.Threading.Tasks.Task> next) { var model = new ModelBinder(new ObjectActivator()).Get<MyModel>(context.Request.QueryString); return Task.Factory.GetCompleted(); }