Converting WPF / ADO.NET Data Services application to the MVVM pattern - Examples - c#

I have a WPF application which was written in C#. This application hasn't been written with any particular design pattern in mind, but as I have learnt .NET I've realised that the MVVM model would be suitable. Thus, I'd like to start converting the code.
This will be the first time I've used MVVM, and whilst I'm willing to get stuck in, I'm finding it difficult to find solid MVVM examples online where an ADO.NET Data Service is the Model and XAML is the View. I'd like to look over some examples before setting off on the process of converting my own app to make sure I have correctly understood what I am doing!
Can anyone recommend a small (but non-trivial) example application with code which uses WPF, ADO.NET Data Services and the MVVM model?

I recommend starting with any example that uses MVVM with WPF, and there are many. The fact is that a clean implementation of MVVM will not have any true data access code in it -- data access should be handled by another, abstracted layer (see MVVM where to put Data Access Layer?).
Work on designing a viewmodel that encapsulates all of the data and interaction that your (already existing) views require. Clean out your codebehind and get your view binding to your viewmodel.
Once you have that going, you can worry about how to get your objects to and from a persistence store, but the actual work of doing so does not belong in the M, V, or VM.
I know that there are tons of examples with data access right in the viewmodel or even the model, but those are meant to be quick illustrations that don't require tangents to address dependency injection, facades, etc.
Find any nontrivial example of MVVM in WPF, and when you get to the part where they deal directly with data access, remind yourself that at that point you'll be using an abstraction of persistence.

Related

Understanding application flow with MVVM

I am having a hard time understanding how MVVM is used in case of more complex applications. All the examples I can find are extremely basic Apps.
Let's say I have a "Package Delivery" application. To perform a delivery I have to do 3 steps:
Scan the package
Enter any damages or problems with the package
Let the recipient sign on the device
All this information gets validated on the device and then sent to the backend.
In MVC I would implement this like this:
The DeliveryController handles all of the logic. This includes navigation between pages, fetching of API data and validating all of the data once it is all collected.
The controller acts as the "Connection" between the Views and collects all the information and brings it together.
But how would this be done in MVVM? Where would all the data be brought together? Most implementations of MVVM I can find do something like this:
In this, the data entered in each View would have to be passed to the next ViewModel until the end of the chain is reached. At that point the SignatureViewModel would do the validation and make the API call. That seems very weird and like it would get very confusing, since data would just be "passed through" multiple ViewModels just to have it at the end of the chain.
Another option I see would be that each ViewModel handles it's own data:
Here for instance the DamagesViewModel would validate and send the data it's own View handles. The big issue with this is that data does not get sent as a whole. Also there can not be any validation of the entire data before it is sent.
My last idea would look like this:
This adds a DeliveryViewModel that essentials acts like the DeliveryController does in MVC. It would handle which ViewModel to navigate to next, handle what API calls to make and validate all the data once it is entered.
To me (as someone who has mostly used MVC) this last options seems most sensible. But I also feel like it might miss the point of MVVM.
How is this usually done in MVVM? I would really appreciate any pointers. Links to articles that explain this well are much appreciated.
Also if anyone knows of any publicly available repositories or projects that have this kind of pattern in them, I would love to see them.
Even when using MVVM I still use some form of a controller and consider ViewModels as basically transformation of data to facilitate the view.
So for me there is still a service or controller layer that completely separates the middle and back end tier from the rest of the architecture.
View models come into play depending on the consumer/app - fetches data from the service tier, transforming the data, validating etc for the purpose of a consumer/app/etc.
I have struggled quite a bit with the same thing. Especially since I’ve used MVC quite a lot.
I think the most important thing to consider is that MVVM is not meant to solve exactly the same things as MVC. You can still implement a controller outside of this pattern to complement it. It also changes quite a lot the general design of the application.
One mean to do it that I have used is to implement the controller as a singleton that can be shared between VewModels. This controller can per example be injected into the ViewModels using dependency injection.
Viewmodels could then for exemple subscribe to events coming from the controller to update.
But this is one way to solve this problem among others.
MVVM is a way to organize code. It’s one way to separate your user interface from your logic.
I have found a blog where you can have a look where MVVM architecture is described perfectly.Though here writer demonstrates MVVM for windows form app but at least you can get some idea about architectural design of MVVM.
https://scottlilly.com/c-design-patterns-mvvm-model-view-viewmodel/
Also please have a look into this repo.
https://github.com/MarkWithall/worlds-simplest-csharp-wpf-mvvm-example

