Autogenerated MVVM: Validation and INotifyPropertyChanged - wpf

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.

Related

What is the point of having both Model and ViewModel in M-V-VM?

I always find it tempting to put a model and a view-model together in one class, and I don't see the downside of doing that.
There must be a good reason for separating them. What am I missing?
ViewModel is the soft-copy of the View i.e. if you have a updateable ListBox on View, you will have an ObservableCollection in your ViewModel that represents that list of items in the listbox. Similarly if you have a Button on your View, the VM will hold its Command.
Model will be actually what has the data that the View shows. So the type collection in your VM is of, can be termed as a Model class.
E.g. a Employees ListView is a View, and has a data context which is the instance of EmployeeViewModel class that has an ObservableCollection property of Employee class where Employee class becomes a Model.
Usually there is 1-1 relationship between View and VM and 1-N relationship between VM and Model.
The model is the domain of your application and so contains your domain logic such as business rules and validations. The ViewModel is the model for your view. It handles the interactions between the user and the view, i.e. when the user clicks a button the view model will handle that interaction and may or may not make changes to the model. Normally in an OO language, you want your objects to have a single responsibility only.
In WPF the ViewModel usually implements the INotifyPropertyChange interface which is then observed by the view for any changes. You wouldn't want the model to implement this interface since it is not related to your domain in anyway.
Another reason for separation is that sometimes your view might not necessary show all data that is in the model. For example, if your model exposes 15 properties but in one of your view the user needs to see only 5 of those properties. If you place your model in the ViewModel the view would be exposed to all 15 properties whereas if you encapsulate the model in the ViewModel then only those 5 properties would be exposed to the View.
There are probably many more reasons but in general it is a good design principle to keep them separated. With that being said, if your application is small enough you can get get away with having your model and ViewModel together to reduce redundancy in your code.
The first real downside of doing this is a lack of separation of concerns. And soon this will lead to redundant code. Now, that said, I've seen a lot times where developers have used their Model objects as ViewModels. And if we're totally honest with ourselves, in a very thin app, separating these concepts can actually lead to more redundancy.
The best thing you can do is learn more about MVVM, and its roots in MVC and Presentation Model, but I think it's a great thing that you're asking this question and that you're not blindly following dogma. In fact, I often don't even start with MVVM at all when I begin a small app. I'll often start with a hundred lines or so in the code-behind, proving a concept, and then start refactoring it into MVVM.
More to the point of your question, the model and view-model have - in a conceptual sense - very different purposes. The Model includes your business logic (domain logic), data model (objects, attributes and relationships), and data access layer. The ViewModel is essentially an adaptor for the Model, adapting it for the specific purposes of the View. In some cases you might have 3 different views (and view-models) for a given data model object. Each view-model would be adapting those same attributes on the model object for the specific purposes of that particular view.
My simple answer (and I don't pretend to be WPF Guru) would be that , in WPF, you'd need a VM when:
1. You don't want to expose all your Model to a specific view
2. Your model is not in "WPF style" (doesn't implement INotifyPropertyChanged, no observable collections or no Commands).

MVVM model validation and data binding?

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.

Grids with ViewModels - WPF

Sorry if this has already been asked, but I just want to make sure that I'm doing this right.
If I have a domian object that has say 10 properties on it. I have a grid on my main form that I want to show the pretty much all the the properties from the model.
I created a viewmodel to wrap the domain object to show in the gridview but then I have to expose all the properties again. I just feel binding straight against the model through the viewmodel feels dirty and defects the purpose a bit.
So for example I don't really like this:
{Binding DomainObject.Property}
where DomainObject is property on my view model.
So my main question is, should I expose all the properties on the model through the view model just to bind it to the grid?
EDIT: Just for added information the domian objects are LINQ-To-SQL objects, so I don't think they implement INotifyPropertyChanged but I'm not sure.
Some people will say it doesn't matter, others say it does. I'm in the latter camp, for these reasons:
You increase the dependencies of the view, as it now depends on the data model, not just the view model.
You require the designers need to know the properties and structure of your data model.
You create more work for the (almost inevitable) refactoring when you decide you need a layer of indirection for formatting, validation, or whatever it might be.
As Thomas pointed out, data models often don't implement change notification
Yes, it's a little more work, but I believe it's worth it to reduce decoupling, maintenance headaches, collaboration with designers, and correctness.
PS. If you find yourself in this situation a lot, you might consider an implementation of ICustomTypeDescriptor that wraps any data object and exposes its properties with change notification. That way your VM can extend this generic wrapper until you decide you need to pull properties out for purposes such as formatting and validation.
If you need change notification on the properties and the model doesn't implement INotifyPropertyChanged, then you need to create new properties on the ViewModel. Otherwise, it's probably not a big issue to bind directly to the model : the MVVM pattern is just a guideline, you can bend the rules a little if necessary...
I think it is a matter of personal preference. I happen to believe it is perfectly fine to expose the Model in a single object from the ViewModel. Recreating all the properties of the Model in the ViewModel just results in a bunch of extra code.
However, this only works provided your Model implements change notifications so the data binding works.

MVVM Experts need your opinion on MVVM and Dataforms

as far as I understand the ViewModel should abstract the model from the view and add additional logic to handle the presentation stuff.
My question is:
How would I create a dataform that is suppose to handle user input for an order and details at once.
It should present fields for entering the orders as well as the fields for 1 detail.
My Model would have an object for an order which contains a list of OrderDetails.
How would look my ViewModel for my OrderEntryForm like?
Would I have an OrderViewModel and an OrderDetailViewModel and my
my OrderEntryForm would contain a property of OrderViewModel and one for OrderDetailViewModel? (nesting ViewModels?)
How would validation be handled in this case? Since Validation should go close to the model?
Especially when I work with RIA-Service...
Wouldn't it make more sense to put it in the ViewModel?
How far would you abstract the Model from the ViewModel?
Example:
private DateTime _OrderDate;
public DateTime OrderDate
{
get { return _OrderDate; }
set
{
if (_OrderDate != value)
{
_OrderDate = value;
OnPropertyChanged("OrderDate");
}
}
}
this would mean I have to map the ViewModel-Property to Model-Properties. Cannot leverage Validation-Logic from the Model here...
This example:
public DateTime OrderDate
{
get { return Model.OrderDate; }
set
{
if (Model.OrderDate != value)
{
Model.OrderDate = value;
OnPropertyChanged("OrderDate");
}
}
}
would requiere to pass in a Model. Have the access to the validation logic of the model but also a coupling...
Most examples on the web show dataforms which use ViewModel's that a just a representation of the tables not a real abstraction...
I know and I saw this
stackoverflow.com/questions/744474/combining-net-ria-services-and-mvvm-in-silverlight-3-0
I also read nikhils blogpost on this but this handles also only Products straight mapping from the tables of the database... =(
I know alot of questions...
What are your opinions on that topic?
How would you handle complex dataforms?
Chris,
I have had the same issue and end up implementing it in a crappy way :-( (two vieModels one per view, but passing the parent to the child View... bad stuff).
From my error I learn that next time I would give a try to:
Generate a single ViewModel, but in the child view pass a detail entity in the datacontext (this detail entity does not have to match with the proxy generated entities, maybe is a container of that entities).
Generate a singleton controller class: this class won't be exposed to the view, it will be transparent for the view, just the detail view model will ask the controller for that dependant data instead of going to the DAL.
Not sure if this are going to be clean solutions, have to give a try and fail :).
I agree with you... there are not real samples with this kind of scenarios.
What do you think?
Thanks
Braulio
PS: About validation, if we create our own super entities, we can there define our validation, in my case I have tried as well extending the entities using partial cases and then I can have an entity myPhoneNumberDetail with my special validation.
I personally think there are no hard and fast rules... well, there is one - be pragmatic.
Pragmatically speaking, a view model is a model, and so is a data model. Both are classes, independent of the UI, and surface state as properties, operations as methods, and notifications as events. The thing that I think in my mind differentiates them is how general they are. I see a model as generally usable across multiple views, vs. a view model optimized for a particular view.
I would personally never abstract for the sake of abstracting. I would never surface top-level properties for every model property and implement it by delegating to an underlying model. This increases work. It increases the amount of code to be tested. It requires propagation of metadata, change notifications etc. If there is some actual logic to add, then yes, there would be properties on the view model I'd expose and delegate to the underlying model as appropriate. Even there I'd ask if it is reasonable/appropriate to expose those as computed properties on the model (view model and data model are both models).
As far as surfacing DAL types directly vs. not, that in my mind is somewhat orthogonal. It depends on other factors - how much do you want to abstract the DAL, how useful a DAL type is - for example, if a DAL type has a lot of foreign keys, a presentation model equivalent or projection might be more useful where there is some denormalization done. Sometimes security might be the reason to write a presentation model/projection - eg. I don't want to send email addresses to the client, and instead want an alternate representation of email addresses.
In my sample, I used a DAL type directly, to simplify and not have an overload of concepts in a single sample. I do want to blog about presentation models and projections in a dedicated manner... and so didn't want to mix posts of viewmodel and .net ria services with presentation model concepts at the same time.
As is so often, with patterns, it really depends. The ViewModel can expose the underlying model, and there is no hard and fast rule that says you "must" hide everything and delegate. I have spoken to many folks that are strict adherents to LOD and still they agree that in the case of UI binding, it does not apply.
Now in the case of whether that model is a DTO or not there you will find a lot of differing opinions. Some believe that the only thing that should ever be on the client is a pure projection i.e. a DTO with all logic living on the server, while others believe that that moving entities between the tiers is fine. That would be an discussion for a different post. :-)
In general the guideline that i would recommend is always at least have a high-level VM which can be used for screen state, etc.
As far as child models, like OrderDetail, then if the child model is sufficent to just bind to then just expose it directly. Now one thing to consider is around notification, if you model is not implementing INPC than you may have no choice but to wrap it in order for binding to properly work.
Even if it implements INPC there may be view-specific concerns that that model does not contain, but which are required to for the view to function. In that case I would use simple aggregation and create an OrderDetailVM that directly exposes the underlying OrderDetail and adds additional properties.
For example
public class OrderDetailViewModel
{
public OrderDetail OrderDetail {get;set;}
public bool IsValid {get;set;}
}
Where IsValid is checking some screen-specific logic.
It really depends though on how much encapsulation you want to achieve. I wouldn't find anything wrong with using a delegation model. Depending on the complexity though it might get unwieldy, for example imagine if OrderDetail had additional children, etc.
HTH
Glenn
To clarify, the VM is an abstraction of the Model, not of the View and not the other way around.
You can certainly use multiple VMs to correspond to discrete portions of your View. If you're not going to need separate VMs for Order and Details, you can just have an OrderAndDetialsViewModel that contains everything, and the whole View will bind straight to that. This is where the abstraction comes in.
You are right, that your model's validation logic is going to be distinct from your ViewModel's validation logic, if you put any in there. In no case will the validation be in the View.
I'm not sure I follow your second example. What is the Model object? Your VM may know about the Model(s) from which it is composed, but it is not going to expose it/them as such directly to the View.
I hope this helps somewhat. Please let me know if there is any part of your post that I failed to address.

How do I maintain coherency between model and view-model in MVVM pattern?

Problem Statement
I'm writing a very basic WPF application to alter the contents of a configuration file. The data format is an XML file with a schema. I want to use it as a learning project for MVVM, so I have duly divided the code into
Model: C# classes auto-generated from xsd.exe
View-Model: View-friendly representation of the Model.
View: Xaml and empty code behind
I understand how the View-Model can make View-binding a breeze. However, doesn't that leave the View-Model <-> Model semantics very awkward? Xsd.exe generates C# classes with arrays for multiple XML elements. However, at the V-VM level you need Observable Collections.
Questions:
Does this really mean I have to keep two completely different collection types representing the same data in coherence?
What are the best practices for maintaining coherence between the Model and the View-Model?
I'm not a big expert, but I think that is the case yes. The general idea is indeed to propagate change between the view and the viewModel via Binding, and then between the ViewModel and the Model via events (in the Model -> ViewModel direction) or dependency (in the other direction).
I don't know how standard that is, but my understanding of MVVM is that the ViewModel should hold a reference to the model so that when the user modifies the view, the ViewModel should call the appropriate code on the model. The other way round, the Model should raise events when modified, and the ViewModel should update itself accordingly (the ViewModel being an observer to the model).
#Does this really mean I have to keep two completely different collection types representing the same data in coherence?
I think yes. It's pretty boring, but it works quite well. Hopefully, in the future we will have also a code generator to create the ViewModel part.
Karl is working on that: http://karlshifflett.wordpress.com/mvvm/
You need clearly ObservableCollections at the viewmodel so, yes, you will need two
completely different collection types in the model and in the viewmodel.
I have done an article about doing undo / redo in MVVM where you can find a possible solution to this. It uses what I call the MirrorCollection: an ObservableCollection derived class witch automatically obtains his items from a List (the list of the model).
I think it is an interesting solution, you can find the articles here
Part 1: Using the Viewmodel pattern to provide Undo / Redo in WPF
Part 2: Viewmodelling lists (here is the MirrorCollection definition)
Expose Events or delegates in Model and hook to the same in ViewModel, when ever values in the model changes notify to viewmodel via event or delegates and from Viewmodle you can update the UI.
If you want to update it from view model to model as simple as that just call some method pass the new values

Resources