breeze: Tracking errors with many-to-many associations - breeze

A few weeks ago, I've asked how to save Many-To-Many associations with breeze.
Ward Bell came up with this nice solution: breeze: many-to-many issues when saving
I've implemented his solution and it works really well. One issue I've come up with recently though, is how to track errors ?
Taking Ward's example, we manipulate UserRoleVm instances. Therefore validationErrorsChanged will not be triggered for this property.
How could I use breeze to raise an error if say, the parent entity does not have at least one UserRoleVm entity in its collection ?

The UserRoleVm is a regular JavaScript object. It is not a Breeze entity and so does not participate in the Breeze validation support. There is no obvious way to make it do so (at least not obvious to me). Almost anything I can dream up would be more complicated than writing traditional, view-based validation.
What kind of validation do you need? In the example that I put together, the user can only add and remove roles (the equivalent of super powers). There is no way the user can touch any value of the corresponding mapping entity (which may not even exist yet).
When I turn my imagination loose, I speculate about the rules governing how many roles the user can have or whether certain combinations of rule are allowed ... or disallowed. Is that what you mean?
If I had such rules, I'd build validation logic into the outer ViewVM (not the UserRoleVMs) ... the VM that supervises the user's actions. This logic would be quite apart from the Breeze validation logic that you register in metadata ... the validation rules implemented by Breeze inside each entity's EntityAspect.
Ultimately, I would have Breeze validations too ... probably entity validations on the parent User entity type ... so that I could guard against an actual attempt to save an invalid UserRole combination.
But such Breeze validation rules wouldn't kick in until you tried to save. While the user is working with "item VMs" (the UserRoleVms), the validation rules would be defined and implemented separately by the ViewVM in good old vanilla JavaScript.
Such is my thinking at the moment.

Following Ward's advice, I have:
-added the following code for forcing User entity's state to be modified whenever a UserRoleVM is added or removed:
$scope.user.entityAspect.setModified();
-added a custom validator for validating the UserRoles collection on the User entity:
function notEmptyCollectionValidator() {
var name = "notEmptyCollectionValidator";
var validator = new breeze.Validator(name, function (value) {
if (!value || value.length === 0) {
return false;
} else {
return true;
}
});
return validator;
}
breeze.Validator.registerFactory(notEmptyCollectionValidator, 'notEmptyCollectionValidator');
var entityType = metadataStore.getEntityType('User');
entityType.getProperty('userRoles').validators.push(breeze.config.functionRegistry['Validator.notEmptyCollectionValidator']());
Now when I hit the save button, the validation occurs on the userRoles collection. If no userRole was selected, I get a validation error and I show a * next to the control in th UI.
Obviously, that does not work for OnChange validation. I don't know yet how I'm going to achieve that.

Related

typo3 flow isDirty on model

Im trying to find out which attributes of an entity have been changed.
As far I have seen, there is a PersistenceSession with a method to check an object if an attribute isDirty. But its always true because it never registers the old object.
So if I take the demo from the QuickGuide and override the update method in the CoffeeBeanRepository:
/**
* #param \Acme\Demo\Domain\Model\CoffeeBean $coffeeBean
*/
public function update($coffeeBean) {
\TYPO3\Flow\var_dump($this->persistenceSession->isDirty($coffeeBean, 'name'), "name changed before");
parent::update($coffeeBean);
\TYPO3\Flow\var_dump($this->persistenceSession->isDirty($coffeeBean, 'name'), "name changed after");
}
... its always TRUE (both), despite I didn't change anything.
Anyone an idea/reference how this can be accomplished?
I am using it for a REST API where a user can't update several fields and on editing of some fields additional actions have to be executed.
The persistenceSession is part of the generic persistence backend of Flow and is neither maintained, nor really used unless you explicitly deactivate doctrine. Hence persistenceSession will not help you, because all entities are considered new for the persistenceSession as you noticed.
With doctrine you need to get the entity changeset from the "UnitOfWork", which you can get from an injected \Doctrine\Common\Persistence\ObjectManager. See also Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity
However, this is a suboptimal solution and a hacky work-around at best. If you need to track changes to your entity, it should be an explicit part of your domain model. For example make your setters record a changed properties list, when the given value is different from the current.
When done, you could even optimize doctrines change tracking on the way with that: http://doctrine-orm.readthedocs.org/en/latest/reference/change-tracking-policies.html#notify

MVC FluentValidation with entity framework in separate .dll

