How to apply the MVC pattern to GUI development - c#

I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.
My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?

If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction.
The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface.
The controller would access the model and load data into the view.
The controller would bind to events defined on the view interface.
The controller would then handle saving of data back to the model via an event.
If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes.
This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies.
Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.

Most every GUI framework (from MFC to SWT to whatever) is already MVC based. In fact, the MVC pattern was first created by Smalltalk-80 and later first really used for GUI development.
Double check and look at the standards and suggested practices for your GUI toolkit of choice. Sometimes MVC won't be a good pattern to work with when solving a certain problem or working with a particular toolkit.
Remember: MVC is a great pattern but isn't a one size fits all solution, don't try and force a problem into MVC when event-based or functional style programming will make your life easier.

Imagine this GUI:
The Zergling unit is presented to the user as an alien icon. You can see that it is in its idle animation. Call this the View.
The player moves the unit by clicking on it and a target location. You can subtitute the player for an AI if you want. Call this the Controller.
The HP and attack range of the unit is calculated every game frame when the unit is in combat. You can change this data to make the Zergling into a range unit. Call this the Model.
Keep this analogy in mind and extend it for your MVC designs.

The imortant thing for you to remember, is that in your MVC setup the Controller must know which View to call, but the View must know nothing of the Controller.
So your View must provide a generalized way for Controllers to interact with it, so that you can have several different Controllers call the same View (a standardized graphical output of some data provided as parameter, for example).
This gives you flexibility:
If your customer wants PDF output of
something you only provide HTML
output for, you can get away with
writing a new PDF View to be called
from the Controller with the same
parameters as the HTML View.
If your customer wants similar HTML output of a different data source (say), you can get away with coding a new Controller that provides a different data set to the same old HTML View, which gives the same HTML report just with other data.
If you keep your View detached from specific Controllers, and put the knowledge about which View to call from your Controller, you're well on your way.

Your controller should definately bind to events defined on an interface the view implements.
How you go about doing this can be the tricky part. Dependency injection? A view factory? Have the view instantiate the controller it wants? It really depends on how complex the application is going to be.
For something really quick and simple I would start with having each view construct it's controller and then look at other options if it needed to get bigger. Personally I think a full dependency injection framework is overkill for half a dozen forms :]

Related

What exactly am I using?

