Business Logics of projects under MVVM in WPF? - wpf

I am developing an application in WPF using the MVVM pattern. If I have Student as a data model, for example, where could I add the business logic like adding new Students, deleting Students and updating Student info, calculating marks and so on?
Does all the business logics come under the model or the viewmodel?
If it is in the model how can we do that? Any example code please? I need full code for an example!

Business logic should be part of of your model, as all of that code should be reusable across different technology platforms. For example, you may want to reuse your models across a web site in ASP.NET MVC, and a desktop application in WPF, so it wouldn't make sense to have business logic in your view models.
View models should contain presentation logic which is specific to that particular application instance.
As for example code, this will be specific to the domain that you are modelling, so you would have to ask a more specific question about what you are trying to model.

I suggest you read PRISM documentation on this subject: Chapter 5: Implementing the MVVM Pattern.
Even if you don't plan to use PRISM, the article is very well written and details the pattern in Microsoft's technology terms.

I would trust very little of what Microsoft has to say on Patterns as their articles are often dated, or modified to support their own proprietary frameworks or products. Also I've found MS thoughts/approaches contradictory within their different teams and also within the generally accepted approach in software.
Not all of it is good and not all of it is bad basically.
To answer your question. I'd use a Service for Business Logic. I'd instantiate a reference to it in the ViewModel and I would not put any logic in either the ViewModel or the Model that did not have anything to do with their role. ie Presentation logic is okay dependingon what it is, it might be best placed in the ViewModel as it is highly tied to the View in question. Same goes for the model.
Keeping in mind these roles you will have a scaleable and testable application.

Related

MVC or MVP architecture for winform applications using Entity Framework as ORM

I am going to develop a winform project of considerable size. I am planning to use Entity Framework as ORM tool. Now I am searching for an architecture(MVC/MVP/MVVM etc..) to implement all these. Firstly there are few choices for n-layered architecture for windows forms and most those I get are written prior to EF came into market. I got a framework called Rocket Framework from codeplex(http://rocketframework.codeplex.com)
I have looked around it but am skeptical that it will accommodate a wide range of requirements. If anyone has already discovered the wheel already, please guide me through.
Also if the existing architectures prior EF4 can accommodate it than also I can give it a try.
Ideas please!
Well your choices is influenced by the technology you're using. Some technologies make a certain pattern natural to do and thus if you (and every developer) don't explicitely design and care about this you'll end up with what feels most natural. On WinForms the most natural pattern is MVP. You have your view that you can layout in the designer and your code-behind file becomes the presenter, essentially combining view and presenter in one class (it's a 1:1 relationship anyway). For web applications on the other hand MVC is a natural pattern since your web server already acts as a controller. Finally MVVM is supported very well in WPF, although you could fall towards MVP there as well if you start using the code behind file a lot. But relying on DataBinding instead can make you forget to use the code behind file. A good article I read about this is here. Of course you can realize MVVM with WinForms, read this link for a good example.
From the point of testability MVVM is perceived as the best pattern since your view model (and therefor the behavior of your view) can be tested without an actual GUI. MVP however is easy to understand and realize, doesn't require complex bindings and gives you most control over what is happening (e.g. event suppression).
WinForms applications are mostly developed with MVP pattern. The original MVC is not used very much - only its Model-2 variant (for example ASP.NET MVC) for web applications. MVVM is used primarily with WPF and Silverlight.
Neither of these patterns affects how you use Entity framework - they are not data access related patterns.
After a lot of R&D and extensive study I finally settled here:
https://github.com/geersch/ModelViewPresenter
It is an MVP architecture written by Christophe Geers. It supports all I needed- Architecture for winform, web portability support, Entity Framework. Really nice and easy to use.
Additional reading:
http://www.cerquit.com/blogs/post/MVP-Part-I-e28093-Building-it-from-Scratch.aspx

What is the best architecture for a business application using WPF & EF?