MVVM - Patterns and Practicality

I've been using MVVM for a while now with WPF. And i've learnt a lot over the course of development (going from never using it, to having a couple of applications developed in it)
However, recently I had some comments directed at the code which made me wonder if i'm doing things the right way. My current setup works (roughly) like this:
Model - Responsible for storing the data, data validation using
IDataErrorInfo and dirty tracking
ViewModel - Responsible for getting the data (from a repository like
pattern) and formatting it for a view's consumption (things like
filtering, ordering) also responsible for command handling from the
view (save, load, filter changes etc)
View - The usual UI stuff
Now it was mentioned to me that i should NEVER have business logic inside the model, and that the model should be as thin as possible, the viewmodel should be responsible for handling things such as data validation and dirty tracking.
I've seen comments and criticism on both sides of this, with people against and for putting logic in the model, What i have yet to see is any actual reasons for these sweeping statements. So id love to know if there is an actual reason i should be refactoring my setup.
Also, given that i do move the logic to the viewmodel, I can see the need for having multiple viewmodels where i currently have a single, for example:
Person - Model
PersonViewModel - Handles the dirty tracking, data validation etc
PersonsViewModel - Handles getting a collection of PersonViewModels,
filtering etc
PersonsView - The UI
This seems a little redundant, but perhaps i'm misunderstanding something. What I'm really looking for is some actual reasons for doing this one way or another, or if this is another argument like the use of code-behind in MVVM (pure opinion with little reasons etc)
High level description of MVVM:
View: User Interface
Model: Business logic and data (e.g Domain Model+Repositories, or Transaction Script+POCO entities, etc)
ViewModel: Data exposted to view in such form, that is easily consumable from view. Wikipedia's definition says: The view model is an abstraction of the view that exposes public properties and commands.
I like the Practical MVVM Manifesto (archived version) principes: Simplicity, Blendability, Designability, Testability.
This is very high level and abstract description and that's why you may find a lot of variations of MVVM. Whatever mvvm style you choose, keep in mind the responsibilities and principles and you should be ok. Try to avoid complexity. MVVM is not a silverbullet and you cannot cover all scenarios with single design pattern. One mvvm implementation may be suitable for one application but not for another. I, for example, build my mvvm architecture from scratch for each new project to ensure the best fit
When is comes to responsibilities:
Take validation as an example:
validation logic that password and repeat password inputs should be equal is clearly presentation logic and should be present in viewmodel. On the other side, there may be business rule, that password must contain at least one special character. This logic should reside in Model, however you may expose it in viewmodel to be easily consumable from view. It's a business logic, but you may need to present it somehow.
if you have application that only uses webservice to retrieve and store then your model will be probably just the data access components.
Here is couple of resources:
Wikipedia: https://en.wikipedia.org/wiki/Model_View_ViewModel.
MVVM is variation of Martin Fowler's MVP pattern, you may find it useful as well: http://martinfowler.com/eaaDev/PresentationModel.html
MSDN (Pattern and practices): https://msdn.microsoft.com/en-us/library/hh848246.aspx
I like to think of the Model layer as anything that has nothing to do with how the app is hosted (i.e. independent of WPF). It is one or more dlls that represent the business domain and the operations that need to be performed in it. If it would make sense to take theses same dlls and use them in a web application, windows service e.t.c then it is usually a sign that the split between Model and ViewModel is appropriate.
There's no simple answer to your question. The simplest answer is that the model and view model should contain the code that you should unit test. The separation between model and view model is a little less distinct. I like to keep the model as simple as possible and limit it to whatever is exchanged with the server tier. The view model should encapsulate the model, and provide any addition functionality (both business logic and abstract presentation logic) so that you can keep the presentation layer as simple as possible (declarative, in the case of WPF XAML).
I see it this way:
Model - Object that can be passed around. A Common type between different layers for communication.
ViewModel - Specifically created for Views. This should contain UI logic, for example, Data Annotations etc will go here. You might also call your web service methods here (assuming your actual business logic sits in a facade layer, or your database logic sits in a different layer/project) to populate the Views, dropdowns etc. You might end up with multiples of these per view, depending on your design.
View - UI Only.
I am not afraid to put external calls in the ViewModel

