How does one implement UI independent applications? - c#

What are the fundamental techniques to make most part of my C# source code UI independent?
For example, I would like to write my source code for Winforms desktop application which I shall be able to plug into asp.net web application or a WPF application with very minor changes. I.e. I shall be able to use the same source code irrespective of UI technology to make it future-proof.
I know CSLA framework can do that.
But if I don't use CSLA (it takes some time to learn a new framework and at present I don't have that much time to spend on it), what points should be taken care of to achieve this kind of ability in my C# code?
Can you give me an example? I already use Business Objects and layering technique in my applications. But even so I have seen that it needs a lot of coding to plug my code to new UI technologies.
Please do not provide me with any superficial answer.

The best way to do UI independent coding is to seperate the logic from the presentation. Take a look at the MVC pattern.
This is more of an discipline issue with your design rather than a framework issue. A framework can't not force you to design properly. It can make things easier for you if you design the app properly, however there are always ways around the enforcement of it.

To make your code UI independent, put the logic that is not dependent upon UI into a separate layer or assembly. Separate logic from presentation. It's what all the patterns like MVC, MVP, and MVVM follow. It's such a fundamental piece of software structure that it should be ingrained upon you; if it's not, make it so.
Separate logic from presentation. Learn it. Live it. Love it.
Edit:
Can you give me an example? I already use BO and layering technique in my applications. But even so I have seen that it needs a lot of coding to plug my code to new UI technologies.
Please do not provide me with any superficial answer.
I see that you have edited. Allow me to elaborate:
There's no getting away from some logic that is UI-dependent. UIs are not a shell; they still have logic and functionality. But that functionality should only be geared toward user interaction. Display data. Gather data. Fancy graphical tricks and animations, if your preferences lie in that direction.
The rest goes to the business layer, and that stuff can be reused. If you layer properly, you can avoid having to rewrite your core functionality every time you write the program for a new UI framework.
But you still have to rewrite the UI stuff.

If you're building a multi-tier application, your business logic, data access, etc should already be separated into classes that are completely independent of your UI. Repurposing those libraries for a different target platform - desktop vs web, etc - should be a simple matter of referencing your existing libraries from your new application.
This is a fundamental rule of software development. Although patterns and frameworks like MVC, etc enforce this more stringently, it's ultimately up to you to design your application correctly. This sort of task doesn't require learning a new technology - just common sense and a tiny bit of experience.

Check out Martin Fowler's excellent article on this topic.
GUI Architectures, Including MVC, MVP, MVPC

Take a look at the explanation of MVVM(Model-View-ViewModel) at MSDN Magazine. MVVM is widely used for WPF application development.

Related

Convert .NET application into Test driven application

I have an old WinForm application written in .NET 2.0. The application doesn't follow any pattern or layer pattern. My client now want to introduce unit testing Framework. As it is live application so it very risky to re-write the whole code again. What approach should i follow ?
Thanks in Advance
There's a book I've seen recommended often on this exact subject, I haven't read it but it seems appropriate for your problem, though I don't know if the fact that it's WinForms complicates this or not.
"Working Effectively with Legacy Code"
http://books.google.ie/books?id=CQlRAAAAMAAJ&q=dealing+with+legacy+code&dq=dealing+with+legacy+code&hl=en&ei=LnVXTrviCtSu8QPEwei0DA&sa=X&oi=book_result&ct=result&resnum=1&ved=0CC0Q6AEwAA
In WinForms it's really hard to unit test because the code behind is linked tightly to the GUI itself. Some automation tests will probably be the best you can get on a WinForms application without going out of your way to change the program.
If your client want a testable solution, I would suggest making it in WPF and use a MVVM framework like Caliburn.Micro that emphasizes unit testing.
Unfortunately, that means rewriting the entire application.
Short answer
Either rewrite application, or don't bother to much with the unit tests.
Since WinForms applications typically have a UI that is strongly coupled with the underlying "data model", some form of automated UI testing is probably your best bet - i.e. an external application emulates user's clicks and other interactions with the UI and checks whether your program is in expected state after that.
You may want to take a look at:
http://smartbear.com/products/qa-tools/automated-testing/supported-testing-types/functional-testing/
To do just the UI tests (since its a .net based) you could use .Net light weight Test automation feature. Details here http://msdn.microsoft.com/en-us/magazine/cc163864.aspx
You dont have to use an external tool for automating it. But again, to test the underlying layers or business logic you have to extend the test cases.
I would recommend you move the most critical parts to normal C# classes and unit test those. And then only do UI testing on the complicated parts of the GUI. I have worked on a legacy project but with ASP.NET Webforms instead of Windows Forms and what I noticed is that some parts of the system changed often and were good candidates for refactoring and unit testing while other parts never ever changed and just were not worth the effort of testing.
If this is a large project then this could take a long time. A huge part of the work is making the code testable and introducing some sort of MVP (Model-View-Presenter) pattern to be able to separate the GUI code from the business logic.
I would highly recommend Working Effectively with Legacy Code as recommended by Eoin Carroll. It describes techniques to work with legacy code and also provides motivation (you could be in for some tough times) by showing that it can be done.
Also take a look at these two StackOverflow questions(here and here) for discussions on WinForms and MVP.
That depends on what you want to test, and how the app is written.
GUI is hard to test, but check out some of the other answers. If, as I suspect, you just want to test the business layer, that's easier:
If the app has the business and GUI decoupled, then you can easily use NUnit, either by integrating it into the project from your IDE, or in NUnit's own way, then write tests to cover what functionality the business layer exposes to the GUI.
If the app isn't decoupled, and you have a lot of the logic in the GUI, then you really need to refactor and decouple. Without doing this you will be restricted to testing via the GUI, which is difficult and not really full-proof, and it means trivial changes to the GUI may invalidate your testing of the business logic.

