I have never used MVC before and would like some advice.
I have actually already written quite a bit of code, but looking at it, it seems to be quite highly coupled between classes and there is a lot of code written on the actual main form of the winform. I am a University student, recently started on a 12 month placement, so do not have much real world experience.
My system is effectively a WinForm GUI that has, amongst other things, a treeview that is popualted at load via an event. And then when the user clicks on a node, it gets a datagridview from a dllplugin (which obtains the data from an Oracle DB via a perl script.
My question, is would MVC apply in this circumstance, and would anybody have any good advice/resources on how I can now, post-design to implement it?
Thanks.
The MVP pattern is more adapted to WinForms applications. Here's a nice article you may take a look at.
Received wisdom is that MVC is good for the web but has some constraints when operating in a desktop environment (I'm not sufficiently experienced in applying this sort of pattern in either context to make a worthwhile judgement).
The pattern that Microsoft (for one) are pushing for forms use is MVVM - which is Model View View Model - and it provides a similar set of benefits in terms of separation and testability. Even allowing that I could wish I knew more I can see what and why, especially if you're looking at WPF (and Silverlight) but in any context where you're trying to ensure separation.
The MVC pattern can work well with WinForms, see this question.
There are lot of related pattern to choose from; in the case of WinForms (unlike WPF) there is no clear winner.
Partly this is due to everyone having different aims, do you care most about:
Code reuse between Forms in the UI
Being able to support form the one UI system
Easy unit testing
Etc
Related
I'm developing WinForms application. By far I've finished about 50% percent of it.
Is there anyway I can convert it into a Web Application without rewriting the whole GUI?
If there is non, in what platform should I use instead (rewriting my project) for having easily both Web and Windows UI?
Is there anything new in this subject in the last 3 years?
I know of course WPF and Silverlight are quite alike, but I'm not sure this is the bust solution.
This will be dependant on how you have constructed your architecture. The main reason WPF and Silverlight are interchangeable are because they tend to use MVVM patterns and architecture (also things like PRISM)
http://msdn.microsoft.com/en-us/library/ff921075(v=pandp.20).aspx
In theory if you follow the pattern you can drop the front whenever you like and and design it using something completetly different. This is known as:
Making your UI loosely coupled.
If you wanted to switch your front end display to a web application you would obviously have to change the UI layer to use HTML, in theory if you have given your application a suitable architecture your business logic should be able to remain the same, however if you have a lot of logic tied into the multiple Windows Forms i'm afraid you will suffer a long and painful migration process with many bugs along the way.
Think of your application as a house - you have the main foundations for the house (insulation, bricks etc.) which you may want to change from time to time to bring the structure up to date, however the fundamental foundations will normally remain the same. You can however decorate the house with however you wish without affecting the fundamentals (sorry for a poor analogy).
Hope this helps somewhat.
EDIT:
I just noticed you wanted to know the best architecture to use with a project, personally from what I know I would use PRISM, WPF and MVVM - you can Build WPF and Silverlight Applications with a Single Code Base Using Prism
I am pretty new to WPF and I have an discussion this morning with my architect who is from C,C++ background.
We are trying to create a video calling application which depends on native dlls by making PInvoke. The WPF application is mainly the UI and in code behind we are making Pinvoke Calls for Video /Audio and listing the available drivers.
So If we are talking Data as from database then there is not much of the "Data" involved in our application.
The WPF application we are trying to modify is Boghe and surprisingly they too are not using MVVM.
While I am keen on implementing MVVM the architect points it as unnecessarily splitting the files in to 3 parts.
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Though I have theoretical answers but can't help but agreeing to his point. Is he actually right?
He says if we want to change any thing in the view like changing a button or any control then it can be directly done in code behind. Why then use MVVM?
Of course it can be done this way. The question is whether it should be done this way.
For a fairly small code base, you can probably get away with mixing up data access, core logic, and UI manipulation in code behind. In the long run however, that will not make for maintainable or testable code, and the mess is likely to get worse over time and turn into spaghetti code. Take my word for it, because a good portion of my time at work is put into reversing such old messes.
Some consequences of mixing everything up in code-behind are:
Code that fundamentally violates the "Single Responsibility Principle" (SRP).
Code that's hard to understand because it does very different things all in the same place.
Code that breaks easily. I change something here and for some arcane reason, some feature breaks over there.
Code duplication / violation of the "Don't Repeat Yourself" (DRY) principle. You often find the same logic in several places. Is this accidental, or on purpose? If I change logic here, must the same/similar logic over there be changed too?
Note that with the exception of the first point, these are not theoretical concerns, but very real, immediate problems of your typical "legacy" code base.
In my opinion, it's not entirely correct to say that MVVM introduces more code-behind classes. This is clearly a statement from someone who does not appreciate the fundamental separation of concerns that comes when you isolate the data, business logic, and UI logical layers from one another: Even with MVVM you have only one code-behind class for your views. The other two classes (yes, there will likely be two more) simply can't be considered "code-behind" because they aren't directly tied to the view / designer.
Short Answer: No!
ViewModels are not the same as Codebehind in different files.
With a proper MVVM implementation, you do not have a codebehind, or at least
a very small one.
But in the ViewModel you do not have direct access to the window, as in MVVM
the communication between ViewModel and View is done over Binding, there is
no direct reference to a View (normally).
MVVM brings in some enormous advantages over view centric approaches.
It is testable, it is far easier changeable, it is an adapter, ...
edit
And if he really is your software architect, he should know better...
at least thats what I expected from a software architect
I too agree with stakx and Mare Infinitus; MVVM provides a lot of benefits and is not just creation of multiple code behind files.
From my experience MVVM is the best way to learn and use the power of WPF, it kind of encourages and forces you to use WPF features like Binding, Commands, Styles, Converters etc. I have seen application's being developed without MVVM and they turned out to be WPF application in Winforms style having problems stakx mentioned (and more).
Apart from UnitTesting(which I think is very imp. in your application), re-usability etc. one very important benefit of using MVVM is that it can support multiple views, i.e. you can have multiple UI's for your application all of them can use same ViewModels; This may not be a requirement for you today but you may require to have a new interface few years down the line or support other platforms like Silverlight or Metro in future, MVVM will save you a lot of effort in that case.
I would suggest you to go through this post which explains real benefits of MVVM and explains other so called benefits (although I feel they are real benefits in practice) - MVVM Backlash
one purpose is that you can unittest your view logic(viewmodel) without the view.
here one nice comment from Rachel regarding viewmodel first approach:
Remember, with MVVM your ViewModels are your application. The View is
just a pretty interface that allows users to interact with your
ViewModels.
If you have only two people in the project, and everyone's all-in-one person, he's right.
But if you do not want designers messing up the controller (or ViewModel), or programmer that changes view to something, you know, as programmers do design.
In addition, You have the clue where to do changes immediately, without searching enormous text files.
Also, the separation by MVVM or MVC is one of basic principles of programming, it's Data-Logic-View separation, and if architect says you not to do it, may be it's time to ask another architect :)
I have been hearing a lot of hype about MVVM for WPF. When do we use it? Is it a use for everything or does it only have specific uses? Is it worth it for every project?
It can be useful in any project, but I find it particularly helpful in situations where providing a clear separation between business logic, interaction logic, and user interface is required (large applications or applications involving multiple developers/designers).
Model = Business Logic
Contains the model of whatever business process/object I am working with.
ViewModel = Interaction Logic
All the code that controls how the model is accessed and modified (e.g. edit/undo functionality, lazy loading, etc.)
View = User Interface
The interface (defined in XAML) that the user interacts with. I try to minimize the use of code-behind in this layer, pushing that into Attached Properties or the ViewModel.
There are doubtless many other uses for MVVM, but this particular scenario is the one I have found to be the most useful in my own WPF development experience.
I've found it useful even in relatively small projects, if I'm making a lot of use of databinding and an object data model / models.
In terms of WPF and Silverlight?
In theory for everything - every non-trivial project (and possibly even then). Its part of a wider process (it creates separation of concerns and allows for testing and other nice things). Basically if you're going to do it (and I think you probably want to, I certainly intend to with new projects) then you should do it pretty much across the board.
If you haven't already, go watch the video linked from here: http://blog.lab49.com/archives/2650 - I found it very helpful in getting my ideas straight.
Better to ask: when shouldn't you use it? The most obvious example is when data binding isn't appropriate and you have to manipulate elements of the view directly in code - if, for instance, your application needs to update the visual state of hundreds or thousands of visual elements in real time you may not be able to afford the overhead of data binding.
Every time I start on a simple project and think "this is so simple, MVVM would be overkill", approximately 8 hours later I get to a point where I realise that using MVVM would make things much simpler.
So I'd say most of the time using MVVM will actually simplify your UI logic, even if you initially think it will be overkill. Projects have a habit of getting more complex over time, and the separation of business logic and view logic enforced by MVVM enables the project to grow in a far more controlled way than having you business and UI logic all mixed in together.
I'm currently working on a large project, where we implement mvvm, CAL (Composite application guidance) in Silverlight. Of course, level of separation of concerns is very high.. but
1) the code gets too robust.
2) MVVM looks great for small projects ( all these hello-world samples all over the internet), but it reduces your oppportunities: For example, Routed events (great instrument) are still EVENTS, but, as you know, it's strictly forbidden to use them directly, as soon as this is code-behind) if you want to follow mvvm.
3) Command Binding STILL doesn work properly in Silverlight(.net4.0, vs2010). It's a long story, just keep that surprise in mind, when your CanExecute delegate will not fire at app start.
A good answer to your question is "MVVM is good for projects with simple UI logic".
Thanks, Ilya.
I have started a WinForms project a few weeks ago and as I did not really know what features I wanted, I just added them along the way. This now caused a horrible mess where my MainForm is a big ball of mud and where for example some important state changes are triggered by UI elements to the point I have to call the OnChange Event of a Control in order to change some state in the database.
In short: I've just started a new project where I want to take a better approach. I just don't know which would be the "good" one. In ASP.net MVC, I found the MVVM Pattern really useful, but on the Desktop, MVVM seems to be only intended for WPF, not for WinForms.
The other approach is a three-tier-architecture: I have my Database-Class which currently talks directly to the UI. I now create a new Static Class ("ApplicationState") that talks to the database and fires events to tell the UI "Hey, Something changed!". The UI would manipulate the State which will then handle the database persistence and again raise Events if the UI needs updating. The point here is that the ApplicationState class never modifies the UI directly, but that the UI subscribes to Events. That looks like a clean/"MVC-y" way of doing it, but maybe I am overlooking something here?
Basically my ultimate goal would be to have the UI completely independent from the database layer just to make sure I don't wire in business logic into the UI again.
Don't throw in the towel on MVVM - it's valid for WinForms as well. Basically, if you use data-binding, you have to make a decision about what your objects will bind to. Often, especially for more complex UI, you dont want to bind directly to your domain objects, you want to build specialized classes (sometimes wrappers) that your UI can bind to which provide everything the view needs (the essence of MVVM) and the technique works just as well with Winforms.
A good series on WinForms Model-View-Presenter approach can be found at
The Build Your Own CAB Series Table of Contents
What I would always go for (first) is to have a layered application
Presentation Layer (JUST UI and databinding logic)
Interface Layer to the Business Layer (defining the contracts for accessing the BL)
Business Layer implementation (the actual logic, data validation etc...)
Interface Layer to the Data Access Layer (defining the contracts for accessing the DAL)
Data Access Layer implementation
This organizes your application extremely well. Then I'd look for some MVC kind approach. I did not develop so much with WinForms, more with Asp.net and some Java Desktop clients (where I used MVC). WinForms works more with the .Net databinding approach (DataSource, DataMember,...). You should go for that approach instead of trying to force something other. I found that it doesn't match that well.
What's always useful is to lay out our UI logic into different controls (like UserControls in Asp.net). This facilitates reuse.
NDepend documentation comes with some pretty cool and advanced online blog posts, articles and white books concerning architecture of .NET code.
Advices on partitioning code through .NET assemblies
Control Components Dependencies to gain Clean Architecture
Re-factoring, Re-Structuring and the cost of Levelizing
Evolutionary Design and Acyclic componentization
Layering, the Level metric and the Discourse of Method
Fighting Fabricated Complexity
Also, if you want to continuously check that your UI code is independent from your database code, you can write easily some Code Query Language rules that will be checked live at development time in Visual Studio:
Keep your code structure clean
Just start writing unit-tests for everything you can think of. As some pieces will turnout difficult to unit-test because of tight coupling to the WinForms, separate them out. Clean. Wash. Repeat.
Nido framework is good. However it is just for your back-end architecture. It will give you a solid, flexible, and simpler back-end with t4template. It prove to be having a very good architectural pattern. Furthermore it can plug not just with WinForm but with any other (MVC ASP.NET etc) front-end too..
Then again RocketFramework is also good
Link1: http://rocketframework.codeplex.com
Link2: http://nidoframework.codeplex.com
Our rule of thumb is to lean towards MVC for most websites due to the stateless nature of the web. Unless you're trying to provide a very rich web experience and bring in silverlight, then you should go with MVVM. XAML goes hand to hand with MVVM and can be your smart client choice as well (or a nice MVCP pattern).
True MVC is almost impossible to uphold in any other circumstance due to the fact that controllers are suppose to handle all input. Most non web architecture has controls that will provide this for you. In fact, most say that ASP.NET MVC is a hybrid MVC anyways but it's very good in my experience.
Okay,
I found some nice answers above but as per my 4+ years of experience in winform, I can say that you can use dotnet remoting for this purpose. In simple words, you need to create one solution for your business logic and client side works and another solution for connection with the database which you can called as a server. Both solution should contain some common projects and then you can easily works on your application without worry about your database.
I would suggest you to read about dotnet remoting.
Hope, this answer is helpful.
I have to develop a basic "line of business" application with the usual functionality like orders, stock control, sales, reports, etc.
I will use WPF to develop this application to run on Windows but I want to develop it "open" so I can do a Windows Forms application using the same structure (maybe to run over Mono) or even a Silverlight module. Can someone that did something like that (and survived) give me a sugestion on a guideline or something like that where I can find good practices? I'm a Delphi developer with some intermediate knowledge on C# but there are so many "amazing" libraries, frameworks and patterns that I'm a little lost on what would be good for that project.
Something like: Use EF (maybe wait for ef4?) or nHibernate, or ADO.NET, and expose your data using WCF, or webservices, or forget Mono because of the flexibility loss, etc. Can someone give me a tip on how you would do it? If someone has a bad experience in this type of project, it would be nice to hear from you as well. There is a lot of learning in the wrong decisions too :)
Mono doesn't implement WPF, it's not even on the roadmap. I'm not sure about Entity Framework...
You could probably do it in Silverlight (which has an open source implementation), but it's not ideal for creating desktop (although it is possible since Silverlight 3)
Where do I start?
First, from your description, you're in over your head.
Second, you're trying to pick a technology stack when everything is new to you.
In the best situation, I'd recommend a good training class in a few of the technologies you mentioned so you get a better understanding of them. I'd also recommend a mentor, someone who's done this before.
Reality though, may not allow for training or a mentor. In that case I'd recommend writing several real-life throw away programs. Take one piece of business functionality and try to write it in a few of the technologies you mentioned. If one feels better, and gives you what you want DECISION MADE! Don't stop with the first one that seems to work, try some more.
You should also listen to some good podcasts. I recommend Dot Net Rocks for a good grasp of the technology. The earlier podcasts for this site were also a very good source for some design discussions StackOverflow podcast
Best of luck.
I had to do something very similar recently in WPF. I have an ASP.NET background, but I have never worked with WPF (or WinForms for that matter), and it had me stumped for a while, but the longer I have been working on it (about 3 weeks now), the easier it has gotten. I really just searched Stack Overflow and Google for code snippets similar to what I was doing, and worked through them and changed them as needed. My company bought a book that helped me out as well (It was WPF Unleashed published by Sams), and it was pretty good. I do wish you luck on your first WPF app.
If you separate the business model and business logic from the user interface,
using MVC (Model View Controller) or MVVM (Model View View-Model) or a simular design pattern,
then you can have multiple user interfaces connected to the same business model + business logic and even connect the same user interface to other business models + business logic.
Thank you all for your suport... Brad, I'm already following your advices, doing some test cases to see what looks good... my problem is that altough I can develop an application in WPF and have a intermediate understanding in using the wpf databindings, generics, linq, anonymous objects, all the cool stuff, I always hear about this and that as the solution for all the worlds problems (like mvvm, or parallel programming, or functional languages, etc) and makes me feel "wrong" in my decisions and a bad developer if I do not use any of this nice technologies. I know the concepts but do not dominate it, and seems a lot of things to learn, sadly I do not have that much time.
Thomas, exactly because mono do not support WPF i want to make the application as isolated as i can, so I can do a simple winform layer to manipulate the data.
darthnosaj, thank you, I'm doing that too, searching internet and found much information (and this nice site full of hellpful people :) )
And Danny, thats what i think i need... will take a look on some sample applications using mvvm and see if that works for me. For what i heard is almost a crime not to use in that case in wich I want that kind of isolation.
Again, thanks all :)
I would suggest you keep your application N-Tier. Make all the entities, data adapter, and business logic separated from the actual desktop application. This way you can use WPF on the Windows platform and use Mono/GTK# on the Linux/Mac platforms.
You will only need to write duplicate code to support the actual GUI application functionality, while your code from the separate entity/data access/business logic library (e.g. DLL/class library) can be used in both your WPF and Mono/GTK# projects. Just add the DLL as a reference to the WPF and Mono/GTK# projects.
There is a good video from Channel 9 on building N-Tier applications
There is also MSDN documentation and guidelines on building N-Tier applications