Simple Elegant pattern to separate Data Access, Business logic and presentation - c#-2.0

I need a simple pattern to do the above.
Few things to note:
1) I have a class that I am obliged to use that does the actual data retrieving and it return DataTable
2) I am not concerned with the generic interfaces that support all possible database types, we are sticking with one database type.
3) How do I elegantly trap the error and inform the user that error occured.
4) Do not offer me to learn MVC - it is not an option right now.
I am interested in the actual pattern design.

You want to use the MVC pattern to separate business logic from presentation (note that I am NOT talking about the ASP.NET MVC Framework) and the DAO pattern to separate business logic from data access.
Your class that returns a DataTable becomes part of your model. You write a layer (a DAO for each domain object) that takes your DataTable and translates it into your various domain objects. Your UI shouldn't contain any logic that does more than presenting output to the user; anything that is actual logic for retrieving data from your model is handled in a controller layer, that gets the data the user is requesting from the model and sends it to the appropriate view to present it to the user.
Exceptions should be handled at layer boundaries; either catch and do something about it (which might just be to log it and send the user to an error page), or wrap in a higher-level exception as appropriate.

Do not offer me to learn MVC - it is not an option right now.
You can do a simple MVC or MVP pattern without using the ASP MVC Framework. It is pretty simple to introduce. Here is a pretty simple example MVP Example

There are a number of patterns that approach what you describe. I would recommend getting a copy of Martin Fowler's excellent book Patterns of Enterprise Architecture specifically Chapter 14. Web Presentation Patterns. You will find that any serious attempt to separate the presentation, domain (business logic), and data source will lead you to one of many variations of the same theme.
MVC, MVP, visual proxy, etc all break down to three layers what differs is the responsibilities of each layer and how layers communicate with each other.
For instance, the Passive View pattern basically strips the UI layer of anything not directly related to presentation. The typicall example being a field you want to highlight if a certain condition is true. In a Passive View the form would only only contain the logic to determine the whether the field should be highlighted. The business rule that trigger's this state would be in a presenter/controller layer which does not directly depend on the actual view.
As far as the data source layer, the main benefit isn't being able to switch databases at the drop of a hat. The main benefit is that changes to the database schema only affect the data source layer and don't extend into the rest of the application. If your stuck with datasets a good approach is the Table Data Gateway pattern.

Related

Service layer and project structure in ASP.NET MVC 5 without repository and UoW patterns