Tips on designing a .Net framework application

Can you please provide me with some tips/guidelines when architecting, designing and implementing a .net framework application, with the requirements given below:
It will be an analytical tool which will retrieve data from files, sql databases and may be cubes. So data layer should be able to handle that. The middleware should be totally independent of the other layers so probably need an IoC container (which one would you recommend)
It will be deployed on the local intranet
The front layer might be WPF application or Silverlight in future (for now, I am concentrating on Silverlight but the point is that it will change)
It should be easy to customise and improve it in the future without changing much of the code as the framework will be deployed for many clients
I need a way to store the configuration information, which will be picked up by the application on application load events to set its feel and look.
I have two months to implement it and looking for as many tips as possible.
SoC for a start
break your application into several assemblies that use IoC (interfaces + implementations):
application model assembly - all other assemblies will reference this one because these classes will be used for inter-communication - they will mostly be just POCOs
presentation assembly - references app model and business services - this one is either WPF or Silverlight in any case use MVVM to make your testing life easier
business services assembly - references app model and data repositories assembly
data repositories - these define repositories that actually get data from the stores
Then I'd create three additional ones:
file data providers
database providers
cube providers
Data repositories would reference all three and use them to provide necessary data.
If configuration becomes very complex with a lot of functionality then you should put it in a separate assembly as well and reference it by business services assembly.
Which MVVM library to use
Since you mentioned time I suppose you'll have hard time catching your deadline. When using MVVM (which I suggested to use) I also suggest you don't use a full blown PRISM (a.k.a. Composite Application Guidance from P&P) but rather go with MVVM Light Toolkit. It will take you less time to get on the bandwagon.
Code generation
In places where appropriate I suggest you use T4 to its full potential. I use it to import stored procedure calls to avoid using magic strings when calling stored procedures (and using their parameters). Check my blog post about it as well.
DAL technology/library
Don't write your own data access code using things like SqlConnection/SqlConnection functionality. There're many data access layer libraries/technologies today that you can use and not reinvent the wheel. If you know nHibernate, then use that. If you know EF, then use that. If you know anything else, use that. Anything that will provide/generate as much code for you as possible that is already tested and debugged.
So it all boils down to:
DRY + YAGNI
a.k.a. Don't repeat yourself and You ain't gonna need it = don't over-engineer you code.
Agile developers are supposed to be lazy
They should develop just as much as it's needed and no more! TDD implicitly provides this process by the red => green => refactor steps.
I would recommend using MVVM and Test Driven Development. The MVVM will give you good separation between the front and middleware, and the TDD will help control the chaos that comes with any nontrivial app development.
Have a look at the Composite Application Guidance from Microsoft's Patterns and Practices group, it may not match what you are doing exactly but will give you some good ideas.
From an architectural standpoint, I highly recommend taking a look at the Microsoft Application Architecture Guide. Since you are already using the Microsoft technology stack, I would consider using Microsoft Unity for IoC. You indicated that your presentation layer might use WPF or Silverlight, so take a look at using Windows Communication Foundation, as you will be somewhat constrained in Silverlight when it comes to communication with your data layer.

What's are the best readings to start using WPF instead of WinForms?

