How do I handle null values during model binding - asp.net-web-api

I have the folowing URL:
http://localhost:7975/test?parameter01=X
In my model, parameter01 is a List<int?>. If a non-integer value (e.g., a string) is passed to this parameter, the model binding process sets this value to null.
How do I intercept this as early as possible in the pipeline so I can return a HTTP status and description without handling this condition in the controller action?

Since you have tagged with asp.net-web-api2 I would recommend using Attribute Routing which enables you to constrain the Parameter Type. With this you'd able to switch handling according to the validity of your input. You can read up on this here
A second possibility would be to write a HTTPHandler which tests for valid input information. This one might be a bit trickier.

Related

Kafka Streams transform() state store

I have a use case where I need to use headers in DSL so used transformValues() but not doing stateful transformation , more of decision making based on headers.
I need to pass the state store name in this function.Is there any alternative of not giving a state store of some default or dummy value?
I need to pass the state store name in this function
That is not correct. The signature of KStream#transformValues() is
<VR> KStream<K, VR> transformValues(final ValueTransformerSupplier<? super V, ? extends VR> valueTransformerSupplier,
final String... stateStoreNames);
Note, that the second argument is a var-arg, and you don't need to provide any parameter for it. Hence, you can call transformValue() with a single argument.

Unique Validator - add error (warning) and return true

What would be the best way to create validator that checks if model value is unique or not, but it does not return false - it only shows message "the value already exists" (I can still save the model)?
Validators usually don't return boolean values, they add errors for given model attribute(s).
One of the ways (with minimal completions) will be using built-in UniqueValidator and saving without running validation.
At first call $model->validate() to fill model with errors.
You can use $model->validate('fieldName') to validate only needed field.
Then call $model->save(false) or $model->save('fieldName') (for just one field).
This will prevent validation before saving and model values will be saved "as is".
Another way for just saving one attribute without triggering events, etc. will be using updateAttributes after calling validate():
$model->updateAttributes(['fieldName' => 'fieldValue']);

WebObjects field validation

I'm trying to find a good way to do field validation in a WebObjects app. If I have a text field and I tie a number formatter to it, it seems that the default behavior is to parse out the number IF the user enters in a valid number, or, if the user enters an invalid number, it seems to just ignore the value entered by the user. I can't do the validation in a save method or an action method because WO will have already ignored the non-number input by the time it reaches the action method. Is there a standard/recommended way, in a WebObjects app, of validating user input such that the user can be alerted of invalid input, rather than just ignoring the invalid input?
This page: http://en.wikibooks.org/wiki/WebObjects/EOF/Using_EOF/Validation claims that WO and EOF have "an incredible array of validation mechanisms" and even hints that there is a built-in way to prevent the user from entering inappropriate data, but I haven't been able to find any documentation or examples of how to do that (if there is, in fact, a built-in way). Coming up with a custom javascript validator to prevent inappropriate data seems like it would be a nightmare - finding a way to make the JS recognize and handle all of the same edge cases that the backend formatters/parsers handle. It would be nice if WO really did have a built-in way to propagate the formatter edge cases over to JS validation.
The above link also says there is a validationFailedWithException method in WOComponent that gets called "when an EO or formatter failed validation during an assignment", but how can I make a formatter fail validation in the non-number example case above? I've tried having the formatter throw an exception in the parse method if a non-number is entered, but that exception doesn't get passed to the validationFailedWithException method. Does anyone know how I can trigger an exception in a formatter that will trigger a call to validationFailedWithException()? And is that even the best/recommended way? Does anyone know of a better way?
I'm pretty sure, that validationFailedWithException is getting called for every formatting error. You should receive there an NSValidationException that wraps a ParseException. The method is usually called on the component containing the binding. It may get skipped on caret (^) bindings.
All the standard number formatter already throw a ParseException (see Format.parse(String)).
The validation handling in WebObjects can get quite complex, it really depends on your needs. But it was designed without JavaScript or Ajax in mind. Newer approaches in Wonder may incorporate the client side, but I have no experience with it.
The normal validation sequence is:
if needed convert the input into the target type with a formatter
call a validateAttributeName method on the target object, where AttributeName is the attribute name to receive the value
When something fails in this sequence validationFailedWithException is called.
While saving an enterprise object "validateFor..." is called on the objects. An exception at this point has to be caught in your action method.
So you have two points to handle validation errors. The "syntactical" errors have to be handled in validationFailedWithException. After this point you have valid inputs. You may manually further check those or greater object structures in your action method or in validateFor... (e.g. validateForSave).

Drupal6: Load a field, like one would load a node?

Is there a field_load() function equivalent to node_load()? I want to get information about the type of a field and other validation constraints without going to the database myself.
Better yet, is there any function that will validate it for me, like is_valid_for_field(field_name, input), that would take a field name and a potential input and return a boolean indicating whether or not the potential input is valid (within min/max, etc) for the specified field?
There is the content_fields() function, which will get you the meta data for a field. In terms of validation, IIRC, you can call content_field() with the operation set to validate, and the relevant data. However, by calling node_save with your completed node, the cck module will take care of all the relevant validation hooks for the entire node structure, so you may be better off taking that route.

In a MVC-model, whose responsibility is it to sanitize input?

A simple question: I have a Model-View-Controller setup, with Models accessing a SQL database. In which part should I sanitize/check for malformed incoming data?
It's important to keep error handling as low as possible in the stack, but supplemental in other parts. If you keep the sanitizing in the controller, you could break the model by swapping out the controller with a looser one, but you can never break the model by being strict higher up in the stack. Keep the sanitizing low in the stack for consistency, and high in the stack for user feedback.
I'd say the Controller should sanitize input.
The model should at most decline to store invalid data.
I would say it is the responsibility of the controller to validate the input and make sure the data is valid before passing on the data to the model.
If invalid data is found, the controller should redirect back to the view and display the relevant error messages.
Having validation in the view only could be bypassed if the user doesn't have javascript enabled or posts to the url directly, however some validation in the view is better from a user experience point of view since the user does not need to wait for a return from the server in a web application.
The model will validate business logic rules, i.e. password length requirements, if a user is allowed to perform an action or not.
The model should obviously also make sure interaction with the database is done in a safe way so that SQL Injection is not possible.
The controller should handle relaying business logic errors back to the view, but can also do some basic sanity checks, i.e. a field is not empty.
I would say output sanitization should also go in the Controller before being passed to the View.
I use two levels of checking. My controller will check what is supposed to be a date is a date, an int an int and so forth. Basically ensuring they can be used to set the values on my objects.
Then my domain has validation for things such as valid values and other business rules. These are ALWAYS checked before saving or interacting with an edited object.
All errors from either level get returned to the user so they can take remedial action as necessary.
I tend to:
Put syntactic validation in the view ("this field is numeric", "that field is a date"). This is often very easy or even implicit in your choice of view design (eg: using a date picker for date fields).
Put semantic violation in a separate validator class ("this date field has to be after that date field", "this can be null if that is greater than zero") and call the validator from the controller, passing errors back to the view for display.
(for my own pseudo-correct definitions of syntax and semantics...)

Resources