MVVM approach, what's a good way? How to improve/speed up development?

this post is meant to have a list of suggestions on MVVM approach... What tools do you use, what do you do to speed up development, how do you maintain your application, any special ways of finding defects in this design pattern......
here is what I do:
So first i create my model/db with EF.
Then I create Views (either user controls or windows) with their respective viewmodel. I usually place the viewmodel in the same location as my view. But while starting the name of my view with "UC-name", I call my viewmodel just "name-model".
In my viewmodel I implement InotifyPropertyChanged
in my xaml view I have a resource of my viewmodel, and bind my grids/controls via the itemsource to the staticresource.
I try to do a lot of front end logic with triggers and styles and also place some code in the xaml.cs file if it regards logic for behaviour of my controls.
I can reach my viewmodel from my view (xaml + xaml.cs).
for communiation between viewmodels I use MVVM lights.
that's pretty much it.
Things I'm thinking about
I'm thinking of using T4 templates for generating viewmodel/view. What do you guys think of this. is this worth it?
when using MVVM light Messenger, we get a subscription based communication, and sometimes I find it hard to track what has changed in my DataContext. Any suggestions on this?
any other improvements or suggestions are more than welcome !
Answering first question regarding View/ViewModel generation I think for CRUD cases it makes sense to use some tools, otherwise it won't be that beneficial.
Pretty nice basic scaffolding implementation example you can find here: WPF CRUD Generator. Also WPF solution by DevExpress looks really promising.
There are at least couple Codeplex projects addressing View/ViewModel generation:
WPF Scaffolder
ViewModel Tool by Clarius
But I am quite pessimistic about T4 for such scenarios. I think writing and polishing own T4's will take you much more time than adoption of existing tools.
Regarding MVVMLight messenger I can say that it will take you some time to get used to it. And as soon as you will understand difference between "regular" and message driven MVVM you'll be able to use it in most efficient way. Very nice article about messenger is Messenger and View Services in MVVM. And want to add a really important quote from there:
A Word of Caution About Messenger
Messenger is a powerful component that can greatly facilitate the task
of communication, but it also makes the code more difficult to debug
because it is not always clear at first sight which objects are
receiving a message. Use with care!
I'm very much a proponent of Domain-Driven Development (DDD). First I have the designer write specifications, roughly adhering to the methodologies in Behavior-Driven Development (BDD). This then forms the basis of unit tests for Test-Driven Development (TDD), for which I use NUnit. For the domain layer itself I start with an Anemic Domain Model i.e. entity classes containing mostly properties and virtually no methods; there are plenty of arguments both for and against this but personally I find it works well. Coupled with this is the Business Logic Layer (BLL) which knows only about the domain entities.
For the Data Access Layer (DAL) I prefer NHibernate, it supports all the usual things you would expect like lazy loading and repository management etc but particularly important is the Object Relational Mapping (ORM) i.e. the bit that translates between your domain entities and the underlying database representation.
One of the problems with NHibernate, in my opinion, is that it uses XML files to do the mapping for the ORM. This means two things: first is that any errors you introduce won't get picked up until run-time. Secondly it's not really a proper "solution" to ORM at all, instead of writing mapping classes you just wind up writing XML files. Both of these problems can be solved by using Fluent. Fluent solves the first problem by replacing XML files with C# files, so your mapping declarations are now done in code which will usually pick up errors at compile-time. It solves the second problem by providing an auto-mapper, which looks at your entities and generates the necessary mapping files automatically. This can be manually overridden if and where needed, although in practice I find I seldom need to. Since the auto-mapper uses reflection is does tend to be a bit slow but it can be run in an offline utility and then saved to a configuration file that is loaded at run-time for near-instant start-up; the same utility can also be used to create your database automatically. I've used this tech with MySql, MS Server and MS Server CE...they've all worked fine.
On the other side of the tier is your view model. I've seen a lot of projects create an almost 1:1 mapping of domain entities to view model classes, I may infuriate MVVM purists by saying this but I really don't see the point in doing all that extra work for something that isn't really needed. NHibernate allows you to provide proxies for the classes it creates, using Castle Dynamic Proxy you can set an intercepter to your NHibernate session factory that automatically injects INotifyPropertyChanged notification to all of your entity properties so that they work with the WPF binding mechanism. Another product, uNhAddIns, allows you to replace any lists with an ObservableCollection in order to get INotifyCollectionChanged support (for reasons I won't go into you can't just put an ObservableCollection into your entities without it seriously affecting performance).
If you're designing and building your application properly using technologies like these and fully unit-testing along the way then you're going to need some way of handling Inversion of Control (IoC) so that you aren't passing object references around all over the place, and for that you'll need a dependency injection framework. My personal preference is Ninject but Unity is pretty good too. Dependency injection is particularly important for good database session management (so that all relevant objects reference the same session), a good rule is one session per WPF form or one per web request.
There are lots of other little things I use to make life easier (MVVM Lite, log4net, Moq for mocking objects for unit testing etc) but this is my core architecture. It takes a while to set up but once you've got it all going you can build fully functional database applications in literally minutes without any of the headaches traditionally associated with layer management in tiered enterprise applications...you just create your domain entities and then start coding for them. Your schema is created automatically, your database is created automatically, you can use your entity classes to fill your database for immediate stress testing and you have full WPF support without having to pollute your entity classes with code or attributes not actually related to the domain. And since all development is driven by anemic domain entities your data is already in the perfect format for serialization into html/ajax/soap etc when you want to give your app web capablities.
You'll notice that I haven't discussed the presentation/XAML layer, mainly because that part is now straightforward. Using a decent architecture you can actually create a fully working and tested application that then only needs pure XAML added to turn it into a releasable product.