Keeping in mind what CannibalSmith once said - "All the answers are saying "WPF is different". That's a huge understatement. You not only have to learn lots of new stuff - you must forget everything you've learned from Forms. It's a completely new way of doing UI."
.. and having many years of experience with visual Windows desktop applications development (VB6, Borland C++ Builder VCL, WinForms) (which is hard to forget), how do I quickly move to developing to say well-formed WPF applications with Visual Studio?
I don't need boozy-woozy graphics to give my app look and feel of a Hollywood blockbuster or a million dollar pyjamas. I always loved tidiness of standard Windows common controls and UI design guidelines, end even more I enjoyed them under Vista Glass Aero Graphite sauce.
I am perfectly satisfied with WinForms but I want to my applications to be built of the most efficient and up-to-date standard technologies and architectured according to the most efficient and flexible patterns of today and tomorrow, leveraging interface-based integration and functionality reuse and to take all advantages of modern hardware and APIs to maximize performance, usability, reliability, maintainability, extensibility, etc.
I very much like the idea of separating view, logic and data, letting a view to take all advantages of the platform (may it run as a web browser applet on a thin client or as a desktop application on a PC with a latest GPU), letting logic be reused, parallelized and seamlessly evolve, storing data in a well structured format in a right place.
But... while moving from VB6 to Borland C++ Builder was very easy (no books/tutorials needed to turn it on and start working) (assuming I already knew C++), moving from BCB to WinForms was the same seamless, it does not seem any obvious to me how to do with WPF.
So how do I best convert myself from a WinForms developer into a right-way thinking and doing WPF developer?
Read this questions:
How to begin WPF development?
Is there a WPF Cheat Sheet outhere?
Learning MVVM for WPF
Learning WPF and MVVM - best approach for learning from scratch
MVVM: Tutorial from start to finish?
Download and work through this Microsoft tutorial: Southridge Hands-on-Lab
Check this videos:
Mike Taulty's series of videos
Jason Dolinger on Model-View-ViewModel
And after that, take a look at StackOverflow questions tagged with both wpf and mvvm
Keep in mind that MVVM seems suited only to single window applications.
I dived into WPF based on inexperience and general recommendations that it would suite better a kiosk project, especially one where the customer has given me photoshop images of all the application screens. Having cool graphics was a requirement for this project and I liked the vague resemblance of WPF with web development.
I found out a few downsides
1) there is no such thing as an official MVVM toolkit. There are a lot of them, all backed by an individual. A shot at a toolkit by Microsoft has been put on the back burner one year ago and there is no VS2010 support.
2) programming a multi windows application, sort of a simple wizard with back and forward, is plain nightmare. I got out of this with a clean design defining a delegate for each UI action and a command for each business action, but still I think it is too much involvement with a framework to be justified, and you cannot show the result of your tests to this customer expecting excitement.
3) You give up the habit of double clicking a button and adding some code. This leaves a nagging feeling of using the IDE against its nature. Basically you use Visual Studio as a text editor and an interface designer, still with a great help from the tool.
The upsides, so far are:
1) defining visual components is very flexible, fast and easy and you can choose between VS and Expression Blend. Animations are simple to create.
2) data binding simplifies the application. You define a DataContext and bindings and do not have to move data from the business logic to the interface yourself, as long as you have a property for everything that must be displayed.
3) You can reduce the amount of business logic in the interface to zero. It is easy to separate the application behaviour from its looks, so you can skin your interface in ten different ways with little effort and test all of your logic without opening a window.
4) you leave a door open to going with Silverlight if they ask you.
My conclusion is that if you have an MDI application in mind you might find yourself in big trouble. You should be aware that, if you choose WPF, you are ploughing ground for future generations rather than getting on a train that will get you there fast and easy. There is no established way to do things, especially those that are not covered by demos.
Toolkits, all things considered, are not so important and each of them will serve you well. In fact a couple supporting classes are enough to start and there are no fancy wizards, it is up to you to follow conventions.
You might even make your own if a few hours, once you understand what is involved in the logic. The downside is that you will have to really understand it well to bend the application your own way.
As I said above, I had to learn a lot just to show a new view when they click a button keeping the code clean. Take the time to see the videos cited elsewere on StackOverflow it will save you time.
if you are looking for books just look at this previous post
What WPF books would you recommend?
Having got into WPF this year, the most important thing for me was learning how to use the Model View View-Model pattern for separating the view from the app logic. As a general rule of thumb if you find you are placing a lot of code in the code behind for your view then you are "doing it wrong".
I found that coming from a WinForms background I was putting in lots of event handlers and doing stuff in my code behind. As I became familiar with MVVM and WPF features I found I was able to remove the bulk of my code behind and replace it with views binding to view-models.
It was articles like this one from Josh Smith that helped get me started on the MVVM path:
http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx
Once you have started to get the hang of displaying data view MVVM bindings, have a look at commands and specifically the ICommand interface. They are the main mechanism by which actions from the user triggers operations to execute. So rather than having a OnClick handler for buttons, you bind the Command property of the button in XAML to a property in your view-model that exposes an ICommand implementation.
My 2c - Donovan
Try this smashing hit.
Windows Presentation Foundation - Unleashed By Adam Nathan
(source: adamnathan.net)

