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.
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 hope the title reflects what I'm really asking. It seems to me that when people undertake XAML based development whether to use MVVM is not even a question, rather an understood fact. Coming from a background of Winforms and Webforms, I found that we almost never used MVP (for example). It was well understood that the main reasons to go down the MVP path (other than being a purist) is higher level of unit testing, and the ability to share "view logic" with different UIs. As far as the later is concerned, it has never been a requirement in my projects. If anything we might have had several user controls for this purpose.
As far as unit testing, I never found it necessary to test my code behind because it did nothing more than handle UI events and act as a proxy (create instance of and bind) to my business layer. I can understand if people bypass the business layer and create instances of their favorite data access layer directly in the code behind, then apply business logic to it right there, where MVP would be a huge benefit. In my cause I always front the DAL with a BLL, so where is the real "win" here as far as unit testing?
Point being it was never automatic to use MVP. I am now looking at possibly using Sliverlight (for the first time) in a project and I feel like I'm going to be committing a sin if I don't use MVVM.
I know there are a slew of little things that are MVVM specific perhaps that were not a consideration before when I was making the "to MVP or not to MVP" decision. I've read about Blend support (I don't even have Blend), maybe some other important aspects? The bottom line is though, is MVVM really that much more important to Silverlight than MVP was to Webforms for example? Or are we riding the renaissance days of .NET development where patterns and best practices are taking center stage (sort of like Java).
We moved from Vb.Net winforms to C# and WPF/Silverlight under MVVM. It is definitely a change of pace from our adhock coding. I love being able to create multiple views to work with the same view model. Makes it easy to customize screens for our customers that want it without a whole lot of programming changes.
I found these posts in Stack Overflow that might answer your questions:
Benefits of MVVM over MVC
Why MVVM and what are it's core benefits?
MVVM Unique Benefits
Those have some good answers comparing MVP to MVVM.
Hope that helps.
**** Additionally **
If you were referring to Expression Blend, I used blend when I first learned xaml. Now that I know what I am doing in it, I rarely use it unless I need to do something complicated with animation or whatnot. I use visual studio for coding it since, from my experience, Blend is still cumbersome. Don't get me wrong, it's a great program and does animations great, but it's for designers, not coders really.
From my limited experience with WPF and MVVM, my opinion is this:
MVVM is a pattern, but is not the end-all-be-all of WPF. Especially in the case of MVVM "purists." There are times and places for event handlers and code behind, even in WPF. The benefit of the xaml development and MVVM is the separation of logic from design, but at times, you logic involves your design much more directly than MVVM allows.
I guess the main reason why MVVM is so advocated because of the power of DataBinding.
With web forms for example, you will need to create your own interfaces, framework etc... to implement MVP, whereas in Silverlight/WPF, databinding is just there, so whether or not you use it, it is up to you.
In my opinion, I think MVVM simply adds in a layer of testable view logic (ViewModel) instead of like the MVP pattern where your business logic can really be in the presenter itself.
In summary, if it is already there, easy to use, use it.. it is like you have a car, but u can still choose to walk 10miles to your nearest market, or you can drive (most would advocate you to drive).
Thats my 2 cents.
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
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've created a simple desktop application in C# 3.0 to learn some C#, wpf and .Net 3.5.
My application essentially reads data from a csv file and stores it in a SQL server CE database. I use sqlmetal to generate the ORM code for the database.
My first iteration of this app is ugly as hell and I'm in the process of refactoring it.
Which brings me to my question. How would you architect a desktop database app in C#?
What are the best practices?
Do you create a Database Abstraction Layer (DAL) which uses the sqlmetal generated code? Or is the generated code enough of an abstraction?
If you use DAL pattern, do you make it a singleton or a static member?
Do you use the View-Model-ModelView pattern with the DAL pattern?
Apologies if this seems like a long open ended question, but I have been giving this a lot of thought recently.
I see a lot of examples on how to architect an enterprise n-tier app in C# but not that many on architecting standalone desktop apps.
I would start with the Composite Application Guidance for WPF (cough PRISM cough) from Microsoft's P&P team. With the download comes a great reference application that is the starting point for most of my WPF development today.
The DotNetRocks crew just interviewed Glenn Block and Brian Noyes about this if you're interested in hearing more from them.
Even better, Prism is not nearly as heavy as the CAB was, if you're familiar at all with that from the WinForms days.
The answer is "it depends" as always.
A few things to think about:
You may want to make this fat client app a web app (for example) at some point. If so, you should be sure to keep separation between the business layer (and below) and the presentation. The simplest way to do this is to be sure all calls to the business logic go through an interface of some kind. A more complex way is to implement a full MVC setup.
Another thing you may consider is making the data access layer independent of the business logic and user interface. By this I mean that all calls from business logic into the DAL should be generic "get me this data" rather than "get me this data from SQL" or even worse "run this SQL statement". In this way, you can replace your DAL with one that accesses a different database, XML files, or even something icky like flat files.
In short, separation of concerns. This allows you to grow in the future by adding a different UI, segmenting all three areas into their own tier, or changing the relevant technology.
Before architecting anything you should define requirements for your app.
It's a common error of beginner developers - starting writing code ahead of thinking about how it would perform. My advice will be to try to describe some feature of you application. It will help you to feel how it should be implemented.
As for useful learning resources I would highly recommend you to take a look at CompositeWPF it's a project designed specifically to teach developers best practices of desktop app development.
I'd start with Jeremy Miller's Build Your Own Cab series.
I was an early CAB adopter. I learned a lot from digging into that technology and reading all the .NET blogs about application architecture.
But recently I had a chance to start a new project, and instead of using CAB I went with StructureMap & NHibernate and borrowed some of the patterns that Jeremy uses (in particular, his way of handling event aggregation). The result was a really simplified, hand-tooled framework that does everything I need and I love working with it.
As to the specifics of your question: I use a Repository for data access. I initially wrote some ADO.NET code and used data readers and mapped my objects. But that got old real fast, so I grabbed NHibernate and was really pleased. The repositories use NHibernate for data access, and my data access needs are pretty simple in this particular app.
I have a service layer (exposed via WCF, Duplex channels) that utilizes the repositories. My app is basically client-server with real time updating (and I know your question was just about clients, but I would use the same technologies and patterns). O
n the client side I utilize MVP with StructureMap for IoC and some very simple event aggregation strategies for cross-class communications. I code to interfaces for just about everything. The only other thing I did was borrow from the CAB the idea of a flexible "Workspace" for dynamically displaying views. I wrote my own Workspace interface though and implemented my own DeckWorkspace and TableWorkspace for use in my app (these were really simple things to write).
A lot of my decisions in this most recent application were the result of experience and pain I felt using other frameworks and tools. I made different decisions this time around. Maybe the only way to really understand how to architect an application is to feel the pain of doing it wrong beforehand.
I would say yes, it could easily be structured towards smaller applications. There is a learning curve towards getting started, but honestly, it helped me understand WPF better than attempting to start from scratch. After starting a project with CompositeWPF and then starting another project without it, I found myself attempting to duplicate features of CompositeWPF on my own because I missed those features! :)