I'm confused about the architectures which we can use to develop a business application with WPF 4.0 and EF 4.0 technologies.
My first choice was a traditional N-tier architecture contains: UI, Business Logic Layer & Data Access Layer with a disconnected behavior.
In this way I create 3 project for each layer and another project for my Entities/DTOs (Each layer is an assembly). Each layer references only to it's upper and lower layers (That is: UI can see the BLL but can't see the DAL). But all layers have access to the Entity/DTOs assembly for communication purposes.
The problem starts when I want to create a simple CRUD form with a DataGrid for example. The BLL disposes the DataContext of the DAL when returns an Entity/DTO, this is the reason that forced me to use STEs. But yet there are several problems. For example I should call "StartTracking" method for each entity returned from BLL to the UI. In short, I don't sure about this pattern reliability or I think I have to forget about automatic handled CRUD forms.
I use the repository model in my DAL layer but when I search about the repository pattern I find it different. It seems that it's not bad to reference to both of the DAL/Repository and the BLL/Services(Not WCF nor WebServices) layers from the UI and thus we can have a connected environment (Without using STEs).
I see an example in which we can get a person from repository but do something on it using BLL or services:
UI CODE:
var person = new PersonRepository().GetPerson(10);
Bll.Salary.PaySalary(person);
-or-
var person = new PersonRepository().GetPerson(10);
Bll.Person.MarkAsAbsent(person);
Or something like that...
With this pattern we can send the Entities/DTOs to the UI in a connected way while the DataContext is alive.
I don't know if I understand the way of using the repository pattern in big projects. I think it's not clear to naming the BLL or services classes and methods in this way. More over the developers might be confused about where to use the repository methods or BLL/service methods or about where to create the methods (in repositories or BLL/service).
I prefer the N-Tier architecture using a good approach to track the Entities/DTOs changes automatically like STEs.
Would you please recommend the best pattern in such situations or/and reference me to some good books or documents about that.
I put together a sample app that may help with some of your questions. You can review the presentation notes and the sample via my blog post here:
http://blog.alner.net/archive/0001/01/01/wpf_ef_4_sig_presentation_2010.aspx
The sample shows using STEs and includes some helpers to make the Entity Framework STEs work better in a desktop client app.
Repositories are there to hide the details of how you get the data. The idea is that you could swap the implementation of a repository from one that uses a local database, to one that uses a remote web service without the upper layers knowing about it.
Maybe the article Architecture for WPF applications is any help for you.
You might have a look at the BookLibrary sample application of the WPF Application Framework (WAF) as well. It shows a WPF MVVM application together with the Entity Framework applying the described architecture.

Is it feasible to reuse WPF ViewModels in MVC?

we have a rich client application written in WPF/WCF and are intending to create a companion website in ASP.net (using MVC if possible).
I've been asked to figure out how much of our current codebase, we can reuse (by a separate team) - and I have little to no experience with ASP.net.
We will reuse our domain model, but is there any point in separating out the WPF-specific parts of our ViewModels and reuse the WPF-agnostic parts in MVC? Does it even follow the same paradigms? We use RelayCommands exclusively for commanding, so it would be easy to wrap the contained methods in something ASP.net specific... But how about UI-specific things - e.g. does ASP.net use INotifyPropertyChanged - or how does it handle UI-updates?
For me it wouldn't make any sense. Your models should contain all of your important business logic code and should be the point of greatest reuseability. Your view models should contain presentation logic only, and as this is so different for a desktop and web app, it doesn't make sense to reuse these.
MVC does not use any binding mechanism for UI updates, as web apps are stateless by nature. You will actually most likely end up using view models for your MVC app, but in MVC these act as simple data transfer objects (DTOs) for providing data to the views for rendering for each HTTP request. Once the view is rendered, you would need to go back to the server to update the view model and rerender the view.
Alternatively, you can of course update the UI client side with scripting. Knockout.js is a nice JS library for client side view model/view binding.
I can't directly answer your specific question because it depends highly on your application and the way your existing view-model is written but the question you raise is an interesting one.
On the one hand, the logic that the view-model contains very little view-specific code is a tantalizing argument for reuse. On the other hand, the view-model very clearly serves the needs of the view and expecting it to serve the needs of a different view could be problematic.
In the end all we can give are guidelines. You certainly don't want a monolithic view-model with ifdefs or ifs all over the place. You could refactor common functionality into base classes -- that's the object-oriented way -- but without good unit tests it's sure to break something in your already working code. But not doing that means having distasteful cut-and-paste code that is almost the same and likely to diverge creating a maintenance nightmare.
Perhaps a practical approach is to assume you'll need a whole new view-model but to review your existing view-model for code you can push down into the model before your start, thereby making the view-model as small as possible. Then at some point, maybe after you get a prototype working, you could attempt a merge to see if it is practical and what issues arise. If it can work, take those issues into account as you continue implementation and then plan the two tasks according to your needs.

