When looking up tutorials for the best practices to do property validation in WPF MVVM I see a lot of people use the interface IDataErrorInfo I was just wondering if it is possible to setup automatic validation like that used in ASP .Net MVC using attributes?
Can anyone sugest what the best practices are for model validation in MVVM? Should the validation be on the base model class? or on the view model class?
Silverlight has a control called the DataForm that works using the DataAnnotations Attributes and someone was kind enough to port that control to WPF. I believe that is something along the lines of what you're looking for.
These are good questions!! Validation belongs in BOTH the Model and the ViewModel(s). Here is how I usually approach it:
First I put as much validation in the Model as I can - these will be rules that are independent of a given presentation. For example, assume an employee in your domain is not valid if it doesn't have a EmployeeNumber property that is not null, and six characters in length, and each of the six characters must be a digit.
Secondly, I have a base ViewModel class that implements IDataErrorInfo. In this base class I basically ask the Model if it is valid, triggering an error if it isn't (which is easy to translate to the View by virtue of IDataErrorInfo). I also make the implementing methods of IDataError info virtual, because...
Lastly, there will be edge cases unique to a given presentation that cannot be captured by the Model. For a (contrived) example, assume you have one presentation in which an employee is valid if only his first and last name are entered, and another that requires a middle initial as well. While you certainly can and should have a FullName component / valueObject property in Employee to validate that the property is not null, you need a subclassed ViewModel for each presentation to know if the user entries for the properties of the Fullame are valid in this case.
Finally, you can and should use a Validator for your Model validation - I like NHibernateValidator but there are certainly other (very) good ones available. Most of them, including NHibernate's, will support the attribute validation you are looking for. I prefer a cleaner alternative to attributes however, whereby I setup all validation rules for my validator in a separate project (ie, MyDomainImpl). Cleaner in the sense of less noise in the Model, and a cleaner separation of concerns.
Feel free to ask questions if you need to Also give yourself some time to work thru this until you have an approach that works for you - this is not a trivial topic.
HTH,
Berryl
My take is that validation should be on ViewModel and not on Model because :
Validations are for incorrect input
and the first logical point of UI is
ViewModel. It is good practice to
validate and stop request at
ViewModel and not send across invalid
data to the Model
Also many a times Models are legacy and the assumption is that they
cannot be modified. ViewModel creates
a good wrapper over the model.
If you are using any Dependency Injection tool for your aplication like Unity, Windsor Castle etc., you can use interceptors to validate ViewModels. Interceptors are invoked first before any call to ViewModel methods.
An example of using interceptor with Castle can be found here -
http://www.castleproject.org/container/documentation/trunk/usersguide/interceptors.html
Where to put the validation logic?
Software systems mostly need some kind
of validation to ensure that the
business logic has to deal with
correct data only. These validation
rules are defined by the business
model and so the Domain layer is the
right place to implement them. Just
keep in mind that you don’t start to
duplicate the validation code between
the business objects.
link
.
You might be interested in the sample applications of the WPF Application Framework (WAF). They show how to use the .NET DataAnnotations validation attributes together with the MVVM pattern.
Related
I would like to know how you are Design your Qooxdoo Code.
I don't get the right Architecture which I am satisfied with.
It is hard to encapsulate the View with logic like services.
I hope someone can give me a hint to a Pattern or something to find a good solution.
One of Qooxdoo's greatest features is a strong OO class system, so really the pattern that you use is up to you - MVC, MVVC, etc are all possible because Qooxdoo's OO system provides you the tools to implement your preferred pattern(s).
One pattern that I find very useful, especially in creating larger apps, is to define custom widgets for editing models; for example, if you have models (aka "Business Objects" etc) for Customer, Invoice, InvoiceLine, and Address having a widget for CustomerEditor, InvoiceEditor, InvoiceLineEditor, etc is really useful firstly because it encapsulates the code, but also because it supports binding.
Binding is a very powerful feature of Qooxdoo - to see why, let's assume for a moment that each one of your Editor widgets has a property called value which is the thing being edited.
In simple binding, your editor can bind properties of the model to the widgets which display and edit those properties, eg CustomerEditor bind value.firstName and value.lastName to a couple of qx.ui.form.TextField and automatically changes to the customer's firstName or lastName will be updated in the two TextField's. Binding can work the other way around too, so that changes to the TextField are copied back into the model.
There is a controller class called qx.data.controller.Form that can simplify making this happen, and optionally incorporate validation of user values and user feedback too.
If you have separate Editor widgets, you can also bind to them - for example, Customer could bind value.address to an instance of AddressEditor, and InvoiceEditor could bind the currently selected InvoiceLine to InvoiceLineEditor etc
I known there are several existing questions about whether to implement INPC on the model, most arguments are about code repetition because of property proxies, which will be not a concern in this case, because the Model and the ViewModel will be autogenerated by a tool, so any code-size arguments is invalid.
There are any drawbacks in not implementing INotifyPropertyChanged on the Model besides code size?
Also, the generated Model will be used directly by the programmers but the ViewModel will only be used by other generated code, so the size and complexity of the view model will be hidden, but the Model has to be as simple as possible without losing functionality, in this case Is better to implement validation and calculated properties on the model or in the view model?
Consider that the model may be or not database entities.
Thanks
This is too generic a question to be answered.
"Is better to implement ... ?" : This depends on the application need . Ideally the Model has all the properties and the Viewmodel is just the place where you fill the Model and write the necessary business logic.
Since you are talking about autogeneration, i suppose you have written some util which does this creation. Ideally the validation should be present in both Model and ViewModel. Model side validations are supposed to check any DB/server side validation if present and the ViewModel(VM) is supposed to validate the client for eg: In VM you validate for whether a property is greater than some other property, but in the Model validation you would validate for uniqness or null etc.
Other thing is the calculated properties(I hope this means calculation done in the database and filled in a property), these properties ideally should reside on the ViewModel .
Hope this answers your question.
I have a list of business objects (1000+) with 50 or so properties they have around 70 different validations that need to be performed. It seems like the way to go is to use a validation rule, but I really like IDataErrorInfo. Is it a waste of memory to have IDataErrorInfo defined for every object while they use the same validation all along?
PS: I didn't post the code because it enormous and tedious to look at.
IDataErrorInfo just contains a pair of properties.
It has no per-instance overhead.
It's up to you to make an implementation that peforms well; the shouldn't be too hard.
I am a big fan of extending the built in ValidationRule class and using it directly in bindings, as opposed to using IDataErrorInfo.
Check my blog post here, see if it helps: Taking data binding, validation and MVVM to the next level - part 1. This concentrates on how to use it for validating a TextBox, but the exact same thing applies to any bindable element, i.e. columns on a DataGrid. The advantages it gives you is you can keep the validation code out of your viewmodel and model (if you are using that sort of pattern), the validation is reusable anywhere, and you can be quite granular with which validations are applied and where.
As a new WPF programer I cant find the difference between two different way to validate user input:
What are the pros and cons of writing custom validation rule against implementing IDataErrorInfo, and vice versa? WhenShould I prefer one over the other?
Update:
Though I got my answer already, I found related article that may help others.
Basically, if you implement IDataErrorInfo, validation is implemented in the bound object, whereas if you implement validation rules, validation is implemented in objects attached to the binding.
Personally, if you're using MVVM, I think you'd have to be crazy to ever use anything except IDataErrorInfo. You want validation to live in the view model. If it's in your view model, it's centralized and it's testable. If it's in your view, then your validation logic can be wrong, or missing, and the only way to find it is by manually testing your view. That's a huge potential source of avoidable bugs.
There are places where it makes sense to use validation rules - if, for instance, you're building a UI around dumb objects (an XmlDataSource, for example). But for most production applications, I wouldn't go near it.
IDataErrorInfo
Validation logic keep in view model and easy to implement and maintain
Full control over all fields in the viewmodel
Validation Rule
Maintains the validation rule in separate class
Increase re-usability. For example you can implement required field
validations class reuse it throughout the application.
My opinion is, for common validation like required field validations, email address validattions you can use validation rule. If you need to do custom validations like range validations , or whatever custom validation use IDataerrorinfo.
You implement IDataErrorInfo to be able to use databinding with eas. You still build your custom validation rules.
I have an old VB6 application. I want to recreate it in VB.Net using WPF. But I am a bit confused about the "Model View Controller"-pattern. I have two books about design patterns (GoF and J.Bishop) afair this pattern is indeed not mentioned inside one of the two books. I have also searched the internet I found some java-examples. But I have still no clue how I should use MVC-Pattern (should I?) in my new WPF-application.
Let's say for example my model (in fact it is more complex) is only a wheel rim (circle) with the properties Manufacturer, Diameter and Depth. The user should be able to modify the properties using textboxes and ComboBoxes.
Could somebody create a small example that explaines the MVC-Pattern with WPF?
Of course I like reusable classes to have a feasible concept throughout the whole application.
thanks in advance
Oops
Here's a "brief" description of what the MVC pattern is and how I would apply it to a WPF application.
(I might have a few details slightly off since I've mainy hacked in Silverlight but the concept is similar enough.)
Basically, the idea is to separate concerns and define interfaces between the different parts of an application, with the goal of keeping the code structured and maintainable.
The Model in your example would be pretty much exactly as you described the wheel rim - a WheelRim class with the various properties defined in suitable data types. I would put the model i an separate assembly to keep it apart from the other code, but you can settle for just keeping the model classes in a "Models" folder. The model would also have a "twin" in a database, the model classes being pretty much one-to-one-mapped to tables.
(You might wanna have a look at Linq2SQL or Entity Framework, if the database is defined you can pretty much get the model for free along with suitable database access code.)
The View would be the actual WPF xaml files - Defining the Grid or Canvas or what have you. On the WheelRimView there would be labels and textboxes for displaying or accessing the different properties, perhaps along with product images and the like. The code behind for the view would have all the relevant event handlers (start, button_click and so on) for getting the data from the fields and passing them to the controllers.
The Controller would be any "handler code" that you would use to manipulate the data. We're talking the basic CRUD operations here, along with validation and the like. Also, the controller layer would be responsible for compiling the data in a format that can go seamlessly into the View. The WheelRimController hence would have methods like "GetWheelRimList", "GetWheelRim", "AddWheelRim", "ModifyWheelRim" and "DeleteWheelRim". The methods take the values as in parameters and manipulate the model objects accordingliy. the
I would recommend keeping the code-behind of the xaml files free from any "controller"-ish code like validation, aggregation and the like - the code behind should basically only take the values from the textboxes, listboxes and such and send them on "as is" to the controller methods for processing. Also, you should keep any data formatting code to a minimum when getting data for presentation (i.e., no filtering or translating in the view).
A typical use case of "User opens a wheel rim and edits the diameter" would play out thus in code:
User clicks "Edit" on a list page. The WheelRimView page loads.
The WheelRimView.Load() method (or corresponding) calls WheelRimController.GetWheelRim(wheelRimId).
WheelRimController.GetWheelRim(wheelRimId) gets the corresonding data from a database table and populates the properties of a WheelRim object, which is returned to the WheelRimView.
The WheelRimView inserts the property values into the labels and textboxes.
The user changes the diameter value and clicks the "Save button.
The WheelRimView.Save() method calls the WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) method.
The WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) method parses the diameter (if it is a string) and loads the model object. It applies the modified value to the model object and saves it into the database.
The WheelRimController.ModifyWheelRimDiameter(wheelRimId, diameter) returns a status code to the WheelRimView (for instance a predefined numeric stating any validation errors) to report the success of the save.
The WheelRimView displays a result message (hopfully "saved") to the user.
I hope that clears a few bits up.
Bevcause of the rich binding support available, WPF (and Silverlight) are well suited to MVVM (Model-View-ViewModel). MVVM is an extension of MVC that uses a view model to bind the current state of a view, instead of manipulating the view directly.
There are a bunch of MVVM frameworks available, as well as Microsoft's own Prism framework (which is arguably more useful if you have a larger, modular application).
WPF is probably more well suited to MVVM (Model-View-ViewModel). I'd recommend reading this MSDN article on MVVM and, perhaps, following their advice. There's also a nice collection of links I found on the Bryant Likes blog.