Convert an ASP.NET application to a Silverlight application

I'm developing an three layer ASP.NET application with C# and Visual Studio 2008 SP1. I'm using WebForms.
I'm wondering to convert that application to a Silverlight application. Maybe I can reuse a lot of code of ASP.NET layer.
What do you think about?
Assuming you have the typical presentation, business logic, and data layers, and also assuming that you have separated your code diligently into these layers, you should be able to replace your Web Forms with a Silverlight interface and leave your BL and DAL intact.
Real projects tend to be somewhat messy, however, making such a transition more difficult. If you're using SqlDataSource you might have problems.
Those are some good points #Andy, and to expand on what he said:
i'm doing that very same thing right now. Because i have a rather comprehensive business layer, i have been able to do a lot of work (a couple of weeks worth), and in that time i have only had to add one function to that business layer. This is important because it reduces the amount of testing required. It also makes any remaining testing easier as it is easier to compare the output of the old version of the application with the new version.
One pattern that really helped to achieve this was the facade pattern. I built a WCF layer that sits over top of the business layer, and by using the facade pattern i can return results that are more suitable for the new silverlight interface, without interfering with the business layer.
It is most likely though that your new UI will have a drastically different architecture than the ASP.NET version. You will be able to achieve a far cleaner separation between UI, code and data. Some of the ASP.NET code that i was quite proud of looks positively mangy next to the equivalent silverlight code. Be prepared to chop your old code up, and eliminate those business rules from the immediate code behind :)
If you're goal is simply to replicate the UI behaviour as delivered by ASP.NET then yes assuming good partitioning you could re-use quite a bit of code. You'd have ask why you would want to do that though.
On the other hand if the goal is to provide a much richer interactive experience to the user then its likely that you'll find even a well designed business layer just doesn't behave the way such a radically different UI needs it to.

Component reuse between ASP.NET and C#.NET

This might seem like a ridiculous question since I'm quite inexperienced in .NET.
Is it possible to build components in C#, using .NET, which can be reused in ASP.NET. For example if one would like to port an application onto the web.
If possible, how portable are they? I.e. can GUI be reused in some extent? Is there an intermediate format to use as base or is it required to use C# components as binaries?
Thanks.
Edit:
Thanks for your input! I'm quite familiar with the design aspects of this problem, i.e. how to model components for reuse. However you made me realize that the question really is about - To what extent is .NET reusable between ASP and Windows? Can one say that certain packages of .NET components are independent of environment and some are platform specific?
Absolutely - a .NET class can be used in any kind of .NET application. However, it kind of depends on what part of the application you're talking about.
Generally, Windows Forms user interfaces are NOT reusable as ASP.NET user interfaces, because the design constraints are so different (i.e. web browsers only support a small number of controls, often use flow (not grid) layout, etc. Similarly, the events are different (a web form button isn't the same as a windows form button, etc.).
What you can reuse easily, though, if you do things correctly, is the business logic. Design your classes so that they don't internally know anything about whether it's a windows form or a web form (or a console application, or web service, etc.). That is, the classes should be pure implementations of your business logic. Then you can use those classes in any context you want to.
The short answer to your question is yes - simply separate out the code you want to share between the two views into a interface-independent class, preferably in a separate assembly, and include that assembly.
The long answer is more complicated - the ability to do this will vary between application and application. You'll be able to separate out less code for UI intensive applications that don't do much behind the scenes (such as, say, some sort of graphics game), than you will for a very simple UI application that does a lot behind the scenes (say, a UI that consists of a single button that then kicks off a complex data manipulation process).
In the end - .NET provides the ability for you to do this. Your actual ability to do this will be very dependent on your own design abilities and your particular requirements. There's a lot of writing available on this subject - I suggest starting by taking a look at Design Patterns (though the original book writes examples in C++, I believe that someone has done a book with examples in C#. I cannot, however, speak to the quality of it.)
I've never done it before, but i guess you can place the common code on a separated class. UI will need to be duplicated as windows forms and asp.net have completely difference programming approaches.

Categories

Resources