Is it possible to generate a complete, working WPF/Silverlight/XAML application that emits best practices?

Is there a way, given a database or some other source specification for an application, for an entire WPF or Silverlight / XAML application to be generated that emits best practices?
For example, assuming I have a well-normalized database (or some other kind of base specification for an app), is there a tool that can create a well-formed MVVM application. This would include...
XAML (Views) for all of the tables (list and edit) with no code-behind
ViewModels that emits properties extracted from the db schema along with commands or behaviors for all of your standard CRUD operations
Models built with the repository pattern (or some other db abstraction) with interfaces that emit the table design and relationships and a default implementation of your choice (sql, sql ce...whatever).
An ideal tool like this would only do a "first pass" of the application after which the developer would make all necessary changes and modifications.
I don't think there is any such tool but it seems like a tool like this should be possible.
Another related question, in the absence of such a tool (or even if there is one), what tool(s) are best used to get me from a database design (or some other kind of base specification for an app) to working app.
What STEP-BY-STEP process do you take to get from design to basic working application in a couple of hours?
I am just trying to figure all of these practices and patterns and I am getting a pretty good grasp of the pieces but not sure what workflow to use to make it all work together quickly but still allows unit testing of separate concerns.
Thanks in advance.
Seth
Not sure if this is what you are looking for, but you can use LightSwitch
From a process perspective, I build and test my ViewModels first. That allows a division of labor between designing and wiring up the UI and pulling data into the ViewModel.

MVC vs. Observer Pattern

I've recently asked a question on StackoverFlow about the MVC: Can the MVC Design Pattern / Architectural pattern be used in Desktop Application Development?
Based on the answer provided I started research on how this would be implemented in a Windows form Application. I came upon the following CodeProject article: http://www.codeproject.com/KB/cs/model_view_controller.aspx
In the comments below the article, certain users argue that (although this is a good article) it is actually the observer pattern. First, but less important, question is does anyone agree or disagree with that and why?
Regarding the second and more important question: I'm trying to build a small task list program in .NET. It will be very tiny and hopefully fast. In general, what would be a better architecture for such a project? The Observer Pattern or the MVC Pattern? Or another pattern?
Thank you
usually the model in an mvc (http://en.wikipedia.org/wiki/Model-view-controller) is an observable/subject (http://en.wikipedia.org/wiki/Observer_pattern#Subject), while the views are observers (http://en.wikipedia.org/wiki/Observer_pattern#Observer). also see: mvc in http://webcourse.cs.technion.ac.il/234321/Winter2005-2006/ho/WCFiles/08-Design-Patterns.ppt
(The article is not an example of MVC AFAIK for the simple reason that there is no controller.. it is more close to .net data binding if you ask me.)
MVC is not the Observer pattern. MVC is concerned with separation of concerns. The Model, the View and the Controller all do one job and trust the others to do theirs. In a way, the Controller 'directs' the view and tells it how to react to a change (Pure MVC). The controller also interacts with the model appropriately (whose responsibility is to encapsulate data and enforce constraints/rules). In MVC, the controller is the starting point for all activities - user input is received by the controller first.. However there are variants like MVP, where the user is input is received by the view first and then pushed/synched with the presenter.
The Observer pattern is where you want to watch another object for a change in state. So you could say .net events follow the observer pattern
If its really tiny, forget about patterns and just code it up without worrying about the architecture... Follow the heuristics/principles of good design
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
http://mmiika.wordpress.com/oo-design-principles/
If you run into design issues or it starts to get all messy, then bring in the pattern battalions.
I would agree that the article is not MVC. Its more of an implementation of observer pattern. Observer pattern in .NET can be implemented by using events, which was the case of the article.
MVC requires a controller class that controls what action to execute upon a request made from either the model, or the view. Applying MVC is a very good programming practice as it greatly promotes separation of concern. You will have a cleaner, more extensible, and more testable app with mvc. Another point to note, you can still apply observer pattern to an MVC app. They will not contradict each other.
===========
To answer your second question: which pattern is the best? I think the way you approach software development is rather wrong. You shouldn't worry too much about those things yet, not until you've hit a problem. e.g. If this object changes state I need these other objects to react to it, hence I would implement an observer pattern.
If I were you I would start on the model side first, and then takes things from there.

Resources