WPF & silverlight development process - wpf

What would be the application development process for WPF applications and silverlight application?
Like how many tiers the application is divided into and how they communicate with each other. And what steps are followed during development like design , then business logic layer.
How the data base is accessed can Linq be used or data sets are better option?

I would suggest that you start out using the WPF Application Framework. Your "tiers" should be something along the lines of:
Business "Model" logic (database, LinqToSQL/EntityFramework is great with WPF)
Your "View" which is your WPF/Silverlight controls
Your "ViewModel" which binds the Logic to your View, passing change notifications anduser interactions.
I would do these steps in order. Assuming step 1 is mostly complete since it's not really unique to WPF/Silverlight, make an interesting UI but don't tie it to your model quite yet. Then study up on ViewModels. ViewModels, strictly bound and not accessed in code behind, will give you the best results.
If you're already familiar with C#/.NET, I would also strongly suggest you check out this excellent screencast showing you how to retrofit an application to following the "Model, View, ViewModel" architecture.

The process would be the same as for any other application; that is, design an architecture to suit your requirements! However, within your actual WPF/Silverlight code, you might want to look at the Model-View-Viewmodel architecture.
MVVM is a pattern that is typically used to structure the code behind a WPF UI, though it doesn't dictate how you access your data or define your business logic. The MVVM code would sit on top of your business/data code and provide an abstraction that's suitable for the UI to work with.

This question isn't really about WPF or Silverlight as they are just UIs. The architecture isn't dictated by whether you use Silverlight, WPF or something else.
For example (and not limited to this scenario), if you are using a classic n-tier architecture, you could continue to do so while using a Silverlight front end.

Related

How to design a data model to be usable across different application frameworks?

I have a WPF GUI application based on MVVM design and data binding. Now, I want to reuse the core code (i.e. the data model) in a Windows service, or a console UI app, or a WinForms app.
Is such a design reasonable? If yes, what are the pitfalls?
Or should I make a standalone data model instead, and interface WPF via wrappers?
UPDATE:
Sorry, I should have been more precise. Let me clarify: I don't doubt the very modularity thing =) My concern boils down to having my current DataModel implement INotifyPropertyChanged, use DispatcherTimers, etc. -- all that non-GUI but still WPF stuff. The model's business logic is based on it.
Is this (non-GUI WPF) design acceptable for reuse in the aforementioned cases, or should I abstract further, until no references to WPF would be required at all?
Yes, this is perfectly acceptable and most of the time it is desired!
When you build an MVVM app, it should be in at least 3 formal layers:
Presentation WPF, UI, xaml, behaviors. All that stuff. Not reusable
Application The view models and structure that supports your application rules. All that stuff. Not intended for reuse
Foundation Database access, business objects. Domain specific algorithms. Ideally this bit should be reusable anywhere
The foundation layer is the clever bit. This is where the meat in your application sandwich is. It makes perfect sense for this to be totally agnostic of UI technology. WPF, winforms, ASP. It shouldn't even need a UI.
Edit for question update:
Removing all references to WPF is hard because sometimes you need a CollectionViewSource on your view models for grouping/filtering of results. That is a WPF class.
It is very tempting to view your seperation-of-concerns as 'just dont reference wpf' and that helps but it can make life difficult. Instead, try to be disciplined with the type of behaviors you are putting in. If you find yourself writing 'clever' (domain) code on a view model, shift it to the foundation layer as a business object method or extension. Similarly, if you find yourself implementing IValueConverter often, perhaps you should make better use of view models.
One thing is for sure, your foundation layer should never, ever, ever reference WPF.
Such a design is very reasonable! You can create a portable C# library for all .NET technologies including WPF, WinRT, ASP MVC, etc which can contain your models. Obviously you'll need to wrap these portable models into a viewmodel anyway, but IPropertyChanged is implemented in all XAML flavors.

Lightweight View Models For WPF

