C# MVC Pattern Help - c#

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.

Related

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

Application(solution) structure for Model View Presenter(+ Passive View) in WinForms?

Once upon a time I wrote a code that, with time, started to smell. It was not coded in a way that it could be easily tested. There were tight coupling on each of the children windows with database-centric Microsoft controls (like BindingNavigator, etc). But then it came the day when I was tired of my own code as it was not reusable, testable, or understandable (even by myself).
After reading about better ways to split presentation from business logic and database access/persistence, I came up with the first big change. I was then able to call a presenter for the children forms of my, let’s say, “MainForm”.
Nowadays, I have a bunch of Presenters, Views, Repositories, Models and Interfaces which I would like to organize in a “standard” project structure (i.e. projects like Business, Model, UI, Test). Can somebody expose such a structure, and, if possible, example folders they use inside each of them?
Also, should I use an only-one “MainPresenter”? or is it better to have one for each children form I will use, for example:
var searchReceivalPresenter = new SearchReceivalsPresenter(
new SearchReceivalsForm { MdiParent = this }, new SearchReceivalsRepository());
In my opinion I should keep several presenters.
Thanks in advance,
I think there may be some misunderstanding of MVP here - I wrote an article about how to do MVP with Windows Phone 7, but I cover the basics of MVP, and you should be able to understand the general theory and then apply it to WinForms:
Developing WP7 apps using the MVP pattern
But to quickly answer your question, every Form should implement a View interface, and every Presenter should handle 1 and only 1 View interface.
Where it gets tricky with WinForms is when you want to open a child Form. What I ended up doing is having the parent Presenter directly call a Show method on the child Presenter. The child Presenter would then use Dependency Injection to instantiate an implementation of the related View interface.
UPDATE (because I didn't fully answer the question) :)
Let me describe a project structure i've used for a winforms/MVP app:
/ - solution root
/[App]Core - project that contains the Model - pure business logic
/[App]Core/Model - data model (lowercase "m"), POCOs
/[App]Core/Daos - data access layer (all interfaces)
/[App]Core/Services - business logic classes (interfaces and implementations)
/[App]Ui - project that contains all UI-related code, but is UI-agnostic
/[App]Ui/Model - contains POCOs that are used by the UI but not the Core
/[App]Ui/Presenters - contains presenters
/[App]Ui/Views - contains view interfaces
/[App][Platform] - project that contains all UI-specific code (e.g. WinRT, WinPhone, WinForms, WPF, Silverlight, etc)
/[App][Platform]/Daos - implementation of DAO interfaces defined in [App]Core
/[App][Platform]/Services - implementation of business logic interfaces defined in [App]Core
/[App][Platform]/Views - implementation of view interfaces defined in [App]Ui
Is that more like what you were asking for?

WPF: MVP vs MVVM

What is the difference between MVP VS MVVM? Why we are using MVP even though we have three layers: business, data access and presentation? Is there any specific reason to divide the Presentation layer into MVP?
MVP and MVVM are both derivatives of MVC. MVC is a pattern that separates the user presentation and interaction from the internal representation.
This requires three layers, since tying the user interaction/presentation directly to the internal representation will cause both to bend to conform to each other. In your application, you described these layers as the Presentation, the Business layer, and the Data Access layer. With only those very loose descriptions, you could potentially be describing any of the MVC derivatives, or the original MVC pattern itself.
The key differences between each of the derivatives are the dependencies each layer takes on the other layers, and how tightly they are bound to each other. This article has some details on the differences, though of course it shouldn't be considered authoritative:
http://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/
"... MVVM is attractive for platforms which support bi-directional binding with less effort. Also a minor tradeoff is ViewModel unlike Presenter can stand on its own (Presenter normally requires a View’s interface)."
We use at our company projects of WPF desktop application MVP instead of the built in MVVM for the main reason that in MVP the presenter is the main entry point that knows everything and no one knows about the presenter.
For each View the presenter which have one responsibility which is taking interactions from the IView interfaces by subscribing to events that the View triggers.
The presenter updates the View by a properties that encapsulates the internal View controls like TextBox with string properity and GridView with any Collection property. The constructor of the MainPresenter class will look something like this MainPresenter(IMainView, IEmployeeStore, IOtherDependency,..)
The Constructor of MainView class will look like this MainView(IPartialViewIfExists,..) that means the view does not know anything about the Presenter or anything else outside the View layer (which is the opposite of MVVM that enforces the MainView to directly couple the MainViewModel to automate the
two way databinding).
That clean loosely coupling architecture which the MVP provides is really powerful and flexible which enables the ability for the following:
Your application can replace the GUI with anytime without changing anything in the presenter, you can also change the GUI technology to something else like WinForms or something.
You can separate your GUIs in a separate project that doesn't require any dependencies of your main application like the presenters and dataAccesses
Your View can be used for any other application witch is useful for general GUIs.
You can unit test the views, the presenters and the data access classes easily.
The ViewModel in MVVM doesn't know about the View but I don't think that is helpful since it is responsible for the View. The View shouldn't know about the presenter which handles business logic and that's what exactly the MVP provides (or the way that we implement MVP).
That doesn't mean that MVVM is bad. MVVM is a good architecture and faster to code and easier to start with since it is already implemented in WPF and Xamarin but as I explained we prefer MVP for listed reasons.
In general MVP is cleaner and more scalable but requires more knowledge and coding experience and have to be implemented manually. MVVM is already there, it is easy to use and lets you implement faster but provides coupling and has some limitations. They all have their pros and cons and it depends on your need.

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.

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

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.

Categories