C# MVC Pattern Help

I am having a go at refactoring my Winforms code into MVC pattern. I have never used this pattern before.
Obviously the GUI will be the view, the controller will be the 'middle tier' which is invoked by any user interaction with the GUI, and the model performs the requried tasks and informs the view of any status changes.
My question is, with the model, I am assuming that can span a great number of classes and is not confined to one 'model' class? Also, can these three sections all be within the same assembly?
Thanks.
for Winforms i wouldnt suggest MVC - id suggest MVVM
try this tutorial http://weblogs.asp.net/dwahlin/archive/2010/09/30/silverlight-sessions-coming-to-devconnections-las-vegas-november-1-4.aspx
this article mentions Silverlight but the MVVM pattern is generic and can be applied to Winforms
as pointed out by Roger Lipscombe - MVP may also work - try this for information on that http://davybrion.com/blog/2010/08/mvp-in-silverlightwpf-architectural-overview/ - again specific to Silverlight in this light but as its a pattern it can be adapted
For Winforms I would suggest learning about the MVP (Model/View/Presenter) and the MVC pattern. Although others have suggested MVVM might be a good idea I disagree - MVVM takes advantage of data binding offered in WPF and although Winforms supports binding to some extent, it's not as binding centric as the WPF architecture/object model.
The 'Model' layer can consist of many classes and I would always use the 'Single Responsibility Principle' as well as other Solid principles when modelling the classes within this layer of your architecture.
Useful links:
SRP - http://en.wikipedia.org/wiki/Single_responsibility_principle
SOLID - http://en.wikipedia.org/wiki/Solid_(object-oriented_design)
MVP - http://en.wikipedia.org/wiki/Model-view-presenter
No, model is not confined to one model class. In model you usually represent your database, and other data-related stuff. Controllers are responsible for most of the actions.
And yes, all this component will land in one dll. Bet there will be a lot of other files, like view files, which are not always compiled in MVC (but you can force that).
You might want to think about making a 'Model' class as an interface. Then all of your specific models implement that interface but share common methods (such as update, delete, etc.)
They can definitely be written in the same assembly. Your folder structure (strictly), should follow a Models/Views/Controllers structure, and place the code files underneath those respectively.
If you decide to try out the MVP pattern, which is a good choice for Winforms, check out MVC#, a framework for building MVP applications. It's simple and good.
Maybe you are interested in the approach I am heading for to combine the MVC/ MVP pattern with Databinding with fluent interfaces. mvc and databinding, what is the best approach?
If MVC, MVP or MVVM is used is from my point of view a matter of perspective. They will all lead to an abstraction of data, logic and visualization of the data.

