Where do you do your validation/business rules? - validation

I'm making a ASP.NET MVC application using EF4, using the Controller --> View Model --> Service Layer --> Repository --> Data Model (EF) approach.
My question is where does the business logic/validation live at?
Should I be making copies of the domain objects into view objects and validating there? Seems like a lot of extra work to duplicate the domain objects into objects for the view models.
I am using POCO's generated using the T4 templates.

Personally I put business validation logic (things like username is already taken, cannot wire money because of insufficient funds, ...) in the Service Layer and things like the username fields is required on the view model.

I actually like #Darin Dimitrov's method and this is what I'm currently using on my project. And in order to take advantage of displaying error messages just like you would do with using attributes, you can use a wrapper around the ModelState as explained in this article.

Related

Need help understanding MVC

To my understanding, MVC is a way to implement the separation of presentation tier from business and data tier. Am I understanding this correctly? If so, MVC should separate the business logic completely from presentation, right?
So to me it seems like javascript (or jquery) is somehow violating the MVC design since it takes over some of the logic on the client side, isn't it? Is model = data tier, controller = business tier, view = presentation tier? I think I have misunderstood the whole concept.
You seem to have a decent understanding of MVC. The trouble is that you are looking at two different potential MVC structures as one and the same. On the server, you can have data models, controllers, and views. On the client side, you can ALSO have data models, controllers, and views. If you want to look at your client side JavaScript as MVC, then jQuery is simply a utility that the view controllers can use to manipulate the view (the DOM).
Simply put, the client side doesn't always have to be only the view. If you use a web application client-side framework like Backbone, for example, then you can have models, views, and controllers all on the client side, which communicate with another, SEPARATE MVC structure on your server.
What you describe does actually pose a challenge for a lot of implementations. Frameworks such as the ASP.NET MVC Framework have been making attempts to auto-render JavaScript to the UI based on business logic in the middle tier (validation rules for form fields, primarily). But they're a long way off from having a truly compelling JavaScript user experience which doesn't repeat logic.
Personally, I like to think of the JavaScript as purely a UI concern. The application internally handles all of the logic. The JavaScript, as part of the UI, may duplicate some of that logic... but only for strictly UI purposes. Remember that the application should regress gracefully into a still-working state if the user has JavaScript disabled. That is, it should still use server-side (middle-tier) code to get the job done. All the JavaScript did was add a richer user experience to the UI layer.
JavaScript isn't the only culprit for this, either. Suppose you have a lot of validation logic in your middle tier defining what's valid or invalid for your objects. When you persist those objects to a database (which is on the periphery of the application just like the UI is), doesn't that database also contain duplicate validation logic? Non-nullable fields and such.
Congratulations! Your understanding of MVC is completely wrong. It has nothing to do with n-tier architecture (which is what you seem to be confusing it with).
The core idea of MVC is separation of concerns. This is used by dividing the application it two major layers:
model layer: contains all of the domain business logic and rules.
presentation layer: deals it user interface
The presentation then is further split into controllers (for handling the user input) and views (for dealing with response).
When applied to web applications, you either have MVC (or MVC-like) structure only on server-side, or, for larger and more complicated applications, you have separate MVC triads for both frontend and backend.
Also, when working with applications, the user of MVC is not human being, but the browser.
In latter case the backend acts like one data source for frontend application. An the whole frontend part of MVC is written in javascript.
P.S. In case if you are able to read PHP code, you can find a quite simple explanation of model layer in this answer. And, yes. It is the "simple version" because MVC is a pattern for enforcing a structure in large application, not for making a guesbook.
You can go to http://www.asp.net/mvc site and refer tutorials / samples to learn about MVC using Microsoft technologies.

Why Symfony2 doesn't have/like models?

I was looking for models in Symfony2 structure and bundles but there are none.
What is the reason Symfony2 do not have models?
Is MVC the wrong way to go?
I am just curious because I know that CodeIgniter in fact doesn't need to use models too. You can place everything in controllers or even in model in some scenarios ;).
Could somebody explain it more in depth?
That's because Fabien Potencier, the former of Symfony2, does not think Models belongs in Symfony. That's why he called it a HTTP framework instead. See also this article he wrote: "What is Symfony2?"
[...] you should know that Symfony2 is really about providing the tools for the Controller part, the View part, but not the Model part. It's up to you to create your model by hand or use any other tool, like an ORM. Of course, tight integration exists for the most well known ORMs like Doctrine2 and Propel; but they are optional dependencies. The Symfony2 core features do not and will never rely on any ORM.
The Doctrine2 ORM uses repositories to take over the control of mapping databases to a class. If you want to have custom methods in your repository, you can create your own repository. That means that a Repository can be seen as a sort of model.
Because they didn't want to.
Tough answer, but there is no set in stone way to program. There are many different methodologies and you can choose to follow them if you wish, but nobody is making you. In this case, the developers for Symfony2 decided models weren't necessary.
That doesn't mean MVC is wrong. I own a sedan, but if you own an SUV, does that mean you're doing it wrong? Just a different way to get the job done.
Because there are no "models" in proper MVC. Model is a layer. Just like presentation layer (which contains controllers, views and templates).
What you should be looking for instead are: services, mappers and domain objects. Those are the more common parts of model layer.