I'd like to create a good app in ASP.NET MVC 5 using EF 6 Code first concept. I want it to be well-designed i.e. having generally speaking: Presentation, Logic and Data layers separated. I want it to be testable :)
Here's my idea and some issues related with creating application
Presentation layer: It's my whole MVC - view models(not models), views, controllers
I believe that's validation should be done somewhere else (in my opinion - it's a part of business logic) but it's quite convenient to use attributes from the DataAnnotations namespace in ViewModelds and check validation in controller.
Logic layer: Services - classes with their interfaces to rule business logic.
I put there functions like: AddNewPerson(PersonViewModel Person), SendMessageToPerson(...).
They will use DB context to make their actions (there's a chance that not all of them will be relying on context). There's a direct connection between service and db - I mean the service class have reference do context.
Where should I do mapping between ViewModel and Model? I've heard that service is a bad place for it - so maybe in controllers. I've heard that service should do the work related with db exclusively.
Is it right? Is my picture of service layer is good?
Data layer: I've read about Repository and UoW patterns a lot. There're some articles which suggest that EF6 implements these two things. I don't want to create extra code if there's no need for such a behavior. The question is: am i right to assume that i don't need them?
Here's my flow:
View<->Controllers(using ViewModels)<->Services(using Models)<->DB.
**I'm gonna use DI in my project.
What do you think about my project structure?
There is no reason to use a Unit of Work pattern with Entity Framework if you have no need to create a generic data access mechanism. You would only do this if you were:
using a data access technology that did not natively support a Unit of work pattern (EF does)
Wanted to be able to swap out data providers sometime in the future.. however, this is not as easy as it might seem as it's very hard NOT to introduce dependencies on specific data technologies even when using an Unit of Work (maybe even BECAUSE you are)... or
You need to have a way of unifying disparate data sources into an atomic transaction.
If none of those are the case, you most likely don't need a custom Unit of Work. A Repository, on the other hand can be useful... but with EF6 many of the benefits of a Repository are also available since EF6 provides mocking interfaces for testing. Regardless, stay away from a generic repository unless it's simply an implementation detail of your concrete repositories. Exposing generic repositories to your other layers is a huge abstraction leak...
I always use a Repository/Service/Façade pattern though to create a separation between my data and business (and UI and business for that matter) layers. It provides a convenient way to mock without having to mock your data access itself and it decouples your logic from the specific that are introduced by the Linq layer used by EF (Linq is relatively generic, but there are things that are specific to EF), a façade/repository/server interface decouples that).
In general, you're on the right path... However, let me point out that using Data Attributes on your view models is a good thing. This centralizes your validation on your model, rather than making you put validation logic all over the place.
You're correct that you need validation in your business logic as well, but your mistake is the assumption that you should only have it on the business logic. You need validation at all layers of your application.. And in particular, your UI validation may have different requirements than your business logic validation.
For instance, you may implement creating a new account as a multi-step wizard in your UI, this would require different validation than your business layer because each step has only a subset of the validation of the total object. Or you might require that your mobile interface has different validation requirements from your web site (one might use a captcha, while the other might use a touch based human validation for instance).
Either way, it's important to keep in mind that validation is important both at the client, server, and various layers...
Ok, let’s clarify a few things...
The notion of ViewModel (or the actual wording of ViewModel) is something introduced by Microsoft Martin Fowler. In fact, a ViewModel is nothing more than a simple class.
In reality, your Views are strongly typed to classes. Period. To avoid confusion, the wording ViewModel came up to help people understand that
“this class, will be used by your View”
hence why we call them ViewModel.
In addition, although many books, articles and examples use the word ViewModel, let's not forget that it's nothing more than just a Model.
In fact, did you ever noticed why there is a Models folder inside an MVC application and not a ViewModels folder?
Also, ever noticed how at the top of a View you have #model directive and not # viewmodel directive?
That's because everything could be a model.
By the way, for clarity, you are more than welcomed to delete (or rename) the Models folder and create a new one called ViewModels if that helps.
Regardless of what you do, you’ll ultimately call #model and not #viewmodel at the top of your pages.
Another similar example would be DTO classes. DTO classes are nothing more than regular classes but they are suffixed with DTO to help people (programmers) differentiate between all the other classes (including View Models).
In a recent project I’ve worked on, that notion wasn’t fully grasped by the team so instead of having their Views strongly typed to Models, they would have their Views strongly typed to DTO classes. In theory and in practice everything was working but they soon found out that they had properties such as IsVisible inside their DTO’s when in fact; these kind of properties should belongs to your ViewModel classes since they are used for UI logic.
So far, I haven’t answered your question but I do have a similar post regarding a quick architecture. You can read the post here
Another thing I’d like to point out is that if and only if your Service Layer plans on servicing other things such as a Winform application, Mobile web site, etc...then your Service Layer should not be receiving ViewModels.
Your Service Layer should not have the notion of what is a ViewModel. It should only accept, receive, send, etc... POCO classes.
This means that from your Controller, inside your ActionResult, once the ModelState is Valid, you need to transform your ViewModel into a POCO which in turn, will be sent to the method inside your Service Layer.
In other words, I’d use/install the Automapper nugget package and create some extension methods that would convert a ViewModel into a POCO and vice-versa (POCO into a ViewModel).
This way, your AddNewPerson() method would receive a Person object for its parameter instead of receiving a PersonViewModel parameter.
Remember, this is only valid if and only if your Service Layer plans on servicing other things...
If that's not the case, then feel free to have your Service Layer receive, send, add, etc...ViewModels instead of POCOs. This is up to you and your team.
Remember, there are many ways to skin a cat.
Hope this helps.

