Keeping the model in sync with the viewmodel - wpf

I am creating a chat application that will also have the ability for file transfer. I am trying to design it with the MVVM pattern utilizing Prism.
My model for this application, or at least this one module(the application only has one module at this time, and it might be the only module), is a ChatManager class that is responsible for hosting servers, joining servers and holding all the state information of the chat sessions. It might be a client that is connecting to another server, or it might be both a client and a server as any individual who hosts a chat will also be a client to his own server.
In my application I have different views and viewmodels for each of the different areas of the program, the message area, the area that has the user list, and the area where users type their messages. The views know nothing about the viewmodels, and the viewmodels know nothing about the views. The viewmodels are very simplistic and contain nearly no logic.
All the logic resides in my ChatController class which basically controls the flow of the application. It is responsible for creating all of the views, all of the models, assigning the proper viewmodels as the datacontexts of the views, and injecting each of the views into the shell at the appropriate time. It also has the responsibility of assigning the actual data to the viewmodels, from the model.
The problem I'm having is how to cleanly keep the viewmodel ObservableCollections up to date with the Lists contained within the model. For example, in the model I have a list of connected users. Whenever that list changes, such as when a user connects or disconnects, I need to update the ObservableCollection of users in the viewmodel that handles the user list.
The way I'm thinking I need to accomplish this is using events. So I've created events that are fired in the model whenever a user connects, whenever a user disconnects. Surely I must have events as well for when the server is sending out a message to all of the users and all the other things the model actually does.
I guess my question is, is this a good way of doing it? Should I instead change the model's user collection to be an ObservableCollection and avoid the events altogether, simply assigning the viewmodel's collection to the model collection?
The more I try to structure this application, the more confusing it becomes for me. Right now my controller is quite large in the number of methods it has and I haven't even begun to add all the features of the chat program that I want to.

I think the whole question's redundant because of the last but one paragraph :)
ObservableCollection is part of System.Collections.ObjectModel. It's nothing to do with any particular UI technology so I don't see any need to keep it confined to the view model rather than having it up in the core and replacing your Lists.

Related

What is best practice for sharing model objects between multiple viewmodels?

In my WPF application I'm using the MVVM pattern and the repository pattern. I have a repository that provides a list of aircraft objects. From a user perspective, I want to display these aircrafts in several different ways (e.g. on a map, in lists, in textual form, etc..), and also allow the user to filter the objects. To achieve this I have built views and viewmodels for each of the different ways of representing the data.
My problem now is that I'm not sure what the best practice is for making the list of aircraft objects available for all the different viewmodels. Here's some of the alternatives I've considered:
1.Inject the repository into each viewmodel, and then get all the objects from the repo.
2.Inject the repository into a MainViewModel that retrieves all the objects from the repo, and then inject the object collection into all other viewmodels that needs it.
So in sum: I have a set of viewmodels that all make use of the same collection of model objects. What is the best practice for sharing this collection between the viewmodels when using the repository pattern?
In a WPF application I'll typically create service objects which encapsulate repositories which in turn contain a session object each, but I use dependency injection to inject the actual implementations. One of the major benefits of doing this is that everything can be easily mocked for unit testing, but another one is that you now have total control over the scope of these objects. If you're pulling your data from a database then you'll have different strategies for session management depending on whether you're developing a windows app vs a web site (say) and in enterprise applications this requirement will change even within the same code base. There's a good article on Germán Schuager's blog discussing the pros and cons of various session management strategies but for WPF applications using one session per form seems to be a good one. If you're using something like Ninject then you simply scope your ISession object to the view model for your top-level "page" and then all the objects within the logical hierarchy for that page can create their own repositories without needing to know about each other. Since they're all sharing the same session object they're also sharing the same entities in the repository cache and thus the model is now being shared by multiple view models. The only thing that remains is to add property notification to the entity classes in your domain layer so that changes made by one view model propagate through to the others, but that's a topic for another post (hint: your DB layer should provide some mechanism for injecting your own wrapper proxies to add property change notification automatically using things like Castle DynamicProxy etc).
The general rule of thumb is that EACH view should have it's own ViewModel, you can reuse ViewModels via inheritance or adding properties but again a view "DESERVES" it's own ViewModel.
You can have your views leverage interfaces, your viewmodels can implement interfaces.
We have a complex composite financial application where we needed to share various model objects across viewmodels, So we took an approach: we created a high level Model Object which holds collections of other model entities. This high level model is returned/populated in servicelayer. We share this high level model object in many viewmodels and with many PRISM modules using event aggregator .
So in your case you may have a AircarftsData Model, which can maintain collection of aircrafts. you can populate this model using your repository. Then You can pass this AircarftsData in various viewmodels.
We have shipped our application in production with this design and faced no issues as such. One thing you might want to be careful of Memory leakage of this Model object. If somehow any child object of this Model is leaked in memory then whole high level model may remain in memory.
Your data should be located in some place... (Service, Database, File, Etc...).
In that case, you should have a class which manage yours client requests:
GetAllAircrafts, Create, Update, Etc...
This class somtimes called XXXService.
I think that this is where you should expose your collection of models.
This service can be injected to the view models and share the collection of models through a get property (Maybe as a read only collection...?)
Good luck !