Sorry for the vague title. I am pretty ashamed to ask this but I really need my awareness right now. I cannot identify whether I am following an MVC pattern or MVVM pattern.
In my previous internship, we had C# code (.NET) which had a controller and connected directly to the database (there wasn't a service layer). The controller would fetch information, format into JSON and give it to Angular's controller, which would display it on the view.
In my current internship, we don't use Angular. We use .cshtml files. The service layer provides its information to the controller, which formats the MODEL and gives it to the .cshtml view and which displays the content.
My questions:
Which one is MVC and which one is MVVM? Please drop down to my level and explain. Most of what I've read on the web seems to confuse me more with what I observe at work.
Everyone at work calls both of them MVC and, I am really confused now. If both are MVC, what's the difference between the two?
Angular is definitely more Model-View-ViewModel-ish. Whereas what you're doing now definitely sounds like MVC.
MVVM is a special pattern where the UI state is encapsulated in a ViewModel, so that the rendering of the final UI is fairly dumb and just data-binding. The state logic to say, show this button, or hide this area is all encapsulated in the ViewModel. One benefit, is that this allows for unit tests to be built to test the ViewModel and thereby implicitly testing all of the UI behaviors. (see: Wikipedia article on MVVM and Martin Fowler's Introduction to Presentation Model which MVVM is a variation of.)
In MVC, the view itself has the latitude to control it's behaviors, what you want to show/hide, etc based off of the data provided, the model. This means that in MVC, you can't test the UI behaviors (e.g. if something is correctly showing or hiding based on data changes) without testing the UI itself.
So in summary, MVVM, the ViewModel controls the UI behavior and the UI itself is dumb and just uses data-binding and does what it's told to do based on the logic in the ViewModel.
In MVC, the UI is 'intelligent' and re-shapes and renders itself however it feels it needs to based on the data it receives from the model.
You can basically look at how the UI is rendered and if you see the UI rendering logic making a lot of its own decisions about how to render itself based on the decision, then you pretty much know you're using MVC. If you just see a lot of data-binding, where almost every behavior is driven by a separate class that encapsulates all of the logic for showing and hiding pieces of the UI and this data is passed to the UI via data-binding, then it's probably MVVM.
I hope that helps.
In both cases, you are using MVC (or at least an MVC-ish pattern). When using the .cshtml files, you are using server-side MVC. When using Angular, you are using client-side MVC (which is probably more like MVVM). The biggest difference is where the model is rendered into HTML elements; on the client, or on the server.
In my opinion, this is a better way to view the differences in what you have done.

Porting Silverlight MVVM app to AngularJS

We're porting an existing Silverlight application into AngularJS/Typescript.
The application has a classical MVVM structure with data models, view-models and views. The models are somewhat tightly interconnected: for example, there are IObservable<> event streams which notify container models of changes within child models.
Here's what confuses me: in MVVM, everything that binds to view is a view-model. One view-model may have a list of other view-models that it contains. In all AngularJS tutorials for people with WPF/Silverlight background, however, only the $scope is called a view-model. What about the nested objects? Are they just domain data models, and you bind to them directly without any intermediate view-model layer?
Then, there's another question: if my data object changed somehow (for example, some service updates it when receiving data from the network, or it simply does some work based on timer), how do I notify the view that it should be updated?
First, I would like to say that you shouldn't try to match one technology to another technology. Doing an app in C# is not doing an app in Javascript (or any flavor of it) so trying to put a name on how the silverlight things are called on Angular/javascript is not a good idea.
What I would suggest is you (and your team) learn how Angular applications are made, what components are used for what purpose and then port the IDEA to angular. Coding an Angular app like a silverlight app is not a good idea.
Anyway, for the sake of the answer, I'll answer some of your questions since I am familiar with WPF / Silverlight.
In angular there is no real need to implement any observation pattern (there is pubsub).
Normally you have services which do a couple of things, like a repository pattern to access your backend or hold your data to use in different pages. Since services are singleton, if you modify it from pageA, pageB will know, so there is no need to tell, that is implicit.
$scope works as a glue between your controller and your view. Since $scope holds POJOs (plain old javascript objects you can put in there anything you need. You can have there nested objects or functions. Then you can use those properties on the $scope in the view without any problem.
If a Service query a backend, it updates the service's data and every controller using that service will automagically get the updated content. The trick here is to know is that you don't have to kill the reference and just update the value.
So, take a little time to learn Angular without having Silverlight in mind, learn what every piece does and start working. That is my advice.

Difference in MVC & MVP interms of code in c#

when we search Google for difference between MVC and MVP then thousand of article is available but i read few but they are not showing difference in terms of coding sample. so if anyone knows any url from where i can see a sample code for both MVC & MVP implementation then please tell me the url. i want basically small sample code by which shown the difference through coding flow in c#. i hope i am very much clear what i am looking for.....i need code same code one with mvc coding flow and another with MVP. i am not asking for theoretical explanation.
I also don't have sample code on my blog post "MVVM vs MVP vs MVC: The differences explained" but I do have a section for each architecture that discusses how to implement them using words. I will describe it here.
MVP requires a few implementation details
Each view must implement an interface for the view (eg IUserEditView for editing users). This interface contains functions for things that the presenter might need to do (eg, showUsers(IList users), displayMessage(String errorMsg)
A presenter is created for each view. It contains functions that the view will need to call (eg, saveNewUser(User user), selectedUserChanged(User user))
An instance of the presenter is created in the view's codebehind. When view events occur, appropriate messages are forwarded to the the instance of the presenter. eg, when the save button is clicked, all the user details are forwarded to the presenter in the form of a new user....myPresenter.saveNewUser(new User(txtUserName.text, txtPassword.text))
When the instance of the presenter is created in (3), the view is passed as an argument to the constructor. This way, the presenter can reference the IUserEditView from (1)
That is the meat of MVP. You will probably need to implement the mediator pattern and have all the presenters inherit from base presenter. This way, presenters can send messages to each other without having to reference each other explicitly which is important (eg, if a new user is added, maybe you need to update a related view like users online).
MVC is a bit more tricky.
The controllers have a method of selecting which view is displayed. This could be referencing just a dictionary of instances of all the views but a better way is to have some class outside the controller manage the details and then the controller can just select the view with something like ShowView("UsersView", listOfUsers). Note the separate class can be a base class, or a factory, helper
A method of forwarding actions from the views to appropriate controllers. With the web, you just can determine the controller & method from the request url (eg, http://www.mysite.com/mycontroller/method, www.mysite.com/Users/AddNew/). For other systems, you will have to implement a class to manage the messages, or just directly forward them to an instance of the controller in the view. I've only used MVC with the web so I'm not so sure about the last point.
Because of (2), the view is now able to trigger actions in the controller. When it does so, the controller modifies the model (the implementation of this will depend on the details of your model).
Updates to the model get sent to the view (usually via an observer pattern). Check out INotifyPropertyChanged if using .net
Word of caution: Although I have described how to implement both methods, they should not really be considered interchangeable. There are cases when you want MVC, MVP, and MVVM. I think if you don't have technology limitations around using MVVM, then it is your best choice. I am biased but I think maybe people are moving away from MVC and towards MVVM (or MVP) except for very specific cases like ASP.NET MVC. My article describes this in more detail if you need clarification.
Short summary for when to use each in terms of C#
WinForms -> MVP
WPF -> MVVM
ASP -> MVC (if you can't use ASP.NET
MVC, then MVP will work too)

What exactly is GRASP's Controller about?

What is the idea behind Grasp's Controller pattern?
My current interpretation is that sometimes you want to achieve something that needs to use a couple of classes but none of those classes could or has access to the information needed to do it, so you create a new class that does the job, having references to all the needed classes(this is, could be the information expert).
Is this a correct view of what Grasp's Controller is about?
Generally when googling or SO'ing controller, I just get results about MVC's (and whatnot) which are topics that I don't understand about, so I'd like answers that don't assume I know ASP.NET's MVC or something :(
Thanks
According to Wikipedia:
A Controller object is a non-user interface object responsible for receiving or handling a system event.
From Applying UML and Patterns:
What first object beyond the UI layer first receives and coordinates ("controls") a system operation?
Controllers, across the board - be it in MVC or GRASP or Patterns of EAA - are all about receiving input and responding to events.
I conceptualize it very literally: think of a video game controller.
It responds to input events - the user pressing buttons. It doesn't necessarily know what to do when you hit a button, but it at least receives the event.
Looking at the controller, one can easily figure out what the system events are - that is to say what inputs it responds to and how the user interacts with the system. On a Nintendo Controller, it's evident that system events are:
Press A
Press B
Press X
Press Y
Press ↑
Press ↓
Press →
Press ←
Press L
Press R
If we were to take all these events and build a software controller to deal with them, it would be an MVC controller: these events are all concerned with the physical controller as presented to the user - it's "view", if you will. But there's a second layer of input events for most video games, where button mashing maps on to specific system operations. For example, if you're playing as Scorpion in Mortal Kombat 2, pressing ← ← B triggers one of your special moves. In that case, the system could need different controllers which deal with these different kinds of events:
Here, the NES Button Controller is a MVC controller which would keep track of the state of UI elements - for example, remembering what buttons were pressed in what order. Depending on application state (see Application Controller - another one!) the NES Button Controller would response to certain button combinations by invoking methods on the other controllers - for example the Scorpion Controller - which are Use Case Controllers.
What's important is that by looking at the design of these controller objects, you can quickly and easily enumerate the system events they respond to.
Altogether, in the end, the MVC Controller is still a kind of GRASP Controller - as its methods tend to represent system events, which respond to user input. But there are other GRASP controllers which are not MVC controllers: Use Case controllers. A GRASP Use Case controller might respond to system events such as "user creates a new sale" while an MVC controller would respond to events like "system receives a PUT request for /sales/new" or "a java.awt.event.ActionEvent fires`".
Models contain data. Views present the data.
Views listen to models, using the Gang of Four Listener pattern.
Controllers decide what to do with the user input. Either they call methods on the models, construct new objects in the current Set of models, remove objects from the current Set of models, rewire views to different models, add views, remove views, or reconfigure views.
GRASP is just a tool to better understand software, and hopefully prevent one from making blatant mistakes in the creation of new software through good design practices. It really has nothing to do with MVC, but it can be used to better understand MVC.
The key in MVC is that the model isn't polluted with code that handles display details. That way you can isolate the "business logic" or "what the class is supposed to do" inside the model alone. Views react to changes in the model because the model emits messages to each view which has registered itself against the model (the listener pattern). The messages are often quite terse, basically the don't need to contain any data other than "the model has changed".
When the views get notified that a change has occurred in the model, the view then acquires the necessary data from the model's public interface. Once the view has the data it needs, it displays the data to the user (using whatever interface the view was meant to support). This isolates the presentation of the data to a class which will break when the view changes incompatibly, and allows modification of the view code without the model class requiring "compatibility" modifications.
The controller is responsible for knowing where the focus lies, and which model or view to update. It's the glue that puts things together, and is responsible for correct handling of input.

C# model view controller

So I am creating a C#/Winforms application in a model-view-controller pattern. My view-controller needs to instantiate multiple groups of objects. The object groups are elements of the model and elements of the view. So for example a textbox and the model to go behind that text box.
I'm wondering if the best way to do this is to put everything in some sort of collection and tie them together with a key?
In the WinForm MVC apps I've built, I typically don't allow the controller to instantiate anything (I try and keep the "new" keyword out of my controllers).
If I need an object I ask a service for it, and internally that service is going to fetch that object from a data source (repository or the like), or in the case of a new object it will likely utilize some kind of factory to get me a new object (with any necessary pre-filled properties already set to default values, rules run, etc.).
The way I like to think about this sort of problem is this: how would I make this work (and make it reusable) if I didn't have a GUI for a view, but instead had a command-line input for my view? The logic to create/add/delete/update the model should be somewhere in your domain, not in the controller. Then the controller just becomes the mediator between the model and the view. The view becomes an I/O mechanism that is just a prettier version of a command-line interface.
Hope that makes sense.
Have you considered using WPF instead of WinForms? It has a nicer MVC-like model and built-in databinding that is much more powerful. It would probably solve your problem and help you build with more modern technology besides.
Perhaps you should design your model to match what the view needs? Then there would be only one model for the controller to pass on to the view.

Categories

Resources