I have a separate .dll with our database model and partial classes etc in using FluentValidation which works fine (it's to be used by both by desktop barcoding terminals and also by our website).
For the desktop apps I can read and display all errors like below
public override int SaveChanges()
{
var errors = this.GetValidationErrors();
if (errors.Any())
{
//handle validation errors
return 0;
}
else
{
return base.SaveChanges();
}
}
For the MVC site I can set up validators on individual models or create data annotations and get those working okay (which is not what I want). The thing I can't get my head around is how I can force my models to map to my entities in a way that I can display the fluent validation messages in the views. I don't want to have two separate sets of logic to be maintained and the barcoding apps and website must use the same.
Do I have to map my entities directly to the views? which i've been led to believe is a bad thing and not very flexible. Or is there a way of stating that a field in a model maps back to an attribute of one of my entities? perhaps an annotation of some description.
EDIT:
Just some clarification for the types of validation i'll need.
most front end input type validation will still stay in the viewModels (required/length/password matches etc - basically all the stuff I can use for client side validation as well). But there are all the business logic validations that I don't want there. Things like email addresses must be validated before other options can be set, account numbers must be of a particular format based on name (stuff I can't do with a regex). This particular date is not a valid delivery date etc.
I guess one thing I could do is add these to the ValidationSummary somehow and display them separate from the individual fields.
I think you're just looking at the situation wrong. What MVC is all about is a separation of concerns. There's things the database needs to know about that your views could care less, and vice versa. That's why the recommended practice is to use view model with your views and not the entity itself.
Validation is much the same. Something like the fact that a password confirmation needs to match the password the user entered does not concern the database at all. Or more appropriately, something like a validation on minimum amount of characters in the password does not concern the database, either; it will only ever receive a salted and hashed version of the password. Therefore it would be wrong to put this kind of validation on your entity. It belongs on the view model.
When I first started out using MVC, I used to add all the validation logic to my entity class and then go and repeat that same validation on my view model. Over time, I started to realize that very little of the validation actually needs to be on both. In fact, the largest majority of validation will should just go on your view model. It acts as a gatekeeper of sorts; if the data is good enough to get through your view model, it's good enough for your database. The types of validation that make sense on your entity is things like Required, but even that is really only necessary on a nullable field that must have a value by the time it gets to your database. Things like DateTimes are non-nullable by default, and EF is smart enough to make them non-nullable on the tables it creates by default. MaxLength is at times worthwhile if there should be a hard limit on the length of a text field in your database, but more often than not, nvarchars work just fine.
Anyways the point is that if you actually sit down and start evaluating the validation on your entity, you'll likely see that most of it is business logic that only applies to how your application works and not to how the data is represented at the database level. That's the key takeaway: on your entity, you only need the validation that's necessary for the database. And that's generally pretty thin.
Just an update. to get the two tier validation that i needed i had to mark all my entity model classes as IValidatable. Then i overrode the validate method for each class and invoked my fluent validation validator method there, passing back the errors needed. for the modelstate.addmodelerror i set the key as the field name and it mapped back okay. bit more code but it works. if i find a better way to do this ill update.

ASP.NET MVC / EF4 / POCO / Repository - How to Update Relationships?