WPF C# MVC/MVP pattern and user control code-behind

I am developing a large-ish application in WPF/WCF/NHibernate/etc. and have implemented the MVP pattern (although this question is still relevant to MVC) as the core architecture.
It feels quite natural to extend and add functionality as well as to come back and make changes on certain bits and pieces, as far as the core architecture is concerned (controllers, views, etc).
But at times the code-behind-ness of custom user controls that I create feels as if it "breaks" the MVC/MVP paradigm implemented, in that code concerns leak in the design and design concerns leak in the code. Let me clarify again, this is only for user controls. It is my personal opinion that this code-behind model (for both ASP.NET and WPF) is a 'Bad Thing', but no matter what my opinion, I'm stuck with it.
What are your recommendations for best practices in such a scenario? How do you handle such concerns? Do you for instance work around the code-behind-ness of custom controls and if so how??
Since you are using WPF, you should really look into the MVVM (Model-View-ViewModel) pattern. It is a form of the Presentation Model (PM) pattern discussed by Martin Fowler. WPF is very binding-oriented, and provides a very powerful and rich data binding framework for XAML. Using MVVM, you can completely and entirely decouple your ViewModels from your Views, allowing truly POCO UI development that offers the ultimate in separation of concerns and unit testability.
With MVVM, you will be able to modularize and decouple all of your views, including Windows, UserControls, etc., from the code that drives them. You should have no logic in Code Behind other than what is automatically generated for you. Some things are a little tricky at first, but the following links should get you started. The key things to learn are the MVVM pattern itself, Data Binding, Routed Events and Commands, and Attached Behaviors:
MVVM
Data Binding
Attached Behaviors
Attached Commands (VERY USEFUL!)
Routed Commands
Routed Events
WPF + MVVM has a bit of a learning curve up front, but once you get over the initial hurdle, you will never, ever want to look back. The composability, lose coupling, data binding, and raw power of WPF and MVVM are astonishing. You'll have more freedom with your UI than you ever had before, and you will rarely, if ever, have to actually bother with code behind.
I happen to like code-behinds (yet another personal opinion), but they work only as long as they do nothing but facilitate interactions between control events and the rest of the application. I'll admit that I've seen a lot of counter-examples, though. I even wrote a few of them....
Really, all the code-behind should do is "oh, someone clicked this button; there's probably something that wants to know about that." PRISM (from MS patterns and practices) provides a lot of architectural infrastructure for WPF and Silverlight; that includes a publish/subscribe interface that allows the controls and the code-behinds to simply publish an event while not even being aware of possible subscribers, or what the subscribers might do with the event. PRISM also adds commands for Silverlight.
A common variant of MVC for WPF and Silverlight is MVVM (Model, View, ViewModel). The ViewModel makes data available to the user controls in some form that is most useful (such as ObservableCollections, to facilitate two-way binding).
Custom Controls are there to display stuff. In that regard they are no different than a button or a drop down combo box. The trick is that don't let them handle stuff directly. They need to send stuff through the View Interface and the Presenter need to likewise interact with them through the view interface.
Think of it this way. If you ignored MVP the custom control would interact with the model in specific ways. what you doing with MVP is taking those way and defining them with the View Interface. Yes you are adding an extra call layer but the advantage is that you thoroughly document how it interacting with the rest of the system. Plus you get the advantage of being able to rip it out and replace with something entirely different. Because all the new thing needs to do is the implement it's portion of the view interface.
If you have a specific example I can illustrate better.

Categories