C# model view controller - c#

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.

Related

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.

ASP.NET MVC Views Extensibility at runtime

We are in the process of moving our application to .NET. One of the main goals is to allow modifications to the application, per client, but not to the source code. We resolved this in the core framework by programming to interfaces and using a Dependency Resolver (having an option to override the base registration) and MEF.
Now when it comes to views (the UI the client sees) the templates seem static and if the client wants to add a new field to the screen it seems they would need to modify the view itself.
The only two things that I can think of is modifying the search path of viewengine. This would allow a copy of the base and changes to it would be picked up. Not really liking this as it's a copy of the code.
The other way, what we are doing now, is that we create a class that is a container to other objects that output HTML. Basically we have a PageObject, LabelObject, InputObject..ect that we can call render on and output HTML. Since they are classes we can use the same methodology as for the rest of the application of giving slice in points. Going this route we really are not using the viewengine for rendering but just for combining all the partial views. Seems kind of clunky.
Is there a different way to accomplish this goal or a different viewengine that I can use to meet the goal of allowing customization for clients without touching the base view? I know HTML is not an object but seems there has to be something in between ASP.NET WebForms and ASP.NET MVC when dealing with HTML and allowing for customizations.
I would create a strongly typed partial view or template (DisplayTemplate or EditorTemplate based on requirements) whose #model is a collection of things that are rendered as inputs and labels. Allow the client to add/remove items from the persisted collection (i.e. in a database) and your problem is solved using the built in ViewEngine.

Design Patterns for C# Windows Forms

I'm writing a flashcard program and am running into an issue I always seem to face when writing this sort of Forms program.
I'll describe the program then the issue.
In this program, one main form controls almost all of the action. Depending on the user's input and form events, different buttons/controls may become enabled or disabled, text in various boxes may be populated, etc.
For example:
Some questions might be multiple choice and others require typed input.
The user inputs their answer and clicks a button -- if they get something wrong, they have the option to override the 'wrong answer' judgement and say it was really a different, correct variant.
Statistics regarding which questions were answered correctly are kept and used in the decision about what flash cards to show next.
Now the issue.
How do I best create a clean interaction between the "form" code (for example, handling the OK button's onclick command, and enabling or disabling various controls) and the "logic" code (underlying data stores, program logic that does not have immediate implications for display)? If it is all mixed together in the form object code it does not seem right.
Can anyone suggest a design pattern (especially one widely used) that manages this cleanly?
In case it is relevant I am thinking of something like this:
Object Model:
Class MyForm: the form itself.
Class FormController:
Child class of MyForm.
Instantiation requires an object of type MyForm.
FormController's job is to put its MyForm object into a particular "state," by enabling/disabling controls, displaying various text, etc.
FormController exposes a small set of public functions which deal with semantically high-level request for the form state (such as "DisplayNewQuestion(QuestionData d)")
Class Session: Contains all underlying persistent data or objects involving this session, including lists of possible questions, objects that select the next question from the list, etc.
Class Driver: Drives both the Session and FormController objects. For example, it would ask the Session object for a new question, and pass it to the FormController object to update the form.
The advantage to something like this is that icky form code and nice logic code are now completely separable. But is it worthwhile? Are there better or more common design patterns for this?
Thanks a ton!
I am always most comfortable with Model View Controller in this situation. The Shade Tree Developer wrote the most informed series I have ever read on the subject, see here
The jist of MVC is
Model contains the data to be displayed
View is your form and only has logic for displaying and informing of user interactions
Controller contains the glue to make it all happen, including the business logic.
The depenencies should be
Model doesnt know about the view or the controller
View knows about the model and knows how to extract data from it to display
Controller knows about the Model and the view, instansiates them both and wires them together.
The model raises an event when it changes, the view captures this event and refreshes its display accordingly.
The view raises an event when a user interaction occurs, the controller captures this event and performs the correct action for the interaction whether that be updating the model or saving or clearing or whatever.
The view should not write to the model itself
You will see a lot of code where the form creates the controller but imo this is wrong. It came about because of people trying to apply this pattern in asp.net webforms where you have no control over the lifecycle, the first thing that always got created was a view so you had no choice but to have this create your controller, however in winforms you are in control, so make it clean, have the controller create the view.
You might want to use the Model-View-Controller (MVC) design pattern, in which the "logic" is your controller and the "view" is your UI. The model is used to access and retrieve data from your data source (a SQL database for instance)
It is worthwhile to separate your logic from your UI, because it makes them more maintainable. For example, if you want to change your UI from a winform to a web page, you don't have to redo all your logic.
Also, it makes up for a really cleaner code. Using design patterns in general helps other programmers understand your code faster as well.

What pattern is this refactoring?

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.

How to apply the MVC pattern to GUI development

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 :]

Categories

Resources