How to DTOs fit into the Repository+Service Pattern of MVC Applications?

I'm about a month into MVC and from what I understand, a pretty good approach to app architecture is:
MVC <> Service <> Repository <> Core
Within MVC we have Views, and Controllers to populate viewModels for the controllers. My question is: Where exactly to Data Transfer Objects come in? I'm building a single-page web app and I'm trying to do it right from the beginning.
From the reading I've done, I should use DTOs to "flatten" the Model objects before passing them into the ViewModel. Do they act as a "only data that I need" object that gets passed from the service to the controller, at which point the viewModels are constructed? If so, is it generally true that each model definition (ie Sets, Cards, Users) should have corresponding DTO classes in the Core layer? Any clarifications here would be awesome, thank you for your time!
First of all, about this phrase: "a pretty good approach to app architecture is...": I don't believe there is a single good approach to all apps, and I would prefer always to use the simplest approach (i.e. fewer layers) that could solve your problem at hand.
When you say "Service", it appears to be a whole layer of web services, rather than just some domain service classes; in most cases I've seen with Asp.Net MVC, the controller itself can fulfill the role of a service, thus eliminating the need to add yet another layer. Of course there are exceptions, just be sure your reason to increase complexity is legitimate.
About DTO's and View models: DTO's, like you described, flatten the object model and return "only data that I need". DTO is a more generic term, usually used with web services where you don't know who is the consumer. Think of (Asp.Net MVC) View Models as a more specialized kind of DTO, that returns "only data that THE VIEW needs". Thus, if you don't need an extra layer of services, you also don't need an extra layer of DTO's, just use View Models to flatten the domain classes directly and return them from your controllers.
In fact, for very simple applications, even the separation of Models x ViewModels is overkill - it is possible to use a single Model layer to fulfill both roles, with the help of the ViewBag. I don't know your requirements, so I can't say which is better for you.
Finally, one comment: if you must build a single page application, Asp.Net MVC is not the best tool for the job. I'd recommend using Asp.Net Web Api (only services, no views) at the server and a client mvc framework, such as BackboneJs or AngularJs.

Having MVC controllers light and models heavy