Implementing ecommerce analytics with MVC Razor

I am implementing various analytic tracking services in an MVC3 site (Google, Coremetrics) and researching if a custom HTML helper or partial view would work better given the following details:
-Code runs multiple sites and business logic is needed to change analytic service account Ids.
-The class must accept an object with order details to render the appropriate tags.
-The code must know which view is being rendered.
The solution I am working on includes am HTML helper base class that accepts the needed objects and is inherited by each provider's individual HTML helper. These helpers will live on the common layout. Is there a better way of implementing analytics on MVC and are partial views better suited since business logic is needed?
The GA analytics tracking code is pretty simple, we also use ASP.NET MVC3 but have just dropped the necessary code directly into our 'Order Complete' view.
There's no reason why you couldn't use an HTML helper instead though. I suggest not overly complicating your object model. Just use a single helper that has parameters matching the parameters used in the JavaScript.
You should be able to find examples of eCommerce tracking code, add parameters as appropriate, done. You might want to create another overload that pulls GA ID and domain name from the web.config as in the example as well, but still accepts the order details as parameters.

Managing Model Changes in ASP.NET MVC Razor Views

I am working on a business application which is being developed from scratch. We have opted to design our business logic using Entity Framework, and since the application has to be delivered on the Web we have selected MVC 3 (Razor) for presentation.
Things are pretty fine yet, but I am afraid how will I manage if anytime in the future we need to change our Entity Classes (like adding/removing fields in the business entities or adding more relational entities etc.). I know I can update my model by selecting "Update Model from Database" in Visual Studio (we are using Database first approach). In this case will I have to scrap my old views and generate new ones or is there any way I can update my exiting views.
That questions a little ambigous, so I'll talk about MVC concepts
The whole approach of MVC is "serperation of concerns" so you should be able to lititimatly change your Model (database, entity Framework, etc.) without updating your controllers or views.
That said your model's responsibillity is to return the data required by the controller/view. So it needs to be consistant. So if you model is bound to a view that return data x, if this view is updated, moved to a new platform, etc, etc then the model should still return the same basic information (for it to continue to work with your existing views/controllers).
If your using code first then you should be able to generate any required db views, etc. on a new db, providing this db supports code first generation (so basically MS-SQL I believe)
When using Editor- or DisplayFor you can pass in the entire model and it will show all the properties on the model.

Looking for way to reduce duplication of validation code in my View Models and Logical Layer

Right now the application being built by our team uses the built in MVC attributes and a few home baked ones to validate the View Models. Because of best practice design principles, we have placed those same rules in the Logical Layer. This has unfortunately caused duplication of validation code.
In MVC3 at least, if JavaScript is disabled, these same attributes will still perform the validation they are meant to, so transforming a View Model in to a DTO and asking the Logical Layer to validate it is not an option because this process would have already been done by the framework.
I have not found the following SO post to be of any help. I have used MS Enterprise Library and the API did not sit well with our team.
Good practices for avoiding validation logic duplication when working with both domain objects and view models in ASP.NET MVC
I'm thinking that the best way to do this is to have the validation attributes bound at runtime to specific properties and have a dependency injection container do this. Is this possible or is there a different approach we could take?
You are asking for multiple validation types to be performed here.
You want client validation (it seems) and some other business validation layer.
If thats the case the only choices as I see it are:
duplicate the code (ya I know Im listing options)
1a. use data annotations on your objects for client validation. Business layer validation happens however you define, and separate as a final check. If you use for instance the entity framework's fluent API this is a standard route.
client side validation is just that - helpers for client side. domain validation will happen upon save. This is ideally the more powerful approach, but isn't as friendly when your domain objects don't match property names on your view models, so you need to map domain errors to view model property errors which normally isnt too bad but can get iffy.
implement IValidteableObject (and rid of client validation). This validation logic is then called from your logical layer and the model binder.
You can inject code for validation, but its not pretty and Im not sure how reusable it is outside the MVC validation route.
There may be other ways beyond this, but those are the main options as I see it.
One way of seeing it is: If your api is your mvc application and the validation is already done by the point you are executing your business rules, you can just assume they are valid. It's input validation, of course is something related to your domain but... if you change the way of thinking, your domain expects valid data and assumes you did your homework before using the business rules.

Resources