I have a 1..* relationship between Review and Recommendations.
The relevant portion of my model (which is also the POCO mapped by EF4):
public class Review
{
public ICollection<Recommendations> Recommendations { get; set; }
}
On an Edit View, i represent the Recommendations as a set of checkboxes.
When i try and add a new Recommendation as part of editing the Review (e.g check another box), nothing is happening - and i know why...
I use the "stub technique" to update my entities - e.g i create a entity with the same key, attach it to the graph, then do ApplyCurrentValues. But this only works for scalar properties, not for navigational properties.
I found this StackOverflow question which looks good, but i am trying to work out how to get this to work with POCO's/Repository (and ASP.NET MVC - detached context).
As i'm using POCO's, review.Recommendations is an ICollection<Recommendation>, so i can't do review.Recommendations.Attach. I'm not using Self-Tracking Entities either, so i need to manually work with the graph/change tracking - which hasn't been a problem until now.
So you can visualize the scenario:
Review:
Recommendations (ICollection<Recommendation>):
RecommendationOne (Recommendation)
RecommendationTwo (Recommendation)
If im on the edit view, two of the checkboxes are already checked. The third one (representing RecommendationThree) is unchecked.
But if i check that box, the above model becomes:
Review:
Recommendations (ICollection<Recommendation>):
RecommendationOne (Recommendation)
RecommendationTwo (Recommendation)
RecommendationThree (Recommendation)
And so i need to attach RecommendationThree to the graph as a new entity.
Do i need hidden fields to compare the posted data the existing entity? Or should i store the entity in TempData and compare that to the posted entity?
EDIT
To avoid confusion, here is the full app stack call:
ReviewController
[HttpPost]
public ActionResult Edit(Review review)
{
_service.Update(review); // UserContentService
_unitOfWork.Commit();
}
UserContentService
public void Update<TPost>(TPost post) where TPost : Post, new()
{
_repository.Update(post); // GenericRepository<Post>
}
GenericRepository - used as GenericRepository<Post>
public void Update<T2>(T2 entity) where T2 : class, new()
{
// create stub entity based on entity key, attach to graph.
// override scalar values
CurrentContext.ApplyCurrentValues(CurrentEntitySet, entity);
}
So, the Update (or Add or Delete) Repository methods needs to be called for each recommendation, depending it's new/modified/deleted.
I've accepted #jfar's answer because he put me on the right track, but thought i'd add an answer here for other people's benefit.
The reason the relationships were not getting updated is for the following reasons:
1) Completely disconnected scenario. ASP.NET = stateless, new context newed up each HTTP request.
2) Edited entity created by MVC (model binding), but not existing in graph.
3) When using POCO's with no change tracking, performing .Attach on an entity will add it to the graph, but the entity and any child relationships will be Unchanged.
4) I use the stub entity trick and ApplyCurrentValues to update the entity, but this only works for scalar properties, not navigational ones.
So - in order to get the above to work, i would have to explicity set the EntityState for the object (which happens automatically because of ApplyCurrentValues), and also the navigational properties.
And there is the problem - how do i know if the navigational property was added/modified/deleted? I have no object to compare to - only a entity which i know was "edited", but i don't know what was edited.
So the solution in the end was this:
[HttpPost]
public ActionResult Edit(Review review)
{
var existingReview = _service.FindById(review.Id); // review is now in graph.
TryUpdateModel(existingReview); // MVC equivalent of "ApplyCurrentValues" - but works for ALL properties - including navigationals
_unitOfWork.Commit(); // save changed
}
That's it. I don't even need my _service.Update method - as i don't need the stub trick anymore - because the review is in the graph with the retrieval, and ApplyCurrentValues is replaced by TryUpdateModel.
Now of course - this is not a concurrency-proof solution.
If i load the Review Edit View, and before i click "Submit" someone else changes the Review, my changes could be lost.
Fortunately i have a "last-in-wins" concurrency mode, so it's not an issue for me.
I love POCO's, but man are they a pain when you have the combination of a stateless environment (MVC) and no change tracking.
Working with detached object graphs is my favorite drawback of EF. Simply pain in the ass. First you have to deal with it at your own. EF will not help you with it. It means that in addition to Review you also have to send some information about made changes. When you attach Review to context it sets Review all Recommendation and all relations to Unchanged state. ApplyCurrentValues works only for scalar values as you have already found. So you have to use your additional information about made changes and set state of relations to Added by using ObjectContext.ObjectStateManager.ChangeRelationshipState.
I personaly gave up with this approach and I'm loading object graph from DB first merging my changes into attached graph and save it.
I answered similar question more deeply here.
Perhaps I need more context but whats wrong with:
recommendations.Add(newRecomendation)
?
In reply to comment:
Ok so whats wrong with
SomeServiceOrRepository.AddNewRecommendation( newRecommendation )
or
SomeServiceOrRepository.AddNewRecommendation( int parentId, newRecommendation )
Last Sentence? You mean the two questions?
This shouldn't be hard at all.
To summarize my answer I think you are doing things "the hard way" and really should focus on posting form values that correspond to the CRUD action your trying to accomplish.
If a new entity could come in at the same time as your edited entities you should really prefix them differently so the model binder can pick up on it. Even if you have multiple new items you can use the same [0] syntax just prefix the "name" field with New or something.
A lot of times in this scenario you can't rely on Entity Frameworks graph features because removing an entity from a collection never means it should be set for deletion.
If the form is immutable you could also try using the generized attach function off of ObjectSet:
theContect.ObjectSet<Review>().Attach( review )
Tons of ways out of this. Maybe you could post your controller and view code?

Reusing validation attributes in custom ViewModels

