Is there any way in Entity Framework 4 of making Validation produce a warning instead of an error? - validation

As far as I can see, the validation within Entity Framework is built entirely around the assumption that, if an item fails its validation, it must not be persisted to the database. Is there any mechanism, possibly running parallel to normal validation, of making a constraint on a field produce a warning to the user, rather than an error which prevents the record from being saved/updated?
To be more specific, I have a situation where a particular numerical field has limits on it, but these are advisory rather than hard-and-fast. If the user enters a value outside these limits, they should get a warning, but should still be able to save the record.
In theory, I could subclass the ValidationResult class to make, say, a ValidationWarning class, then create a custom subclass of ValidationResults whose IsValid property was sensitive to the presence of ValidationWarning messages, and ignored them in deciding whether the entity is valid. However, this requirement has arisen in a project which is already someway along in its development, and it would require a lot of refactoring to make this kind of custom subclassing work properly. I would prefer to find a mechanism which could be levered in without creating that much disruption/rework.

I had a similar requirement on a project and how I solved it was this. If (ModelState.IsValid) is false, I cleared out the errors out of the ModelState and sent it on its way again,then logged the "error" to another service. This is a bit of a hack and I would'nt recommend doing as it is not exactly best practice.

Related

Problems with Spring Forms and Validation

I am newer to Spring, previously I've worked in PHP and Python. I am having some issues understanding how Spring forms work and are validated. My understanding thus far is that when you are using the your form is backed by a bean, meaning you must provide a bean to the JSP. You can also use the stand HTML forms but then you have to manually retrieve the request parameters in the controller.
Here is the issue I am having. I have a User bean that is using Hibernate Validator, and I have add, edit pages for users. The issue is I don't want the password field to appear on the Edit page, the password is going to be garbage anyway because its using BCrypt. However when the form is submitted validation fails because it expects the password to be present. There doesn't seem to be anyway to do partial bean implementation using Spring Form.
I would like to use Spring Form if possible because it reduces repetitive validation code, and its always nice to work with objects. My thoughts now are do I create an intermediate object and then translate the data from that to my bean. Seems tedious and can lead to the creation of way to many objects. My other thought is to just using plain old HTML forms and pull the params myself and set the values in the object.
I'm not sure what is the best approach or if I'm even thinking on the right track. Spring Forms and the validation is offers seems great, but seems like it isn't particularly flexible. Like I said I'm new to Spring so I may just be missing something or not understanding.
Another issue I have been wrestling with is having multiple objects needed on a form. Lets say I have a User bean, which has the following Properties.
private Role role;
private Country country;
So I need to pass User, List, and List to my JSP. I can get them to display fine, however if the form validation fails when it returns to that page, I lose my role and country objects, unless I re-add them to the model before returning the view name. Am I missing something here or is that the norm. It's a request object so I guess that makes sense but seems tedious to have to re-add them every time.
My understanding thus far is that when you are using the your form is
backed by a bean, meaning you must provide a bean to the JSP.
I'd say mostly true. The form is backed by a bean, but the Spring JSTL tags know how to get to the bean based on the set modelAttribute. The bean is living in what you would consider "page" scope, unless you add set your model attribute to be in session. Either way, if you are using the Spring JSTL tags, they are going to one or the other place to get it.
You can also use the stand HTML forms but then you have to manually
retrieve the request parameters in the controller.
Not true. You can "simulate" the same thing that the Spring JSTL tags are doing. Understand that JSTL tags are very much like macros. They are simply copying in some pre-determined block of code into the output with some very rudimentary conditional statements. The key bit that Spring MVC needs to wire the Model Attribute on the Controller side is the name and value, which are easy to decipher how those get generated/wired together.
However when the form is submitted validation fails because it expects
the password to be present.
You could create a "DTO" or "Data Transmission Object", which is basically a go-between to take the values from the UI and are converted in the Controller/Service layer to the real Model objects on the backend. Or, if you are lazy like me, put the User in session scope, in which case you don't have to post the value as Spring will take the one out of session and just updated the one or two fields you did post. Don't post the password, Spring wont set the password.
My thoughts now are do I create an intermediate object and then
translate the data from that to my bean.
Yes, this is the DTO I referred to. You only need to do it where you need to.
I'm not sure what is the best approach or if I'm even thinking on the
right track.
There are probably thousands of ways to do anything in coding, some more right or wrong than others. I know some developers who are design-Nazi's and would say you should always do it one way or another, but I am not one of those people. I think as long as you are consistent, and you are not doing something completely boneheaded you are on the right track. My #1 concern with all the code I write is maintainability. I
Don't want to spend 20hrs trying to re-learn what I did 6mo ago, so I tend to choose the simpler option
Hate repeating code, so I tend to choose more module designs
Hate having to spend 20hrs trying to re-learn what I did 6mo ago, so tend to make heavy use of JavaDoc and comments where I find the code is tricky (lots of loops, doing something weird, etc)
Another issue I have been wrestling with is having multiple objects
needed on a form.
There are several ways to deal with this too. I have never used it, but you CAN actually have more than one Model Attribute associated with the same form and Controller handler. I think you use a <spring:bind> tag or something. I have seen samples around, so Google it if you think you need that.
My approach is usually to either put something in session or build a DTO to hold all the things I need. The first I use more for things like lists to drive building the view, for instance if I have a drop down of States coming from a table. I would have a List of the States put into session and just use them from there, that way I only go after them once and done.
I use the DTO approach (some might call it a Form Bean) when I have a complex gaggle of things I need to change all at once, but the things are not necessarily connected directly. Just to point out: You can have nested objects in your model attributes and use them in your Spring JSTL tags. You can also have Collections (List, Set, Map) in your Model Attribute and get to those as well, although Spring doesn't handle nested Collections very well.
Hope that helps.