What is the real purpose of ViewModel in MVVM?

I had a talk with teamlead about this topic and from his point of view we can just use bindings and commandings omitting ViewModel, because we can test UI behaviour without VM using Automation or our own developed mechanisms of UI testing (based on automated clicks on Views). So, if there are no real benefits, why should I spawn "redundant" entities? Besides, automated integration tests look much more indicative than VM tests. So, it seems that we can mix VMs and Models.
update:
I agree that mixing VMs and Models brings into single .cs a data model and rules of data transformation for representing it in a View. But if this is only one benefit - I don't want to create a VM for each View.
So what pros of VM do you know?
The VM is the logic behind your UI. combining the UI code with the logic ends up in a mess, at least from my experience. Your view should define what you see - buttons, menus etc. Your VM is in charge of the binding and handling events caused by the user.
Edit:
Not wanting to create a VM for each view doesn't sound like a SW-oriented reason. Doing so will leave your view clean of logic and your model free to be the connecting layer between the core layer and your app layer.
I like the following example referring to the model and its role (why it shouldn't be combined with the VM): imagine you're developing some Android app using Google maps. Google maps are your core. Then one fine day you really need the option to, say, color parts of the map in pink, bright pink. An email to Google asking for colorPink(Map)will probably get you nowhere. That's where your model steps in and provides you the map wrapper that you need to define your pinky method.
Without a separate model, you'd have to go through every VM that uses map and update it.
So, the view has a role, the model has a role, the VM is the logic between those.
Edit 2:
There are some cases where there's no need of a model layer - I tended to disagree at first but was convinced after a discussion: In relatively small applications, the model can end up being a redundant wrapper with no added functionality over the core. In such cases, you can use the core objects directly.
What is he binding to? Whatever he is binding to is effectively a view model, whether you call it that or not. If it also doubles as a data model, then you're violating the Single Responsibility Principal (SRP). Essentially, the problem here is that you're lumping together code that is servicing different parts of the application architecture, which will lead to a convoluted mess.
UI Testing is a pain not just because you need to accomodate for changes in the View which can occur many times but also because UI tends to interfere with its own testing. Depending on the tests needed you'll need to keep track of focus, resize and possibly other (mouse) events which can be extremely hard to make it a representative test.
It is much easier to scope the test to the logic in the ViewModel and leave the UI testing to humans. The human testers do not need to test the logic; their only consern should be the UI.
By breaking down a ViewModel into a hierarchy of ViewModels you might be able to reuse a ViewModel multiple times. There is no rule that states that you should have a ViewModel for each View. (After a release or two I end up there but that's besides the point :) )
It depends on the nature of your Model - sometimes they are simple and can serve as both like you are suggesting. However, depending on the framework, you'll need to dirty up your model with some PropertyChanged event code which can get messy and distracting. In more complex cases, they serve as a mediator between your the view and the model. Let's suppose you're creating a client app that monitors a remote process or database entries - creating View Model's for these entities let's you surface your data in a way that is convenient to bind to for a UI framework (but is silly in a DB framework), encapsulate operations as commands, perform validation, etc etc.

Does sharing one instance of ViewModel among several Views have any merits?

One of my collegues offers quite a strange approach where VMs are used like singletons and each is attached simultaneously to several views.
I see no pros for such weirdness besides a kind of data sharing instead of caching at data access layer.
I've never seen this in practice but don't want to reject the ideas just because of that.
P.S. I speak about sharing one instance, not about applying differen views to one VM.
Thanks.
I suppose this approach could be useful if the views were to be kept in sync and made to look identical. Otherwise, I agree that it's confusing.
The only time I've seen singleton view models used in the real world are when you have a view that is also single instance, meaning that only one copy of the view is allowed to be open at any given time. In that case, there is a performance benefit because the view model doesn't have to be recreated every time the view is re-opened.
I'm not sure I would necessarily call it a "singleton" view model, but I like to share view model instances between multiple view controls in some cases. For example, this can be quite useful in a master/detail scenario where changes you make to the details may change the way the master part looks visually. For example, a list/tree view with an editing panel beside it that shows details of the selected item. Sure, you could do this kind of thing by passing messages between two VMs, but that seems more likely to add additional code than VM re-use.
Where I wouldn't recommend having a completely singleton VM is if you need some kind of master/detail scenario where the detail editing is modal, as in a dialog you open to make changes. There you are going to want to encapsulate the edit in a separate instance to make cancel support easier. An application-global (e.g. static) singleton implementation just makes that kind of thing much messier.
In theory you must have a View Model for each view, but I think that in some cases may be useful use tha same view model for different views. For instance, supose you are displaying a User in differents application´s places and you want that when the User.Name changed in an application´s place, also in all other places where the User is showed, the User.Name changed too. For this notification issues, it is better have only one view model, then using the INotifyPropertyChanged interface all views will be notified. I think that this is what your collegue would may want, but also is not good make an over use of this, because would increase the complexity of the application, and/or may bring some unexpected behaviors.

WPF/Silverlight enterprise application architecture.. what do you do?

I've been wondering what lives in the community for quite some time now;
I'm talking about big, business-oriented WPF/Silverlight enterprise applications.
Theoretically, there are different models at play:
Data Model (typically, linked to your db tables, Edmx/NHibarnate/.. mapped entities)
Business Model (classes containing actual business logic)
Transfer Model (classes (dto's) exposed to the outside world/client)
View Model (classes to which your actual views bind)
It's crystal clear that this separation has it's obvious advantages;
But does it work in real life? Is it a maintenance nightmare?
So what do you do?
In practice, do you use different class models for all of these models?
I've seen a lot of variations on this, for instance:
Data Model = Business Model: Data Model implemented code first (as POCO's), and used as business model with business logic on it as well
Business Model = Transfer Model = View Model: the business model is exposed as such to the client; No mapping to DTO's, .. takes place. The view binds directly to this Business Model
Silverlight RIA Services, out of the box, with Data Model exposed: Data Model = Business Model = Transfer Model. And sometimes even Transfer Model = View Model.
..
I know that the "it depends" answer is in place here;
But on what does it depend then;
Which approaches have you used, and how do you look back on it?
Thanks for sharing,
Regards,
Koen
Good question. I've never coded anything truly enterprisey so my experience is limited but I'll kick off.
My current (WPF/WCF) project uses Data Model = Business Model = Transfer Model = View Model!
There is no DB backend, so the "data model" is effectively business objects serialised to XML.
I played with DTO's but rapidly found the housekeeping arduous in the extreme, and the ever present premature optimiser in me disliked the unnecessary copying involved. This may yet come back to bite me (for instance comms serialisation sometimes has different needs than persistence serialisation), but so far it's not been much of a problem.
Both my business objects and view objects required push notification of value changes, so it made sense to implement them using the same method (INotifyPropertyChanged). This has the nice side effect that my business objects can be directly bound to within WPF views, although using MVVM means the ViewModel can easily provide wrappers if needs be.
So far I haven't hit any major snags, and having one set of objects to maintain keeps things nice and simple. I dread to think how big this project would be if I split out all four "models".
I can certainly see the benefits of having separate objects, but to me until it actually becomes a problem it seems wasted effort and complication.
As I said though, this is all fairly small scale, designed to run on a few 10's of PCs. I'd be interested to read other responses from genuine enterprise developers.
The seperation isnt a nightmare at all, infact since using MVVM as a design pattern I hugely support its use. I recently was part of a team where I wrote the UI component of a rather large product using MVVM which interacted with a server application that handled all the database calls etc and can honestly say it was one of the best projects I have worked on.
This project had a
Data Model (Basic Classes without support for InotifyPropertyChanged),
View Model (Supports INPC, All business logic for associated view),
View (XAML only),
Transfer Model(Methods to call database only)
I have classed the Transfer model as one thing but in reality it was built as several layers.
I also had a series of ViewModel classes that were wrappers around Model classes to either add additional functionality or to change the way the data was presented. These all supported INPC and were the ones that my UI bound to.
I found the MVVM approach very helpfull and in all honesty it kept the code simple, each view had a corresponding view model which handled the business logic for that view, then there were various underlying classes which would be considered the Model.
I think by seperating out the code like this it keeps things easier to understand, each View Model doesnt have the risk of being cluttered because it only contains things related to its view, anything we had that was common between the viewmodels was handled by inheritance to cut down on repeated code.
The benefit of this of course is that the code becomes instantly more maintainable, because the calls to the database was handled in my application by a call to a service it meant that the workings of the service method could be changed, as long as the data returned and the parameters required stay the same the UI never needs to know about this. The same goes for the UI, having the UI with no codebehind means the UI can be adjusted quite easily.
The disadvantage is that sadly some things you just have to do in code behind for whatever reason, unless you really want to stick to MVVM and figure some overcomplicated solution so in some situations it can be hard or impossible to stick to a true MVVM implementation(in our company we considered this to be no code behind).
In conclusion I think that if you make use of inheritance properly, stick to the design pattern and enforce coding standards this approach works very well, if you start to deviate however things start to get messy.
Several layers doesn't lead to maintenance nightmare, moreover the less layers you have - the easier to maintain them. And I'll try to explain why.
1) Transfer Model shouldn't be the same as Data Model
For example, you have the following entity in your ADO.Net Entity Data Model:
Customer
{
int Id
Region Region
EntitySet<Order> Orders
}
And you want to return it from a WCF service, so you write the code like this:
dc.Customers.Include("Region").Include("Orders").FirstOrDefault();
And there is the problem: how consumers of the service will be assured that the Region and Orders properties are not null or empty? And if the Order entity has a collection of OrderDetail entities, will they be serialized too? And sometimes you can forget to switch off lazy loading and the entire object graph will be serialized.
And some other situations:
you need to combine two entities and return them as a single object.
you want to return only a part of an entity, for example all information from a File table except the column FileContent of binary array type.
you want to add or remove some columns from a table but you don't want to expose the new data to existing applications.
So I think you are convinced that auto generated entities are not suitable for web services.
That's why we should create a transfer model like this:
class CustomerModel
{
public int Id { get; set; }
public string Country { get; set; }
public List<OrderModel> Orders { get; set; }
}
And you can freely change tables in the database without affecting existing consumers of the web service, as well as you can change service models without making changes in the database.
To make the process of models transformation easier, you can use the AutoMapper library.
2) It is recommended that View Model shouldn't be the same as Transfer Model
Although you can bind a transfer model object directly to a view, it will be only a "OneTime" relation: changes of a model will not be reflected in a view and vice versa.
A view model class in most cases adds the following features to a model class:
Notification about property changes using the INotifyPropertyChanged interface
Notification about collection changes using the ObservableCollection class
Validation of properties
Reaction to events of the view (using commands or the combination of data binding and property setters)
Conversion of properties, similar to {Binding Converter...}, but on the side of view model
And again, sometimes you will need to combine several models to display them in a single view. And it would be better not to be dependent on service objects but rather define own properties so that if the structure of the model is changed the view model will be the same.
I allways use the above described 3 layers for building applications and it works fine, so I recommend everyone to use the same approach.
We use an approach similar to what Purplegoldfish posted with a few extra layers. Our application communicates primarily with web services so our data objects are not bound to any specific database. This means that database schema changes do not necessarily have to affect the UI.
We have a user interface layer comprising of the following sub-layers:
Data Models: This includes plain data objects that support change notification. These are data models used exclusively on the UI so we have the flexibility of designing these to suit the needs of the UI. Or course some of these objects are not plain as they contain logic that manipulate their state. Also, because we use a lot of data grids, each data model is responsible for providing its list of properties that can be bound to a grid.
Views: Our XAML definitions of the views. To accommodate for some complex requirements we had to resort to code behind in certain cases as sticking to a XAML only approach was too tedious.
ViewModels: This is where we define business logic for our views. These guys also have access to interfaces that are implemented by entities in our data access layer described below.
Module Presenter: This is typically a class that is responsible for initializing a module. Its task also includes registering the views and other entities associated with this module.
Then we have a Data Access layer which contains the following:
Transfer Objects: These are usually data entities exposed by the webservices. Most of these are autogenerated.
Data Adapters such as WCF client proxies and proxies to any other remote data source: These proxies typically implement one or more interfaces exposed to the ViewModels and are responsible for making all calls to the remote data source asynchronously, translating all responses to UI equivalent data models as required. In some cases we use AutoMapper for translation but all of this is done exclusively in this layer.
Our layering approach is a little complex so is the application. It has to deal with different types of data sources including webservices, direct data base access and other types of data sources such as OGC webservices.

MVVM pattern: ViewModel updates after Model server roundtrip

I have stateless services and anemic domain objects on server side. Model between server and client is POCO DTO. The client should become MVVM. The model could be graph of about 100 instances of 20 different classes. The client editor contains diverse tab-pages all of them live-connected to model/viewmodel.
My problem is how to propagate changes after server round-trip nice way. It's quite easy to propagate changes from ViewModel to DTO. For way back it would be possible to throw away old DTO and replace it whole with new one, but it will cause lot of redrawing for lists/DataTemplates.
I could gather the server side changes and transmit them to client side. But the names of fields changed would be domain/DTO specific, not ViewModel specific. And the mapping seems nontrivial to me. If I should do it imperative way after round-trip, it would break SOC/modularity of viewModels.
I'm thinking about some kind of mapping rule engine, something like automappper or emit mapper. But it solves just very plain use-cases. I don't see how it would map/propagate/convert adding items to list or removal. How to identify instances in collections so it could merge values to existing instances. As well it should propagate validation/error info.
Maybe I should implement INotifyPropertyChanged on DTO and try to replay server side events on it ? And then bind ViewModel to it ? Would binding solve the problems with collection merges nice way ? Is EventAgregator from PRISM useful for that ? Is there any event record-replay component ?
Is there better client side pattern for architecture with server side logic ?
Typically, I've kept a reference to the DTO in my Model classes. For multiple models, I ensure each model knows how to construct itself from a DTO, as well as how to Save itself using an injectible "saver" or other service provider object. Carrying around a reference to the DTO makes it pretty easy, when you call Save() on the model, to modify the old DTO according to the Model before passing it back to the service.
Hopefully any "updates" to other objects after a Save() operation could be communicated in other DTOs, which should then be loaded into the appropriate Model classes used by your ViewModel.
The downside to this is that you do indeed have to write the mapping code, but this is usually the easiest part. I am not convinced this is the best way to do things and I would appreciate reading others' responses.
I used another variation with a lot of success. We had a real-time GUI, so repetitive redraws on the client were not acceptable.
We made our DTOs aware of their property changes, and emit PropertyChanged events to the ViewModel, therefore replaying server-side events.
Code is straightforward to write, unit test, etc. It becomes easy to browse when PropertyChangeListeners (interfaces implemented by ViewModels) are typed.
This boundary can also be used to switch threads to the GUI worker thread.

Resources