/// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate <TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { var model = module.Bind <TModel>(configuration, blacklistedProperties); module.Validate(model); return(model); }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { IDictionary<string, object> data = GetDataFields(context); DynamicDictionary model = DynamicDictionary.Create(data); return model; }
/// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate <TModel>(this INancyModule module, BindingConfig configuration, params Expression <Func <TModel, object> >[] blacklistedProperties) { var model = module.Bind <TModel>(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return(model); }
public Servers() { InitializeGet(Helper.Servers, "servers"); InitializeGetAll(Helper.Servers, "servers"); InitializeEnable(Helper.Servers, "servers"); InitializeDelete(Helper.Servers, "servers"); Put["/servers", true] = async(_, ct) => { Request.ServerAdd request; try { var config = new BindingConfig { BodyOnly = true, IgnoreErrors = false }; request = this.Bind<Request.ServerAdd>(config); request.ApiKey = Guid.Parse(Context.CurrentUser.UserName); var results = Validate(request); if (results.Count > 0) { return CreateErrorResponseAndUpdateApiKey((from result in results select result.ErrorMessage).Implode(", ")); } } catch (Exception ex) { return CreateErrorResponseAndUpdateApiKey(ex.Message); } return ExecuteRequest(request); }; }
public void Should_allow_overwrite_on_new_instance() { // Given // When var instance = new BindingConfig(); // Then instance.Overwrite.ShouldBeTrue(); }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { var customer = (instance as Customer) ?? new Customer(); customer.Name = customer.Name ?? context.Request.Form["Name"]; customer.RenewalDate = customer.RenewalDate == default(DateTime) ? context.Request.Form["RenewalDate"] : customer.RenewalDate; return customer; }
public BindingContextForTests(Type destinationType, Type genericType) { DestinationType = destinationType; GenericType = genericType; Configuration = new BindingConfig(); ValidModelProperties = GetProperties(destinationType, genericType); TypeConverters = GetTypeConverters(); }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackListedProperties) { var data = GetDataFields(context, blackListedProperties); var model = DynamicDictionary.Create(data); return model; }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { var body = Encoding.UTF8.GetString( context.Request.Body.ReadBytes((int)context.Request.Body.Length) ); var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>( body ); return data; }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { var fileUploadRequest = (instance as FileUploadRequest) ?? new FileUploadRequest(); var form = context.Request.Form; fileUploadRequest.Tags = GetTags(form["tags"]); fileUploadRequest.Title = form["title"]; fileUploadRequest.Description = form["description"]; fileUploadRequest.File = GetFileByKey(context, "file"); return fileUploadRequest; }
/// <summary> /// Extracts data from the Nancy Request Context and binds it to a DynamicDictionary object. /// </summary> /// <param name="context">The context.</param> /// <param name="modelType">Type of the model.</param> /// <param name="instance">The instance.</param> /// <param name="configuration">The configuration.</param> /// <param name="blackListedProperties">The black listed properties.</param> /// <returns></returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackListedProperties) { object model = null; if (modelType == typeof(DynamicDictionary)) { var data = GetDataFields(context, blackListedProperties); model = DynamicDictionary.Create(data); } else if (modelType == typeof(IList<PatchOperationDto>)) { model = ParsePatchOperationsList(context.Request); } return model; }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList); var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } if (!configuration.BodyOnly) { var bindingExceptions = new List<PropertyBindingException>(); foreach (var modelProperty in bindingContext.ValidModelProperties) { var existingValue = modelProperty.GetValue(bindingContext.Model, null); var stringValue = GetValue(modelProperty.Name, bindingContext); if (!String.IsNullOrEmpty(stringValue) && (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)) { try { BindProperty(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } if (bindingExceptions.Any()) { throw new ModelBindingException(modelType, bindingExceptions); } } return bindingContext.Model; }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList); var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } if (!configuration.BodyOnly) { var bindingExceptions = new List <PropertyBindingException>(); foreach (var modelProperty in bindingContext.ValidModelProperties) { var existingValue = modelProperty.GetValue(bindingContext.Model, null); var stringValue = GetValue(modelProperty.Name, bindingContext); if (!String.IsNullOrEmpty(stringValue) && (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)) { try { BindProperty(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } if (bindingExceptions.Any()) { throw new ModelBindingException(modelType, bindingExceptions); } } return(bindingContext.Model); }
/// <summary> /// Initializes a new instance of the <see cref="DynamicModelBinderAdapter"/> class. /// </summary> /// <param name="locator">Model binder locator</param> /// <param name="context">Nancy context</param> /// <param name="instance">Optional existing instance, or null</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Blacklisted property names</param> public DynamicModelBinderAdapter(IModelBinderLocator locator, NancyContext context, object instance, BindingConfig configuration, params string[] blacklistedProperties) { if (locator == null) { throw new ArgumentNullException("locator"); } if (context == null) { throw new ArgumentNullException("context"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } this.locator = locator; this.context = context; this.instance = instance; this.configuration = configuration; this.blacklistedProperties = blacklistedProperties; }
/// <summary> /// Initializes a new instance of the <see cref="DynamicModelBinderAdapter"/> class. /// </summary> /// <param name="locator">Model binder locator</param> /// <param name="context">Nancy context</param> /// <param name="instance">Optional existing instance, or null</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Blacklisted property names</param> public DynamicModelBinderAdapter(IModelBinderLocator locator, NancyContext context, object instance, BindingConfig configuration, params string[] blacklistedProperties) { if (locator == null) { throw new ArgumentNullException("locator"); } if (context == null) { throw new ArgumentNullException("context"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } this.locator = locator; this.context = context; this.instance = instance; this.configuration = configuration; this.blacklistedProperties = blacklistedProperties; }
private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable<string> blackList, Type genericType) { return new BindingContext { Configuration = configuration, Context = context, DestinationType = modelType, Model = CreateModel(modelType, genericType, instance), ValidModelProperties = GetProperties(modelType, genericType, blackList), RequestData = this.GetDataFields(context), GenericType = genericType, TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters), }; }
public ServiceModule(ServiceManager serviceManager) { // Find all service methods having a ServiceGetContractAttribute attached to it. var bindQuery = from service in serviceManager.Services from method in service.GetType().GetMethods() from attribute in method.GetCustomAttributes(true) where attribute is ServiceBase.ServiceGetContractAttribute select new { service, method, attribute }; foreach (var bindData in bindQuery) { var service = bindData.service; var method = bindData.method; var attribute = bindData.attribute; var contract = attribute as ServiceBase.ServiceGetContractAttribute; if (contract == null) continue; bool isPut = contract is ServiceBase.ServicePutContractAttribute; var mapper = new ContractMapper("/" + service.Name + "/" + contract.uri, method); string uri = mapper.GetMappedUri(); Func<dynamic, dynamic> lambda = parameters => { var arguments = new List<object>(); mapper.MapArguments(parameters, Request.Query, arguments); if (mapper.BindBody && mapper.DynamicBody) { // Bind manually for now until I've fixed the dynamic type. // Attempt to deserialize body from Json Nancy.DynamicDictionary body = null; if (Request.Body.Length > 0) { var buffer = new byte[Request.Body.Length]; Request.Body.Position = 0; Request.Body.Read(buffer, 0, (int)Request.Body.Length); string bodyStr = Encoding.Default.GetString(buffer); Log.Debug("Got body data:\n{0}", bodyStr); var serializer = new Nancy.Json.JavaScriptSerializer(); try { var bodyJson = serializer.DeserializeObject(bodyStr) as System.Collections.Generic.Dictionary<string, object>; if (bodyJson != null) body = Nancy.DynamicDictionary.Create(bodyJson); } catch (System.ArgumentException) { // Just eat it. Log.Warning("Got request with invalid json body for url: " + Request.Url); return null; } } arguments.Add(body); } else if (mapper.BindBody) { // Bind specific type. var config = new BindingConfig(); config.BodyOnly = true; config.IgnoreErrors = false; // The Bind<> method exists on the ModuleExtension rather than the NancyModule. var extensionMethods = typeof(ModuleExtensions).GetMethods(); var methodList = new List<MethodInfo>(extensionMethods); // Get correct generic bind method var bindMethod = methodList.Find(x => x.Name == "Bind" && x.GetParameters().Length == 1 && x.IsGenericMethod == true); var genericMethod = bindMethod.MakeGenericMethod(mapper.BodyType); // Bind our object. var boundBody = genericMethod.Invoke(null, new object[] { this }); arguments.Add(boundBody); } try { object result = method.Invoke(service, arguments.ToArray()); return Response.AsJson(result); } catch (TargetInvocationException e) { Log.Error( "Invocation exception of uri: " + uri + "\n" + "Exception: " + e.Message + "\n" + "Callstack:" + e.StackTrace + "\n" + "Inner: " + e.InnerException.Message + "\n" + "Callstack: " + e.InnerException.StackTrace); // TODO - A better way to unwrap this? Just throwing inner exception will cause an ObjectDisposedException throw new Exception(e.InnerException.Message); } }; if (isPut) { //Log.Debug("Adding PUT binding for {0}", uri); Put[uri] = lambda; Post[uri] = lambda; } else { //Log.Debug("Adding GET binding for {0}", uri); Get[uri] = lambda; } } }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { StreamReader reader = new StreamReader(context.Request.Body); return reader.ReadToEnd(); }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted binding property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.GetTypeInfo().IsGenericType) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = modelType.GetInterfaces().Where(i => i.GetTypeInfo().IsGenericType).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable <>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("When modelType is an enumerable it must specify the type.", "modelType"); } } var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); try { var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } } catch (Exception exception) { if (!bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, innerException: exception); } } var bindingExceptions = new List <PropertyBindingException>(); if (!bindingContext.Configuration.BodyOnly) { if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() || bindingContext.DestinationType.IsEnumerable()) { var loopCount = this.GetBindingListInstanceCount(context); var model = (IList)bindingContext.Model; for (var i = 0; i < loopCount; i++) { object genericinstance; if (model.Count > i) { genericinstance = model[i]; } else { genericinstance = bindingContext.GenericType.CreateInstance(); model.Add(genericinstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingCollectionValue = modelProperty.GetValue(genericinstance); var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i); if (this.BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, collectionStringValue, bindingContext, genericinstance); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); var stringValue = GetValue(modelProperty.Name, bindingContext); if (this.BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } if (bindingExceptions.Any() && !bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, bindingExceptions); } } if (modelType.IsArray()) { var generictoArrayMethod = ToArrayMethodInfo.MakeGenericMethod(new[] { genericType }); return(generictoArrayMethod.Invoke(null, new[] { bindingContext.Model })); } return(bindingContext.Model); }
private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable <string> blackList, Type genericType) { return(new BindingContext { Configuration = configuration, Context = context, DestinationType = modelType, Model = CreateModel(modelType, genericType, instance), ValidModelBindingMembers = GetBindingMembers(modelType, genericType, blackList).ToList(), RequestData = this.GetDataFields(context), GenericType = genericType, TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters), }); }
public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = 10; var config = new BindingConfig { IgnoreErrors = true }; // When var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel; // Then model.AnotherIntProperty.ShouldEqual(10); }
/// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> public static TModel BindTo <TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { return(module.BindTo(instance, configuration, NoBlacklistedProperties)); }
/// <summary> /// Bind the incoming request to a model /// </summary> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Model adapter - cast to a model type to bind it</returns> public static dynamic Bind(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return(new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, null, configuration, blacklistedProperties)); }
/// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> public static TModel BindTo <TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties) { dynamic adapter = new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, instance, configuration, blacklistedProperties); return(adapter); }
/// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example> public static TModel BindTo <TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression <Func <TModel, object> >[] blacklistedProperties) { return(module.BindTo <TModel>(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree())); }
public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true() { // Given var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() }); var context = new NancyContext { Request = new FakeRequest("GET", "/") }; context.Request.Form["IntProperty"] = "badint"; context.Request.Form["AnotherIntProperty"] = "morebad"; var config = new BindingConfig {IgnoreErrors = true}; // When // Then Assert.DoesNotThrow(() => binder.Bind(context, typeof(TestModel), null, config)); }
/// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <returns>Bound model instance</returns> public static TModel Bind <TModel>(this INancyModule module, BindingConfig configuration) { return(module.Bind(configuration)); }
/// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperty">Expressions that tell which property should be ignored</param> /// <example>this.Bind<Person>(p => p.Name, p => p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind <TModel>(this INancyModule module, BindingConfig configuration, Expression <Func <TModel, object> > blacklistedProperty) { return(module.Bind(configuration, new [] { blacklistedProperty }.ParseBlacklistedPropertiesExpressionTree())); }
/// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.IsGenericType()) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("when modeltype is an enumerble it must specify the type", "modelType"); } } var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } var bindingExceptions = new List<PropertyBindingException>(); if (!bindingContext.Configuration.BodyOnly) { if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() || bindingContext.DestinationType.IsEnumerable()) { var loopCount = GetBindingListInstanceCount(context); var model = (IList)bindingContext.Model; for (var i = 0; i < loopCount; i++) { object genericinstance; if (model.Count > i) { genericinstance = model[i]; } else { genericinstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericinstance); } foreach (var modelProperty in bindingContext.ValidModelProperties) { var existingCollectionValue = modelProperty.GetValue(genericinstance, null); var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i); if (BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty, bindingContext)) { try { BindProperty(modelProperty, collectionStringValue, bindingContext, genericinstance); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } } else { foreach (var modelProperty in bindingContext.ValidModelProperties) { var existingValue = modelProperty.GetValue(bindingContext.Model, null); var stringValue = GetValue(modelProperty.Name, bindingContext); if (BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext)) { try { BindProperty(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } if (bindingExceptions.Any()) { throw new ModelBindingException(modelType, bindingExceptions); } } if (modelType.IsArray()) { var generictoArrayMethod = toArrayMethodInfo.MakeGenericMethod(new[] { genericType }); return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model }); } return bindingContext.Model; }
public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { return new Concrete() as IAmAnInterface; }
/// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> public static TModel Bind <TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return(module.Bind(configuration, blacklistedProperties)); }
/// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate <TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { var model = module.BindTo(instance, configuration, NoBlacklistedProperties); module.Validate(model); return(model); }