Laravel 4 Model validation vs Controller validation

It seems like official way to validate models in Laravel 4 is through Validator in Controller? Can somebody point out why is it so?
Wouldn't it make more sense to implement validation in Model?
I prefer the Ardent package for making validation of models as smooth and minimal as possible. To me it makes more sense to have the validation rules in the model as well.
It will return false when $model->save() is called and validation fails, then you can get the error messages through $model->errors()->all() for example.
It does make sense to have validation in the models, but this validation should only be there to make sure you don't save any corrupt data.
The Validator is in the Controller because it's used to handle Input, and generate Output.
If you would do the validation in the Model then you either have to return false, and show the user the most random of error messages about invalid data.
You could also return some kine of array containing all the errors that are generated, but that's something a Model shouldn't do.
Or you could throw an Exception, which is something that should be done when a model tries to consume invalid data, but it kills the application, which is not the wanted solution for a form validator.
When doing the form validation in the Controller, you can do everything you want with the error messages, without changing the purpose of a Model.
And in your model you can do a validation to make sure you didn't make a mistake, which will corrupt your database. Because if this happens the application should shut down.
So to put this in a real answer to your question:
Validation in the model makes sense to avoid corrupt data, but if you want to give feedback to the user about invalid input, it should be in the controller.
I wrestled with this for a while and settled on handling most of my validation in a validation service, based something along the lines of this. I can then have different validation rules based on the context.
As Nico mentions, validation in the model is good to avoid corrupt data, but I prefer thin controllers so I pass the functionality that would sit in controller into the service. This also has the benefit of being able to reuse the validation in different controllers/methods.
Why I prefer In-Model Validation: I've worked with both styles and each have pluses and minuses, but I prefer in-model validation. In our current app I don't see in-controller validation as an option, since we're altering our data in so many places (dedicated forms, inline edit, bulk edit, bulk upload, api, etc). I've never really worked with validation services (though they might be an option) but I personally like to keep logic as close to the model as possible, that way I know another developer won't bypass it. I also don't like adding lots of extra files on top of the MVC and basic Libraries folder because it just seems like more you have to think about organizing properly.
Issues with In-Model Validation: These are some things you need to consider to make In-Model work well. SOME OF THESE ARE ALREADY TAKEN INTO CONSIDERATION BY PLUGINS. I think other frameworks (CakePHP) already deal with these, but Laravel doesn't really.
Values that will be validated but not saved to the db (e.g.,
"accepted_agreement").
Many to many or belongs to many
relationships
Setting conditional defaults (not critical but
might want to think about at the same time)
Various form scenarios - sometimes you might need different validation
depending upon which form submits it. The form reference can be a
purgeable attribute for validation maybe?
How will you get back error messages (all in-model validation plugins handle this for you)
Different validation rulesets. Draft creation vs "real" creation. (Most handle this for you)
Ultimately, for simple applications that don't have lots of ways of interacting with the model, I'd say controller validation may be simpler, other then that I prefer in-model.

How do I avoid duplicating validation logic between the domain and application layers?