When I started using xVal for client-side validation, I was only implementing action methods which used domain model objects as a viewmodel or embedded instances of those objects in the viewmodel.
This approach works fine most of the time, but there are cases when the view needs to display and post back only a subset of the model's properties (for example when the user wants to update his password, but not the rest of his profile data).
One (ugly) workaround is to have a hidden input field on the form for each property that is not otherwise present on the form.
Apparently the best practice here is to create a custom viewmodel which only contains properties relevant to the view and populate the viewmodel via Automapper. It's much cleaner since I am only transferring the data relevant to the view, but it's far from perfect since I have to repeat the same validation attributes that are already present on the domain model object.
Ideally I'd like to specify the Domain Model object as a meta class via a MetaData attribute (this is also often referred to as "buddy class"), but that doesn't work since xVal throws when the metadata class has properties that are not present on the viewmodel.
Is there any elegant workaround to this? I've been considering hacking the xVal sourcecode, but perhaps there is some other way I have overlooked so far.
Thanks,
Adrian
Edit: With the arrival of ASP.NET MVC 2, this is not only a problem related to validation attributes anymore, but it also applies to editor and display attributes.
This is the quintessential reason why your input screens should not be tightly coupled to your model. This question actually pops up here on the MVC tag about 3-4 times a month. I'd dupe if I could find the previous question and some of the comment discussion here is interesting. ;)
The issue your having is you're trying to force two different validation contexts of a model into a single model which fails under a large amount of scenarios. The best example is signing up a new user and then having an admin edit a user field later. You need to validate a password on a user object during registration but you won't show the password field to the admin editing the user details.
The choices for getting around these are all sub-optimal. I've worked on this problem for 3 projects now and implementing the following solutions has never been clean and usually frustrating. I'm going to try and be practical and forget all the DDD/db/model/hotnessofthemonth discussions everybody else is having.
1) Multiple View Models
Having viewmodels that are almost the same violates the DRY principal but I feel the costs of this approach are really low. Usually violating DRY amps up maintenance costs but IMHO the costs for this are the lowest and don't amount to much. Hypothetically speaking you don't change how max number characters the LastName field can have very often.
2) Dynamic Metadata
There are hooks in MVC 2 for providing your own metadata for a model. With this approach you could have whatever your using to provide metadata exclude certain fields based on the current HTTPRequest and therefore Action and Controller. I've used this technique to build a database driven permissions system which goes to the DB and tells the a subclass of the DataAnnotationsMetadataProvider to exclude properties based values stored in the database.
This technique is working great atm but the only problem is validating with UpdateModel(). To solve this problem we created a SmartUpdateModel() method which also goes to the database and automatically generates the exclude string[] array so that any non-permissisable fields aren't validated. We of course cached this for performance reasons so its not bad.
Just want to reiterate that we used [ValidationAttributes] on our models and then superceeded them with new rules on runtime. The end result was that the [Required] User.LastName field wasn't validated if the user didn't have permission to access it.
3) Crazy Interface Dynamic Proxy Thing
The last technique I tried to was to use interfaces for ViewModels. The end result was I had a User object that inherited from interfaces like IAdminEdit and IUserRegistration. IAdminEdit and IUserRegistration would both contain DataAnnotation attributes that performed all the context specific validation like a Password property with the interfaces.
This required some hackery and was more an academic exercise than anything else. The problem with 2 and 3 is that UpdateModel and the DataAnnotationsAttribute provider needed to be customized to be made aware of this technique.
My biggest stumbling block was I didn't ever want to send the whole user object to the view so I ended up using dynamic proxies to create runtime instances of IAdminEdit
Now I understand this is a very xVal specific question but all of the roads to dynamic validation like this lead to customization of the internal MVC Metadata providers. Since all the metadata stuff is new nothing is that clean or simple to do at this point. The work you'd have to do to customize MVC's validation behavior isn't hard but requires some in depth knowledge of how all of the internals work.
We moved our validation attributes to the ViewModel layer. In our case, this provided a cleaner separation of concerns anyway, as we were then able to design our domain model such that it couldn't get into an invalid state in the first place. For example, Date might be required on a BillingTransaction object. So we don't want to make it Nullable. But on our ViewModel, we might need to expose Nullable such that we can catch the situation where the user didn't enter a value.
In other cases, you might have validation that is specific per page/form, and you'll want to validate based on the command the user is trying to perform, rather than set a bunch of stuff and ask the domain model, "are you valid for trying to do XYZ", where in doing "ABC" those values are valid.
If ViewModels are hypothetically being forced upon you, then I recommend that they only enforce domain-agnostic requirements. This includes things like "username is required" and "email is formatted properly".
If you duplicate validation from the domain models in the view models, then you have tightly coupled the domain to the UI. When the domain validation changes ("can only apply 2 coupon per week" becomes "can only apply 1 coupon per week"), the UI must be updated. Generally speaking, this would be awful, and detrimental to agility.
If you move the validation from the domain models to the UI, you've essentially gutted your domain and placed the responsibility of validation on the UI. A second UI would have to duplicate all the validation, and you have coupled two separate UI's together. Now if the customer wants a special interface to administrate the inventory from their iPhone, the iPhone project needs to replicate all the validation that is also found in the website UI.
This would be even more awful than validation duplication described above.
Unless you can predict the future and can rule out these possibilities, only validate domain-agnostic requirements.
I don't know how this will play for client-side validation, but if partial validation is your issue you can modify the DataAnnotationsValidationRunner discussed here to take in an IEnumerable<string> list of property names, as follows:
public static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance, IEnumerable<string> fieldsToValidate)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>().Where(p => fieldsToValidate.Contains(p.Name))
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}
I'm gonna risk the downvotes and state that there is no benefit to ViewModels (in ASP.NET MVC), especially considering the overhead of creating and maintaining them. If the idea is to decouple from the domain, that is indefensible. A UI decoupled from a domain is not a UI for that domain. The UI must depend on the domain, so you're either going to have your Views/Actions coupled to the domain model, or your ViewModel management logic coupled to the domain model. The architecture argument is thus moot.
If the idea is to prevent users from hacking malicious HTTP POSTs that take advantage of ASP.NET MVC's model binding to mutate fields they shouldn't be allowed to change, then A) the domain should enforce this requirement, and B) the actions should provide whitelists of updateable properties to the model binder.
Unless you're domain is exposing something crazy like a live, in-memory object graph instead of entity copies, ViewModels are wasted effort. So to answer your question, keep domain validation in the domain model.

