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.
Related
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.
i've created a forum system in MVP pattern but i'm not sure if i implemented it in a right way. so here is what i ended up with:
i've created a database which has three tables: forums, threads, posts
added a new typed dataset to the project and then dragged all the tables into it
created three new calsses: ForumsModel, ThreadsModel, PostsModel
added three interfaces: IForumView, IThreadView, IPostView
three more classes: ForumsPresenter, ThreadsPresenter, PostsPresenter
inside the model classes i just call the typed dataset methods and in presenter i've called the model methods. the views are .aspx pages. that's all there is for the forums system but here is the tricky part:
since MVP pattern is an UI pattern i have to do the validations of data in Application itself. so with my design the MVP is the application!
what did i do wrong??
edit 1: first of all about why i chose typed dataset with stored procedures over other options: it's the lightest data provider that doesn't compromise whatever architecture you have. other options are direct sql which is not a good option for newly created application, LINQ to sql classes which are too heavy to be instantiated with each request, Entity Framework which is great but is too much for such a simple task! at least if i was creating a blog engine it would have been my first choice.
as for the why i didn't choose MVC, it's because i think MVP is the better pattern since it'll give me complete seperation of different parts of my application. at the end it's a matter of tase but you should be able to implement any pattern, right?
i've seen different flavors of MVP but the one i'm trying to implement is this:
model<------------->presenter<-------------->view
the databind option is for the presentation model pattern which is introduced by martin fawler as far as i remember but the one i'm trying to create is a microsoft version which basically is an extended version of the PM pattern.
two days ago i asked a question about data validation and someone suggested that i should do it in "Application itself" so when i asked where is this "Application" he said that the MVP is an UI pattern and it shouldn't be your "Application" and you should implement the MVP in your user interface layer. so that's the reason i asked this question at the first place!
With MVP the code behind becomes the View implementation based on a View interface.
The View interface contains the page events the Presenter will need to bind to in order to change the state of the View, as well as properties and methods it might need. For instance it could hook onLoad event and call into the View to change it's state. In doing this it's agnostic to the View implementation and knows nothing about controls. This means you can write unit tests without an ASPX instance.
To create a MVP engine that automates wire up, you would make use of a base page, generics and IoC. The IoC allows you to set dependency overrides for things like WebContextBase which is visible to only that request pipeline, and which can be passed to your Presenter constructor.
IoC also allows you to inject other dependencies Into your Presenter to help keep it light weight. This way you can move business and data access to other layers.
MVP is really useful where you have to use WebForms, such as with most CMS systems. If you aren't constrained, then use MVC.Net for new web development.
Update: As promised here's a fairly decent example. The bit it's missing is the dependency overrides which can be done like this:
var dependencies = new DependencyOverrides
{
{typeof (HttpRequestBase),new HttpRequestWrapper(Request)},
{typeof (HttpResponseBase),new HttpResponseWrapper(Response)},
{typeof (IPrincipal),Context.User},
{typeof (IIdentity),Context.User.Identity},
{typeof (IUserProfile),Context.User.Profile},
{typeof (HttpSessionStateBase),new HttpSessionStateWrapper(Session)}
};
presenter = container.Resolve<TPresenter>(dependencies);
You made an architecture mistake by choosing webforms over the ASP.NET MVC framework. Also typed datasets are so 2003, you should use Entity Framework. Get with the times!
Have you looked at ASP.NET MVC? It's the Model-View-Controller pattern, and will handle all the routing and plumbing for you. You'll get easy model validation with DataAnnotations, and there's plenty of Resources and Tutorials
Or is there a specific reason why you need to use the MVP pattern with classic ASP.NET?
Since your question was not about the merits of MVC vs MVP or Typed Dataset vs Entity Framework, I am assuming you have a compelling reason to do things the way you are doing them.
With that out of the way, you don't seem to be doing anything wrong. With MVP, validation is supposed to take place in the Presenter implementations, as they have access to your view instances during postbacks. Of course you could also use client side validation with javascript.
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)
I have an example with a bunch of logic in my GUI class (winforms). I am going to refactor that so that there is no logic in the gui and a separate class holds all the logic.
What is that pattern? Say I had a form class called AddAddressForm, what would you call the associated file that holds the logic? AddAddressMediator (doesn't quite fit that pattern), if I was doing WPF I would call it the ViewModel (but I am not).
Sounds something like model-view-controller without the model part.
I don't think its called anything. I've tried doing that sort of thing in the past with Windows Forms, but unfortunately it didn't really work:
For each form I had another class called something like MyFormLogic that supposedly contained all of my logic for the form, with the form itself just containing a load of methods and events for manipulating the form (things like an AddButtonClicked event, and a AllItems collection property)
It seemed like a brilliant idea at the time (Yay easy unit testing!), but what actually happened is the MyFormLogic class became just as big and messy as before, and now I had a whole lot of extra pointless code exposing the extra methods events in my actual form class. (Also creating an instance of forms was a pain)
I'd recommend that instead you work on refactoring out as much logic as possible into lots of smaller classes that do 1 thing, rather than 1 extra class which deals with all forms logic (Its difficult to explain what I mean without some examples)
By the example given , it seems that your object shares some kind of common data.
Look at the Flyweight Pattern then.
I believe it is called Model-View-Presenter pattern. although it is commonly used in asp.net, it should be applied to WinForm as well.
http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
Martin Fowler splits original MVP pattern into 2 patterns , Supervising Controller and Passive View, But I still like its original name , MVP.
it depends type of logic , say you have Conditonal Logic and you create different object from it , so seprating this in a new class will be pointing to Factory Method.
2- If you have complex algorithms in your class and you seprate it another class/s , you most probably using Strategy Pattern.
lot of other combinations also possible.
It's Model-View-Controller (MVC). In your example, the Model is the Address, the View is the dialog, and the Controller just mediates events from the dialog to the Address object.
Note: you may omit the Controller for really simple situations, but don't if you ever want automated unit-tests; the separation (via interfaces) will pay off.
I believe this is called Humble View.
For more details and different takes on it, see the Humble View section of the GUI Architectures page on martinfowler.com.
What you describe is still the Model-View-ViewModel pattern, which isn't specific to WPF. The core tenet is that the ViewModel contains state and logic, and the View constantly synchronizes itself with the ViewModel. This is nice and easy with WPF bindings, but they aren't a prerequisite; any stateful UI can utilize MVVM. The Forms flavor of the pattern can get quite wordy on the view side.
Sounds like your basic separation of concerns by breaking out the view and functionality into different files. Not really sure if it really falls under any sort of pattern per say, but it does remind me of web forms a liitle bit with the views and code behinds.
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 :]