Any given entity in my domain model has several invariants that need be enforced -- a project's name must be at least 5 characters, a certain product must exist to be associated with the project, the due date must not be prior to the current date and time, etc.
Obviously I want the client to be able to display error messages related to validation, but I don't want to constantly maintain the validation rules between several different layers of the program -- for example, in the widget, the controller, the application service or command object, and the domain. Plus, it would seem that a descriptive error message is presentation-related and not belonging to the domain layer. How can I solve these dilemmas?
I would create specific exceptions related to your expected error conditions. This is standard for Exception handling in general and will help with your issue. For example:
public class ProjectNameNotLongEnoughException : System.Exception
or
public class DueDatePriorToCurrentDateException : System.Exception
Mark these possible exceptions in the xml comments for the methods that may throw them so that applications written against your domain model will know to watch out for these exceptions and will be able to present a message within the presentation of the application. This also allows you to have localized error messages based on the culture without cluttering up your domain model with presentation concerns.
If you choose to perform client-side validation, I'm afraid that you can't have your cake and eat it too. In this case, you may have to duplicate validation logic in order to achieve the desired features while maintaining your architecture.
Hope this helps!
I realise this is an old question, but this may help others in a similar situation.
You have here Behavior and Conditions which you need to encapsulate into your domain model.
For example, the ProjectName having a requirement on a certain length I would suggest should be encapsulated within a ValueObject. It may seem overboard for some, but within our Domain Model we almost always encapsulate native types, especially String, within a ValueObject. This then allows you to roll your validation within the constructor of the ValueObject.
Within the Constructor you can throw an Exception relating to the violation of the parameters passed in. Here is an example of one of our ValueObjects for a ZoneName:
public ZoneName(string name)
{
if (String.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("Zone Name is required");
}
if (name.Length > 33)
{
throw new ArgumentException("Zone name should be less than 33 characters long");
}
Name = name;
}
Now consumers of that ValueObject can either perform their own validation before calling the constructor, or not, but either way your invariants will be consistent with your model design.
One way we build validation rules within your Domain Model, and then utilise them within your UI is to use the Mediatr module, which uses a One Model In, One Model Out pattern, and allows you to define Validators for each of your Query or Command models. These are defined using FluentValidation. You can then add a Provider to the ModelValidatorProviders within MVC. Take a look at JBogards ContosoUniversity example here https://github.com/jbogard/ContosoUniversity/tree/master/src/ContosoUniversity and look at the DependancyResolution folder, DefaultRegistry.cs.
Your other example of a Product must exist to be linked to a Project. This sounds to me like a Domain Service would be the best option to facilitate the cooperation between 2 bounded contexts? The Domain Service will ensure the invariants remain consistent across the bounded contexts. That Domain Service would not be exposed publically, so you would need an ApplicationService or a CQRS type interface which will take that DomainService as a dependency, allowing the DomainService to perform the operations required. The DomainService should contain the Domain Behavior, whereas the Application Service should just be a facilitator to call that function. Your DomainService would then throw exceptions rather than result in inconsistent or invalid invariants.
You should ultimately end up in a position where you don't have duplicated validation, or at least you never end up with invalid invariants because validation has not been performed at some point, as validation is always handled within your domain model.
While a descriptive error message may seem to pertain to presentation moreso than business, the descriptive error message actually embodies a business rule contained within the domain model -- and when throwing an exception of any kind, it is best practice to pass along some descriptive message. This message can be re-thrown up the layers to ultimately display to the user.
Now, when it comes to preemptive validation (such as a widget allowing the user to only type certain characters or select from a certain range of options) an entity might contain some constants or methods that return a dynamically-produced regular expression which may be utilized by a view model and in turn implemented by the widget.

Code first validation that requires database access (duplicate valies)

This question may have already been asked, sorry
I'm looking at the architecture for validating our model. Our simple validation can be achieved by using the property validation attributes (some custom) and using
ModelState.IsValid
however the problem is when validation requires access to the database or access to another property. A perfect example is to check for duplicate names. In this case we need to check the database for duplicate names where the id is not equal to that of the current object (for updates)
If we were to write this as an validation attribute to be applied to the name property this would cause to problems. Ome how do we get access to the database and two how would we get access to the id property.
So in conclusion. Is there any examples of good ways to architect a fix to this problem?
I spent some time exploring this today for a project I was working on and came to these conclusions.
It is not to bad to solve the how, much of it involves some reflection and using the validation context to inspect and access other properties of your model or using IValidationObject. The real question becomes is it okay to do validation that requires database interaction.
For one I was concerned about performance, in one particular case a validation made a query that returned an object to ensure it existed which I later needed for relationship assignment which would then cause another query.
Secondly you need to think about database concurrency. The best way to do duplication checks is during insert not before because the database could change between the two operations. This also relates to the first reason, an object could be deleted immediately after a database reported it exists.
In my particular project I felt it better to keep this sort of behavior with modifying my EF context and adding anything that went wrong to the ModelState.