asp.net mvc database interaction validation

Does anybody have any links or advice on how to hook up validation that requires interacting with the database before updating or adding to the database? Every example I see shows how to validate properties e.g. "Is Required", "Is Email", "Is Numeric", etc, but how do you hook up validation for "Can't order out of stock item"? This xVal blog post touches on it but doesn't provide an example.
I've been following the NerdDinner tutorial which uses a Repository, but this is the bit I don't quite get... Say we had an OrderController with a Create method, and before creating an order we had to first check that the item is in stock. In the NerdDinner style the Controller uses the Repository to talk to the database, so how would our Order object (Model) be able to enforce this validation along with the property validation, as it can't talk to the database?
Thanks for any help
In the NerdDinner tutorial, you can checkout the IsVaild and then the GetRuleViolation methods. Based on your business and database rules, you could use these to check the data you have before you insert it. You could even create an IsValidForInsert Method to check any insert specific rules you need to enforce.
In NerdDinner, the GetRuleViolation allows you to retrieve the violated rules and bubble them up to the interface as you choose.
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (CheckDbForViolation)
yield return new RuleViolation("Database Violation", "SomeField");
if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title is required", "Title");
if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description is required", "Description");
if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy is required", "HostedBy");
... etc ...
yield break;
}
public bool CheckDbForViolation()
{
/// Do your database work here...
}
You could take this further and split database code into the repository. The CheckDbForViolation would call the repo for the info and then determine if there was a violation or not. In fact if you are using a repository, I think that would be the preferable way of doing it.
You do not really need any guidance from examples on how to do this. Ultimately you will have to be able to create such applications on your own which means being creative.
I've decided from the beginning do not use either built-in validation or membership API in order not to run into its limitations at some point of time.
For your situation: it's pretty much standard.
Imagine the execution flow as follows:
Post form
Validate input data format without talking to the database
If (2) is pass, then you validate the input from the point of business rules/data integrity. Here you talk to the database
If (3) passed then perform your operation whatever it is. If it somehow fails (maybe data integrity rules in the database prohibit the operation, say, you deleted a related object from the other browser window) then cancel it and notify the user of an operation error.
Try to keep controller methods as empty as possible. The validation and operation logic should reside in your models and business logic. The controller should basically attempt the one intended operation and based on the status returned just return one view or the other. Maybe a few more options, but not the whole load of checks for user roles, access rights, calling some web services etc. Keep it simple.
P.S. I sometimes get the impression that the built-in features intended to simplify simple things for majority of developers tend to create new barriers over the removed ones.
I would create an OrderService with a method PlaceOrder(Order order). The OrderService use the Repository to perform CRUD ops and to enforce business rules (stock check) and eventually thrown exception on rules violation you can catch and report to the user.

Resources