I understand MVVM's usefulness in the context of a large team developing a shrink-wrapped application over a long period of time. But in the context of an internal LOB application, MVVM seems overkill and I'm having trouble swallowing the overhead of debugging declaritive databindings, jumping from layer to layer to layer, and extracting VM's that are barely more than the Model with a command or two. Even accepting that overhead, still leaves me with the holes in MVVM like dialogs. A few things I've considered is:
Binding directly to the Model and do old-school event handlers for form interaction
Binding a user control or window to itself, effectively using the code behind as the VM.
Include a property in my VM to reference the related view.
Make ViewModel's subclasses of a View.
The above items and their combinations address some problems but not all. I do realize that I might sacrifice testability. What other technical (not conceptual like SOC) issues will I run into using one or more of these practices?
I always use MVVM when coding in WPF or Silverlight, even for small single-page apps. It makes it much easier to test and maintain in the long run, and I find it faster to create apps with it than without it
I don't mind taking some shortcuts in smaller apps, such as binding to the Model instead of exposing the Model's properties in the ViewModel, or defining my View in a DataTemplate instead of a UserControl, or using Window's Dialogs in my ViewModels, but I would never consider doing a WPF or Silverlight app without MVVM.
If you want, I have an example of a very simple app done with MVVM here
Code re-usability comes to mind. Properly written VM's could be re-used behind Silverlight or WP7 implementations down the road.

WPF/XAML vs MVC Paradigm: flawed in the very fundamental design

In MVC a model can have multiple views, in WPF a XAML code-behind model is tight to 1 single XAML (view) isn't WPF/XAML flawed from the start in respect to MVC ?
I recommend looking at MVVM for use with WPF.
You're comparing MVC with Windows Forms to WPF with code behind - which is comparing an architectural pattern to a technology (without using a pattern). This is an unfair comparison.
I wrote a series on MVVM starting from a Windows Forms perspective that may help with understanding this. You'll find that the separation of View and ViewModel possible with WPF is far cleaner and simpler to implement than the Controller of MVC. It actually allows even more decoupled architectures with less implementation work.
Good question!
In MVC you state that a model can have multiple views, which is true. However, each view would have its own controller.
In MVVM a model can have multiple views, and in this case each may have their own view model.
However, in practical terms, if a ViewModel does not have any concepts that are highly specific to a certain view, it is entirely possible to re-use view models. In fact, I wrote an article on cross-platform XAML applications where I re-used code between three apps, one on WP7, one in Silverlight, the other WPF:
http://blogs.msdn.com/b/mikeormond/archive/2010/12/09/writing-cross-platform-xaml-applications.aspx
The views for each were very different, however I was able to re-use both the models AND the view models for all three apps.
WPF/XAML is a technology, and MVC is design pattern, it's good when technology is not limiting you to a specific pattern, and allows developer to choose what pattern to use. Same as programing languages allow's you to use any design pattern.
You can use MVC, MVP, MVVM, or YourMegaPattern with XAML\WPF. Technology should be above patterns, it's frameworks that are usually bound to a specific pattern.
For example you can take ASP .NET techology, and MVC framework based on it.

UI Design Pattern for Windows Forms (like MVVM for WPF)