I have heard that the controller should be kept light and models heavy.
I am somewhat confused about the best practice on what should be kept in the controller and what should be kept in the model.
In our organization, we use Entity Framework where and put the tables there.
For the controller, we use LINQ and then send the info over to the view.
Kind of confused on what code should be in the Controller and in the Model.
DisclaimerThe whole topic is a giant mess. Especially when it comes to Web MVC. For all practical purposes it is impossible to use classical MVC pattern for web, because the view should be observing model. Theoretically you could implement something like that with WebSockets, but keeping a persistent model for each user is not a realistic solution.
Here is what you must know about MVC
The most important idea in both classical MVC and MVC-inspired patterns Separation of Concerns. It divides the application in two major layers:
Presentation layer
Governs the user interface. It deals with both creation of the interface and reacts to the user's manipulation of this interface. This interface might be GUI for a desktop application or HTML web page, but it also can be REST API or receiver-responder on a Mars rover. This is why a web application can implement MVC pattern in both frontend and backend.
The mandatory parts are views and controllers, but, in context of web, fully realized views usually also use multiple templates to create the interface.
Model layer
This is where all the business rules and logic lives. The M in MVC is not a single entity. Instead it is a layer, which contains different structures. Some of those structures are also responsible for interaction with storage.
What are the responsibilities of controllers ?
Controllers are part of presentation layer, which deals with user input. In context of web-based implementations, you will usually have 1:1 relationship between views and controllers, where controller receives the requests from browser and, based on the content of said requests, alters the state of model layer and view.
If you are using classical MVC or Model2 MVC, then that is the extent of controllers responsibilities.
In MVP and MVVM patterns, where you have a passive view, controller-like structures are responsible for acquiring information from model layer and passing it on to the current view instance. This post might provide some additional details on the MVC-inspired patterns.
But the controller is in no way responsible for any form of business logic. If it was, it would mean, that you have a leaking abstraction, because the structures of presentation layer would be doing work, which should be in the model layer.
Usually the controllers will the be simplest structures in you application.
What about the model ?
As mentioned before, model is a layer, which encompasses all of the domain business logic and related functionality. This layer , just like presentation layer, is made up from multiple groups of structures:
Domain Objects[1]
These structures are usually what people mean, when talking about "models". They are also known as model objects or business objects. This is where most of domain business logic ends up.
Data Storage Structures
This group would contain all of the classes, which abstract the interaction with storage (SQL databases, caching systems, noSQL, remote SOAP or REST APIs). They will usually implement some variation of data mapper or repository pattern , but you could be using some other solutions too, like unit of work. The implementation details are not so important. What is important is that they let you store data from and retrieve information into your domain objects.
Services
Or you could call the "components". There are high level abstractions in your model layer, which facilitate the interaction between domain objects and storage structures. The usually represent large chunks of model layer, like "recognition service", "mailers", "article management", and will provide the interface for presentation layer to interact with.
That's something of a religious debate.
Some like as little as possible code in their controller and other as little as possible in their model.
Do what feels natural to you in the project, but be consistent within it.
All else is dogma you can pick an example either way and make a case.
Model is the core of your application. It is best to think of models as of your business entities. Do you want to create a view of an invoice? Then Invoice be your model, it represents the underlying object.
Controller is just a way to handle requests from a client, retrieving the data from database (or updating them) and flushing out the responses.
Your thoughts about the application design should be model-centric, that's the important part.
In simple terms, Model represents the underlying data that your application will be using. It is to be designed in a way that it can be used across different applications.
For example, A model to represent News data can be used by console commands, Web service etc.
It is in model where you will have ur business logic defined, independent of the view.
Controller can be thought of as glue that binds Model and View together. They deal directly with client requests and accordingly interact with views and models.
In a well designed application, you data structure and business logic will be designed in a
Model, making it "heavy". While Controller will just interlink your model and view with the client requests, making it "light".
In the classic Model-View-Controller MVC pattern, your Model is essentially a "headless" application, with no UI and is completely UI-agnostics. It offers an API that is the functional core of the application.
The View is the user interface, however you choose to define it (web page? elevator control panel? something else?). A given application might have 1 view or it might have many views.
The Controller (or Controllers — like Views, you might have one to many Controllers for a given application) relays and transforms events, notifications and data between View and Model so as to preclude the Model from needing to know anything that is View-specific.
The idea is to isolate the core application (the Model) from the user interface (the View). From that some things follow:
The View is aware of and communicates with both Controller and Model (you're unlikely to try to wire up the View to another Model) and expected for the Controller to be aware of both View and Model.
The Controller is aware of and communicates with both View and Model.
The Model knows nothing of Controller or View.
Code that performs business logic should be in the Model, not in the Controller.
I'm no MVC expert, but try and concentrate on the fact that the controller should use the input from the user to direct them to the correct view.
I don't know if NerdDinner is an ideal example, but you can see Scott Hanselman et al does a little bit of data access from his EF context but pushes most of the other logic to service classes or helpers on the model.
I don't know if I agree with the 'models heavy' part, as I don't use the models as 'business objects'. If I really need a lot of 'business' logic, I will typically create that in a separate 'Domain' layer and may even have a separate Data Access layer on top of this. But for a lot of simple (see: non-enterprise) projects, this is overkill in my experience.

What's the difference between a ViewModel and Controller?

What are the responsibilities of one vs the other?
What kind of logic should go in one vs the other?
Which one hits services and databases?
How do I decide if my code should go in the viewmodel or the controller?
For the record, I am using ASP MVC, but since the question is architectural, I do not believe it matters what language or framework I am using. I'm inviting all MVC to respond
The ViewModel is a Pattern used to handle the presentation logic and state of the View and the controller is one of the fundamentals parts of any MVC framework, it responds to any http request and orchestrates all the subsequent actions until the http response.
The ViewModel Pattern: More info
In the ViewModel pattern, the UI and
any UI logic are encapsulated in a
View. The View observes a ViewModel
which encapsulates presentation logic
and state. The ViewModel in turn
interacts with the Model and acts as
an intermediary between it and the
View.
View <-> ViewModel <-> Model
The Controllers (Comes from the Front Controller Pattern): More Info
It "provides a centralized entry point
for handling requests."
HTTP Request -> Controller -> (Model,View)
--Plain Differences:--
While the ViewModel is an optional
pattern the Controller is a must, if
you are going the MVC way.
The ViewModel encapsulates
presentation logic and state, The
Controller orchestrates all the
Application Flow.
The ViewModel can be on the client side as well as server side.
Wherever it may be, the sole purpose of viewmodel is to play the
presentation data.
In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.
The Model-View-Controller (MVC) is an architectural design pattern which exists, primarily, to separate business logic from the presentation. Basically, you don't want your back-end touching your front. It typically looks like this:
The reasons for doing this is because, by separating the back-end and the front, you don't tie your user-interface directly to your data/work. This allows you to put new interfaces onto your business logic without affecting said logic. In addition, it also improves the ease of testing.
A simple example of where MVC comes in handy - let's say you have an application that manages your company's finances. Now, if you are correctly using MVC, you can have a front end that sits at some financier's desk and lets him handle transactions, manage the finances, etc. BUT, because the business logic is separate, you can also provide a front-end to your CEO's Blackberry that lets him see the current status of the business. Because the two front-ends are different, they can do different things while still providing (different types of) access to the data.
EDIT:
Since you updated your question a bit, I'll update my answer. There is no perfect science to the separation of MVC. There are some good rules of thumb, however. For example, if you are talking about GUI components, that is probably a view. (Are you talking about look and feel, usability, etc.) If you are talking about data and the "business" side of the house (databases, logic, etc), you are probably referring to a model. And, anything that controls the interaction between the two is most likely a controller.
In addition, it should be noted that, while Views and Models are typically "physically" separated, a controller can exist with a view when it makes sense.
You are correct when you say the framework (or even language) for MVC doesn't matter. The pattern itself is language agnostic and really describes a way to architect your system.
Hope that helps!
I think there's some value to learning received doctrine. But there is also value in understanding how the doctrine came to be the way it is.
Trygve Reenskaug is widely credited with inventing MVC. N. Alex Rupp's article Beyond MVC: A new look at the servelet architecture includes a History of MVC. In a section on Reenskaug's 1978 work at Xerox Palo Alto Research Center, there's a link to his paper Thing-Model-View-Editor: an Example from a planningsystem. There the pieces are described like this.
Thing
Something that is of interest to the user. It could be concrete, like a house or an integrated
circuit. It could be abstract, like a new idea or opinions about a paper. It could be a whole,
like a computer, or a part, like a circuit element.
Model
A Model is an active representation of an abstraction in the form of data in a computing
system
View
To any given Model there is attached one or more Views, each View being capable of
showing one or more pictorial representations of the Model on the screen and on hardcopy. A
View is also able to perform such operations upon the Model that is reasonabely associated
with that View.
Editor
An Editor is an interface between a user and one or more views. It provides the user with a suitable command system, for example in the form of menus that may change dynamically
according to the current context. It provides the Views with the necessary coordination and
command messages.
Rupp identifies Reenskaug's Editor as a Controller or Tool.
MVC Triads emerged in SmallTalk-80. The model was an abstraction of the real-world concept, the view was its visual representation, and the controller was the buttons and slider bars that allowed the user to interact with it (thereby "controlling" the view). All pieces in the triad were interconnected and could communicate with the other two pieces, so there was no layering or abstraction involved. Since then, Reenskaug has "preferred to use the term Tool rather then Controller." According to his notes, these are the terms he has used in later implementations
Some logic and model should be invoked to generate some data (structured or semi-structured). From this data the returned page/JSON/etc. is created, typically with only rudimentary outlining logic.
The first part (creating the data) is done by the controller (via the model usually). The second part - by the View. The ViewModel is the data structure being passed between controller and view, and usually contains only accessors.
Model represents your data and how it's manipulated. Thus, model touches the DB.
View is your UI.
Controler is the glue between them.
MVC stands for Model, View, Controller.
Model = Data (Database tables)
View = HTML, CSS, JavaScript, etc
Controller = Main logic, a contract between Model & View.
In simple and graspable terms,
MVC allows you to develop your applications in a way that your business data and presentation data are separated. With this, a developer and designer can work independently on a MVC app without their work clashing. MVC makes your app avail OOP too.

Where are the Business Rules in MVC

Now that everyone is talking about MVC, I notice that the business rules are not being addressed. In the old days of the 3-tier architecture, The business rules were in the middle layer. Where do they fall in the new MVC?
The reason you never see MVC address "Business Rules" is that MVC by and large is a presentation pattern. It's focused on how to structure your application. The Model, for example, can be thought of as a presentation model. The model of your application, which the view then renders.
However, in order to create the presentation model, you generally need to go to your domain models where all your business logic lives. At that point, MVC doesn't dictate where that code physically live. Is it on another tier? MVC doesn't care.
At first brush, I'd say they belong in the model. The MVC Entry on Wikipedia seems to agree: "In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data".
After all, by 'Business rules' we mean the functional algorithms and logic that encode the domain that your application is involved with, as opposed to input/output related logic. These core business-related logic does not - or should not- change based upon what is being displayed to the user (which is the domain of the View) or the user input (which is primarily received by the Controller).
In my experience, asking this sort of question has been very revealing during the software development process: we found a large number of things that were considered 'business rules' by some people, but turned out to be something else. If it is not a true business rule, it might not belong to the model.
Business rules always live in the model. The model is the bit that you could resuse with a completely different UI. The view is obviously completely dependent on UI choices and the controller has to take data from the model and tell the view to render it.
Putting business logic into the view is bad because it ties the structure to the presentation.
Putting business logic into the controller is bad because it splits your business domain between the data persisted by the model and the rules in the controller.
A quote from a Wikipedia Article:
MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the model is represented by the actual content, usually stored in a database or in XML nodes, and the business rules that transform that content based on user actions.
Is there any reason why you cant mix MVC and Ntier? Our application does just that. Our controllers are used for data validation and decide which Business Layer calls to make.
OurApp.Web - Asp.net MVC Project
OurApp.Business - Business Layer Library
OurApp.DataAccess - Data Layer Library
OurApp.Entities - Basically all the 'models' shared by all layers
Business rules should be in the model, NOT the controller. The controller and view are part of the presentation layer.
The model represents the domain's entities and functionality ..
The controller is merely a manager for taking user input and requests, performing actions in/on the model and mapping that to views in the presentation layer. The controller is not just a mediator either, the view OR controller may act upon the model.
This is an anciently posted question, but I like a rules repository to be completely independent of any part of an application. Multiple applications, multiple implementations of a business tier, should be able to access a static rendering of a business rules repository. Simple separation decisions such as this make a migration from desktop -> web, for instance, trivial.
In my architecture, View -> Model -> Controller -> Business Tier -> Rules Repository, i.e. the controller accesses coarse data as presented by the business tier/layer, feeds it to the model which massages it into a presentable form, and the view passively displays it. The business tier, which is re-usable across any presentation format, will have explicit rules and access to a subsystem with implicit rules. By design, each component is ignorant of the details of a component above it.
I think the issue is a matter of definition. It seems to me that the logic for presenting the screens in the order needed is a controller issue and I have seen some projects that use a rules engine to determine the order and what is required input from the user. This is not the same as business rules imho.
You guys are wrong the business rules live within the controller and not the model...

Resources