What is the best way to handle domain-centric validation while providing a rich UI experience?

My company is developing a GUI application that allows users to query a legacy database system and have the results displayed back to them on the screen (the results just come back in a blob of plain-text). I'm struggling with the best way to structure the interaction between the user interface and the domain layer, especially validation of user input.
Basic Use Case
User selects a query to run from a menu in the application.
The application code displays the data entry form for the selected query.
The user enters the parameters for the query. If a field contains invalid data, it is immediately highlighted in red, and its tooltip text is changed to display an error message (i.e. if you are entering a Person query, and you enter a date of birth in the future, for example, the date of birth field will immediately turn red).
When the user clicks Run Query, the application runs a second validation pass; this second validation pass is required in order to run validation checks that involve multiple fields. If the this validation check passes, and all the fields are valid, the query is sent; otherwise, the user is prompted to fix any remaining errors.
My Current Validation/Error Reporting Strategy
Currently, I'm using domain-centric validation, but the overall design seems messy to me and maybe a little too over-engineered. A brief overview of the current design:
Domain layer: I have one class per query. Every query class contains a collection of IQueryField objects that hold the values entered by the user. Each query class implements a common IQueryMessage interface, which defines (among other things) a Validate method. This method is called to enforce message-level validation rules (i.e. rules that must examine the state of multiple fields at once). The IQueryField interface also defines a 'Valdate' method (among other things). This is to support per-field validation rules.
Per-field validation: To handle the per-field validation and error reporting, the data entry code binds each input control to an IQueryField; whenever the user changes the value of a control, it calls the the corresponding IQueryField's Validate method, which in turn fills a Notification object (just a collection of strings at the moment) with any errors detected in the value entered by the user. The user interface code then checks the Notification object and changes the appearance of the user control to indicate an error condition, if necessary.
Message-level validation: When the user tries to send a query, the application calls the Validate method on the IQueryMessage instance associated with the data entry form (at this point, the data binding code has also ensured all the message's fields have been populated from the input controls on the form, and the per-field validation code has been run). If there are any validation errors, the user interface displays them at the top of the form. If there are no errors, the data entry form is closed and the query is serialized and sent over the network.
Is Something Wrong Here?
I feel like something isn't "right" here. I have a few issues with the current design:
I would like the domain-level validation code to indicate the name of any fields that are in error, bur I don't want to hard-code the UI label captions into the domain classes. One possibility I thought of was to have the domain-level Validate methods generate messages with a field placeholder, such as "%s cannot be in the future", and have the UI code fill in the placeholder with the correct label.
The IQueryMessage and IQueryField interfaces both have a method called Validate. I'm thinking this should be extracted into a separate interface, (IValidatable perhaps), but I wonder if I am making things needlessly complex.
I'm using VB6, so I can't use inheritance in my classes (VB6 supports classes but not inheritance). I can only define and implement interfaces. Because of this, and because of the way my current interfaces are designed, I'm duplicating a lot of boiler-plate code in my implementation classes. I am thinking of solving this with an inversion-of-control approach. For example, I was thinking of defining a single concrete QueryField class, which could be initialized with a collection of IValidationRule instances that define what validation rules to use, then the QueryField.Validate() method would just collect the results of executing each rule. This way, the validation rules can be tailored to each field, but the QueryField class can handle all the common field-related stuff (field name, field length, required/not required checks, etc.).
How Can I Improve This?
I'm interested in any refactoring suggestions and hints on improving the current design. Also, I'm not necessary tied down to domain-centric validation; other suggestions are welcome. The main motivation behind using domain-centric validation was to keep increase encapsulation, and allow query message and field objects to be used in a non-GUI environment, without having to rewrite all the validation logic.
When you initialize a QueryField object, pass a label to it from the GUI. Then it's the UI that is responsible for setting the label name which seems reasonable to me.
I don't think this is necessary.
What you are describing doesn't really sound like IoC but rather just plain old composition. Since you can't even use inheritance this improvement seems to make sense. Generally you want to prefer composition to inheritance anyways. However if you are almost done with the work then I wouldn't bother refactoring this late in the game.

Resources