MVVM is most commonly used with WPF because it is perfectly suited for it. But what about Windows Forms? Is there an established and commonly used approach / design pattern like this for Windows Forms too? One that works explicitly well with Windows Forms? Is there a book or an article that describes this well? Maybe MVP or MVC based?
I have tried MVP and it seems to work great with windows forms too.
This book has an example of windows forms with MVP pattern (sample payroll application). The application is not that complex but will give you an idea about how to go about creating it.
Agile Principles, Patterns, and Practices in C#...
You can get the source code at
Source Code
EDIT:
There are two variations of the MVP pattern
(a) Passive view and (b) supervising controller
For complex databinding scenarios I prefer to go with the Supervising controller pattern.
In supervising controller pattern the databinding responsibility rest with the view. So,for treeview/datagrid this should be in the respective views, only view agnostic logic should moved on to the presenter.
I'll recommend having a look at the following MVP framework
MVC# - An MVP framework
Don't go by the name (it's an MVP framework).
Simple winforms MVP video
Winforms - MVP
An example of dealing with dropdown list
MVP - DropDownList
Simple treeview binding example (poor man's binding). You can add any treeview specific logic in BindTree().
Below is the code snippet.... not tested, directly keyed in from thought....
public interface IYourView
{
void BindTree(Model model);
}
public class YourView : System.Windows.Forms, IYourView
{
private Presenter presenter;
public YourView()
{
presenter = new YourPresenter(this);
}
public override OnLoad()
{
presenter.OnLoad();
}
public void BindTree(Model model)
{
// Binding logic goes here....
}
}
public class YourPresenter
{
private IYourView view;
public YourPresenter(IYourView view)
{
this.view = view;
}
public void OnLoad()
{
// Get data from service.... or whatever soruce
Model model = service.GetData(...);
view.BindTree(model);
}
}
As it has already said, i always worked in a MVP pattern when using Winforms. But the design pattern you will use not mean you will use right. There is loads of anti-pattern attached to MVP.
If you want to starts everything in a good manner, you have to use the framework for building smart client. So i will recommend to use that design and practices: Smart Client Software Factory http://www.codeplex.com/smartclient
You have a discussion here about the current smart client frameworks : http://codebetter.com/blogs/glenn.block/archive/2008/05/10/prism-cab-and-winforms-futures.aspx
PS: I like this post on the MVP anti-patterns: http://blog.mattwynne.net/2007/06/13/mvp-smells/
Hope this helps
The Model-View-ViewModel (MVVM) Pattern is a design pattern. Per definition a design pattern shows a common solution in the object-oriented world and this solution can be applied in various platforms (WPF, WinForms, Java Swing, etc.). I agree that MVVM is best used with WPF because it leverages the strong binding capabilities. However, Windows Forms supports data binding as well.
The WAF Windows Forms Adapter shows how to apply the MVVM Pattern in a Windows Forms application.
I have written about a variation of MVP/MVVM design patterns called MVP-VM, which is a tailor made solution for winforms applications that require full testing coverage and use data binding as main mechanism for keeping the presentation updated with model data.
MVVM for .NET Winforms
MVVM (Model View View Model)
introduces similar approach for
separating the presentation from the
data in an environment that empowers
data binding (WPF). Since .NET
framework 2.0 already offers advanced
data binding infrastructure that also
allows design time binding of
application objects - the ‘View Model’
entity can fit quite well in MVP based
environment.
I asked this same question to two of my techies co-workers: is MVVM for WindowsForms possible? Both gave me the exact same answer: "No way! WindowsForms is missing the rich bindings of WPF and Silverlight (OneTime, OneWay, TwoWay, OnewayToSource) and it is also missing the TypeConverters."
Screen Activator Pattern for WindowsForms - you can find it here, ported from Caliburn.Micro by jagui
Rich Bindings and TypeConverters - Truss by Kent Boogaart, does it in an UI independent way
Commands - WPF Application Framework (WAF) has a WafWinFormsAdapter project that takes care of some MVVM stuff namely commands
Again, can we have MVVM for WinForms?
Yes we can. We have all the pieces. We just have to glue them together.
I believe that MVP is a pattern well-suited to WinForms development - as is partly evidenced by it's use in CAB - Microsoft's framework for WinForms.
I use MVP in WinForms to extract code out of the View - because I can't test the View code. And also to enable code that needs to be reused (or is duplicated) to stay out of the View where it can't be shared.
I can refer to my own project where I use the MVP pattern ExceptionReporter.NET. Though I'm sure I don't use it perfectly.
You mentioned MVVM working for WPF - I think the reason for that is because of strong data-binding support. If you were not using data-binding in WPF (and it's certainly not compulsory) then you could choose MVP. The point being that MVP is a strong choice for any client-side application. And possibly a 'better' choice, even in WPF, if you plan on sharing code between projects that aren't WPF.
For more evidence of the value of using MVP in WinForms see Boodhoo's video presentation on using MVP:
http://www.bestechvideos.com/2008/06/29/dnrtv-show-14-jean-paul-boodhoo-on-model-view-presenter
And an MSDN article by the same author at http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
The BindTree method seems a little
flawed to me. Suddenly the the View
knows abou the Model. Is that a good
thing? There must be tons of poeple
being confronted with these kind of
problems. I am surprised that there
aren't any books about it. Since there
are books about everything in the .NET
world.
These Design not about hiding the model rather precisely defining the interactions between the different layers of the applications. You can change the backend completely and as long as you pass a Model through Bindtree your UI will continue to work.
Now class Model may be a poor choice of a name in the example that Rajesh gives. It can be TreeData, or RecordsData. However you define it, it has what you need to using the binding mechanism of Winforms to bind a specific control to the underlying data.
The best site to browse for this kind of material is here. Martin Fowler has collected a variety of useful UI design pattern and enterprise design patterns.
Again the key to this is the use of interfaces to precisely define how each layer interact with each other.
In my own application (a CAD/CAM applications used to run metal cutting machines) my structure looks like this.
Forms implementing form interfaces
UIDLL with views implementing view
interfaces that interact with forms
through the form interface. The
specific views register themselves
with UIViewDLL Views executes Command Objects found
in command libraries that interact
with the Model.
Command libraries; lists of
commands implementing ICommand.
The command that interact with
views do so through the interfaces
exposed in UIViewDLL.
UIViewDLL; exposes the View Interfaces
used by the commands.
Model; the classes and collection that
make up core data structures of my
application. For me these are things
like material, cuttingpaths, shape,
sheets, torches, etc.
Utility; a DLL that has commonly used
utility classes used by my company
that span different application. For
example complex math functions.
You can use Enterprise Architecture, Patterns and Practices as the starting point, although they are slightly dated.
Under General Guidance there is Application Architecture for .NET: Designing Applications and Services, which is a good introduction to .NET ways and layered N-tier application.
alt text http://i.msdn.microsoft.com/ms954595.f00aa01%28en-us%2CMSDN.10%29.gif
For more formal "patterns", there is Enterprise Solution Patterns Using Microsoft .NET.
(source: microsoft.com)
To name a few,
Model-View-Controller
Intercepting Filter
Three-Layered Services Application
The first good explanation of UI design patterns I read was in Jeremy Miller's blog - Building Your Own CAB. It describes the common patterns - Passive View, MVP, etc. and addresses some of the ways you might implement them in C#.
You can try MugenMvvmToolkit that allows to use a "pure MVVM" for WinForms.
Due to the fact that it supports bindings on all platforms, all of the native binding features available for WPF platform available on all platforms (include WinForms).

Should I use the Model-View-ViewModel (MVVM) pattern in Silverlight projects?

One challenge with Silverlight controls is that when properties are bound to code, they're no longer really editable in Blend. For example, if you've got a ListView that's populated from a data feed, there are no elements visible when you edit the control in Blend.
I've heard that the MVVM pattern, originated by the WPF development community, can also help with keeping Silverlight controls "blendable". I'm still wrapping my head around it, but here are some explanations:
http://www.nikhilk.net/Silverlight-ViewModel-Pattern.aspx
http://mark-dot-net.blogspot.com/2008/11/model-view-view-model-mvvm-in.html
http://www.ryankeeter.com/silverlight/silverlight-mvvm-pt-1-hello-world-style/
http://jonas.follesoe.no/YouCardRevisitedImplementingTheViewModelPattern.aspx
One potential downside is that the pattern requires additional classes, although not necessarily more code (as shown by the second link above). Thoughts?
I definitely think you should use the MVVM pattern for Silverlight applications - and one of the benefits of the pattern is that you can actually make your application really blendable through some simple techniques. I often refer to "blendability" as "design for designability" - that you use certain techniques to make sure your application looks great in Blend.
One of the techniques - like Torbjørn points out - is to use a dependency injection framework and supply different implementations of your external services depending on wether the code is being executed in Blend or in the Browser. So I configure my container to use a dummy data provider when the code is executing in Blend, and that way you get design time support for your list boxes, data grids etc.
The challenge is often how to set the DataContext declaratively - so I often end up using a service locator class a a "front end" to the IoC container. That way I can bind the data context to a property on the service locator.
Another technique is create some kind of ObjectDataSource control (non visual) that has two properties: Design Time DataContext and RunTime Data Context. The control does the job of detecting where is being executing, and then setting the Parent DataContext to the right object.
I'm not sure if I can answer your question, but I have foudn the article below very valuable. Jonas Follesø is using ninject to switch out his services when in design/blend mode. Very nice!
http://jonas.follesoe.no/YouCardRevisitedImplementingDependencyInjectionInSilverlight.aspx
I also agree with Jonas regarding MVVM with Silverlight. I do believe that MVP is also a good choice, but recently I have had time to try both MVP and MVVM with Silverlight and I am much happier with the results from MVVM. (Yep, I changed my mind the more I used MVVM). The VM abstracts the binding of the Model from the View (obviously) in MVVM which allows for more binding scenarios (at least cleaner ways to do them) than with MVP. That's just one aspect, though.
I'll be posting some examples of both MVP and MVVM with Silverlight on my site.
I've tried a few options and I'm settling on MVVM as the best choice for me. Blendability is an important point, and I also find the VM aspect intuitive for rigging up dynamic behaviors and procedural effects and animations (like Nikhil's Silverlight.FX). At one point I tried to avoid Blend altogether through fluent interfaces but am finding the coupling between UI and behavior too painful in the long-run. I want to design my UI in Blend and then add effects and other behaviors in code, this is proving to be the best pattern for me to follow so far.
I think many of us are waiting for the trailblazers to go ahead and create really good sample apps using MVVM in Silverlight (and WPF for that matter). There are a number of tricky areas such as the lack of ICommand in Silverlight, or the difficulty of interacting with animations starting and stopping only using data binding.
Its definitely a pattern to watch for the future though, and is worth trying out if you don't mind 'cheating' occasionally in the places where you can't quite figure it out.
I love the ViewModel pattern and highly recommend it. I have a couple of "getting started with ViewModel" types of posts on my blog.
ViewModel Pattern
HelloWorld.ViewModel
Binding Converts - VisibilityConverter
Silverlight Airlines with a ViewModel
I agree with Jonas. MVVM seems to be the model that works best for me (though John Papa thinks MVP makes more sense). I have an MSDN Article on this coming out in March that hopefully will answer the call for a good example.
BTW, I would like to see some cohesion in the MVVM Framework department. There isn't a good solution for a framework to follow yet. I like Jonas' (I think Jonas' is the FX Framework) but since its not WPF compatible it might not be the right choice for some.
I've been using MVVM lately on a couple of different Silverlight projects and it's been working really well, I would definitely recommend it. Jonas's post is a great place to start, I've recently blogged on my MVVM experiences too and created a really simple solution to demo the main touch points.
There's a very good Techdays 2010 video introduction to the MVVM pattern, clearly explained:
TechDays 2010: Understanding the Model-View-ViewModel pattern
Hanselminutes podcast by Laurent
For more complicated applications that require a higher degree of automated testing it definitely makes sense, and the move away from DependencyProperties to DataContext binding is a lot neater than it's ASP.NET counterpart.
The biggest challenge I've found with Silverlight is testing the actual UI (there's one commercial framework so far I think), and the huge tangle of event calls you get into when using WCF services (or the WebClient for that matter) with Silverlight.
I've always thought MVVM and PresntationModel http://martinfowler.com/eaaDev/PresentationModel.html are essentially the same thing. PresentationModel is a lot easier to say.
I've used it succesfully in java swing, windows forms, WPF and silverlight. If you think in terms of separation of concerns a Presentation Model makes a lot of sense. You have one class whose only concern is providing a Presentation friendly Model.It really doesn't matter what technology is used to show it on the screen. It might change some implementation details but splitting the concerns apart is a good idea no matter how you show the information.
Because of that separation you can easily write tests against your presentation model regardless of the view technology. So that's a plus.
With the Feb 2009 release of Prism v2 by P&P, even better support for MVVM now available for Silverlight and WPF. See microsoft.com/compositewpf for more details.
Take a look at my article about MVVM and Silverlight in real life projects and decide for yourself.
http://alexburtsev.wordpress.com/2011/03/05/mvvm-pattern-in-silverlight-and-wpf/

Resources