How can I attach UI layer resource files to domain model data annotations? - asp.net-mvc-3

This question really has larger architectural implications and I welcome any input or suggestions on this:
I'm more of the Martin Fowler school of thought when it comes to OOP. I believe you should be able to directly render domain entities in the UI. If I have a Car entity, I should be able to render it to a webpage. The domain model is a crosscutting concern and not a layer. Treating the domain model as a layer leads to an anemic domain model. I don't believe in DTOs in an OOP architecture.
A view model for me is a way of composing the domain entities required in your view. It's not a DTO. I don't understand what the reasoning behind using a view model like DTO is though it seems like a common thing to do using automapper?
So using the metadata approach I put data annotations on my domain model to give any UI implementation hints on how to render and validate the entities. I like to have a richER domain model.
In MVC3 how can you accomplish this (specifically using the Display data annotation) with a resource file that resides in the UI layer? Is there a native implementation for this or do I need to get creative myself? Or have I gone wrong somewhere in my approach?

I disagree.
For one thing, some of the attributes you will use to specify how an entity property should be displayed on a web page come from the System.Web namespace, not the System.ComponentModel.DataAnnotations namespace. By putting these attributes on properties in your domain model, your domain model is taking a dependency on System.Web. For example, there is the [HiddenInput] attribute that tells MVC3 to render a field as input type="hidden". This is not in System.CompoenentModel.DataAnnotations.
Secondly, I don't believe you need data annotation attributes on your entity properties to have a rich domain model. A rich domain model comes from classes that wrap knowledge in a context. The client application should not need to know anything about the domain in order to use it. You achieve a rich domain model with classes, methods, and properties that describe knowledge using the ubiquitous language. DataAnnotations attributes don't lend themselves well to the ubiquitous language imo. And, your domain is more than just your entities. There are factories, services, and other patterns that you can use to build a rich domain model. A domain with only entities and metadata sounds anemic to me.
Thirdly, you may have an entity that should be rendered in different ways on your web site. When someone searches for a car, you may want to display just the make, model, year, and thumbnail photo. When someone clicks on the search result, you may want to display multiple photos, reviews, etc. If you were to use the UIHint attribute on an entity to tell the web ui how to render the car, you wouldn't be able to have different strategies for rendering the Car in different contexts.
Finally, yes, automapper is really great for DTOing your entities into viewmodels. It essentially lets you populate copies of the entity, disconnected from the domain, targeted for specific UI concerns. Here it is safe to use HiddenInput and UIHint attributes to tell MVC3 how to render data.
Response to comment 1
As far as UIHint, I mentioned it here because it has a special meaning with MVC3 EditorTemplates. In cases where a partial view involves receiving input, what is the composition of the view? Text fields, drop-down lists, and input elements that often correspond to entities and their properties in some aggregate root. You will therefore need some representation of the entities to encapsulate the data. Your DTO can be an aggregate root as well, with depth. You can have a root DTO with scalar properties (text/date/bool), navigation properties (drop-down list) and collection properties (ul/ol/table).
We create a corresponding viewmodels for many entities in an aggregate root, and implement them as views using EditorTemplates. If we ever want to switch to a different EditorTemplate, we can apply UIHint to a viewmodel property. Thus we can tell it to "render a location dto as a google map". Automapper can map navigational and collection properties to corresponding viewmodels, forming as complex a representation of your domain entities as you need for the user.
Forgive me if I misunderstand what you mean by flat dto.
Response to comment 2
A viewmodel dto can flatten out / denormalize some properties (using automapper), if your requirements call for it. For example, consider a University entity. It may have many names in many languages (translations), hinting at a UniversityName entity in the aggregate, with University having a collection of Names (1..n). Of those names, 1 may represent the OfficialName / NativeName, and another may represent the TranslatedName to the user's CurrentUICulture. Other entities in the collection may represent TranslatedNames that the user does not understand, and need not be bothered with.
If you have a view that is only interested in these 2 Names in the collection, you can promote them to first-class properties on the viewmodel:
public class UniversityViewModel
{
public string OfficialName { get; set; }
public string TranslatedName { get; set; }
// ...other properties
}
This is a case where denormalizing part of the entity when converting to a viewmodel dto can make sense. Notice how the viewmodel is anemic -- a bare container for data transfer from a controller to a view. This is perfectly fine, and in fact, encouraged.
Answer to original question
To answer your original question, it helps if you think of your domain model & entities as a layer -- more specifically, a bottom layer. Layered software is easier to understand if you think about the various concerns in an application as having dependencies on other concerns. MVC3 is a presentation / UI layer, and will have dependencies on the layers beneath it -- one of those being your domain layer.
If you want to access a resource file in the UI from the domain layer, you are going in the opposite direction. You would be making a low layer depend on a higher layer. If your domain lib depends on the UI lib for a resource, and the UI lib depends on the domain for entities, you end up with a circular dependency. I think you could probably accomplish it using reflection if you needed to, but in that case, you would be fighting against the framework. MVC and .NET in general may not be the best choice for you if that is the case.
I actually think of resource files as a cross-cutting concern. Our application has i18n sprinkled throughout, and often we find we need the same language text resources in both the domain and the UI.
There is nothing wrong with putting a Display attribute on an entity. But if you want to use resources for it, then either put that resource in the domain layer, or if you feel it doesn't belong there, in a lower layer. That way it can be accessed by both the domain and the UI.

So I ended up putting a resourse file in the domain model and added a custom HiddenFieldAttribute so that I don't have to reference the MVC assembly in the domain model.
I still fundamentally dissagree that a view model is really a DTO and that the domain model should be constructed as a layer. I feel that architecting the application in this way creates abstractions that really have no value. If the domain model was truly a layer then we would build a set of logical interfaces from which to access it, and this we don't do. It's a cross cutting concern.
Thanks to olivehour for an interesting discussion and suggesting that it's okay to place resource file(s) in to domain model assembly.

Related

Working with Breeze + ViewModels

In my app I have my domain layer and web interface (other layers I will not go into details).
My views, working with ViewModels objects, and the database persist domain objects.
To convert a ViewModel object to a domain object I use AutoMapper.
The problem with the working Breeze is that when I will create a new object var newCust = manager.createEntity('Customer', {name:'Beta'}) this is a domain object, and should be an ViewModel object.
Not all, but in some cases the ViewModel is not similar to the object domain. For example, collections of objects in the domain are: ICollection<Person> while in view model are ICollection<int> int is a PK of person.
Question
How to working with breeze in these cases?
How to make the metadata also manages the structure of my viewmodels so I can create objects of type my ViewModel?
#ridermansb - Because you mentioned AutoMapper, I will assume that your mapping is taking place on the server. You want your server API to expose "ViewModels" (in this case you might call them DTOs) rather than the domain model objects. Sometimes your ViewModels mirror your domain objects exactly; sometimes they don't.
Your client only sees what your API exposes. If this is a BreezeJS client, you will likely treat the ViewModels as client-side entities. They are Breeze entities in the sense that you expect Breeze to query, cache, change-track, and validate them. BreezeJS doesn't know whether these "entities" correspond to server-side DTOs or server-side business objects.
Of course if you're using DTOs/ViewModels, your server code is responsible for translating between the DTO form and the domain object form. Presumably this logic lies somewhere in/between the server-side API layer and the domain layer.
If you have chosen this architecture, you have chosen to deal with the bi-directional translation between ViewModels and domain objects and have embraced all the complexity and hassle that entails. I have no words of advice for you on that score.
So let me rephrase and narrow your question: "How can I get metadata that describe the object model exposed by my server-side API?"
My favorite way (assuming a .NET server) is to let EF do it for me. I create a DbContext that references NOT my domain model classes but rather my ViewModel/DTO classes. Of course these classes would not actually map to a real database. No problem; they don't have to. You will never use this DbContext to access data. You will only use it to generate metadata. You are using EF as a design-time, metadata-generating tool ... and that's it. This is an efficient maintainable approach.
I hope to demonstrate this technique "soon" but I've been mighty busy recently so no promises.
Alternatively, you can write the metadata by hand as described here.

MVC viewmodel redundancy

Wouldn't creating ViewModels lead to redundancy? In the sense I have my domain model and I need to display the data from it on a view. So we create ViewModels, add DataAnnotations to it and display it on the View. At this point I have 2 object with almost identical data.
As others have already said, only the most trivial application can get away with passing their domain models directly to the view. Even then, it's still not a good idea for a lot of reasons.
The requirements of your view are different from the requirements for your data model. For instance, you may have a field that is required in your view, but is nullable in your vie model. If you add a `[Required]' attribute, then your model will now consider this field non-nullable.
However, my single biggest reason for never using domain models in views is for security. MVC allows you to post any value to it, and the default model binder will happily plug values you post into the model, which means if you had an IsAdmin flag, and someone posted a true value for IsAdmin, then when you saved the changes to the model, someone is now an admin.
The first rule of web security is never trust input from the user, and passing your view models directly to the view basically gives up sanitizing your data.
Yes, it is a form of redundancy. But redundancy is often required to achieve other goals. In case of Models, having this separation of view models and domain models helps in achieving a decoupled setup between your view and data-store. And it is not often that ViewModels are exact copies of Domain.
Which means, either can change without having an impact on other. I can see cases where this would be valuable - data-type changes in table need not call for deployment of the web application.
So, in summary, while there is redundancy, it is a design choice on whether the system is complex enough to benefit from this redundancy.
In 99% cases ViewModels don't lead to redundency.
The only 1% which comes to my mind is simple application with anemic domain models and pages, which shows nothing but a single model on a page. This is peculiar to content management pages.
In any other case:
1) your ViewModels will join information from multiple domain models
2) you'll have a logic specific to your domain in domain models
3) it's not a good idea to mix view-specific metainformation like DataAnnotations into your domain
Nope, using ViewModel has its own purpose. Let's think about a situation when your view has two or more Entities from the Domain Model, without a ViewModel, how are you gonna organize data? The data needed for a view sometime is not exactly like domain model, it can has
less or more information and sometime we have to pre-process data from domain before rendering view(e.g. format date time depends on client's culture).
Furthermore, ViewModel help de-couple the Web UI from the domain layer. Entities in Domain Model is not just about data representation(which is the only purpose of view model), they also have operations that mimics the business rule, you don't want expose too much domain knowledge to the UI layer who doesn't need to know.

Zend Framework / MVC: What type of objects to push to the View?

Hey guys - here's a question on Zend Framework or better on MVC in general:
I am asking myself for a quiet a long time now, if it is a good idea to push business objects (User, Team, etc.) to my views or if it would be better just to push dump data containers such as arrays to the view for rendering.
When pushing business objects to my view I have a much tighter coupling between the views and my domain model, however, the view could easily do things like foreach($this->team->getUsers() as $user) { ... } which I personally find very handy.
Providing domain model data in dumb arrays to me looks more robust and flexbile but with the costs of that the view cannot operate on real objects and therefore cannot access related data using object's method.
How do you guys handle that?
Thanks much,
Michael
It's better to make your View access a Domain Model object in an object-oriented manner, instead of using the Controller to convert Model data into plain scalars and arrays.
This helps to keep the Controller from growing too fat. See the Anemic Domain Model anti-pattern. The Controller only needs to know what Model to instantiate, passes the request inputs to that Model, and then injects the Model into the View script and renders. Keep in mind that a Domain Model is not a data-access class.
You can also write View Helpers to encapsulate a generic rendering of a Domain Model object, so you can re-use it in multiple View scripts.
Your View should accesses the Domain Model only in a read-only manner. View scripts should not try to effect changes to the Domain Model.
You can also design your Domain Model to implement ArrayObject or other SPL type(s), as needed to make OO usage easy in the View script.
It's true, a large driving motivation of MVC and OO design in general is decoupling. We want to allow each layer to remain unchanged as the other layer(s) are modified. Only through their public APIs do the layers interact.
The ViewModel is one solution to abstract the Model so that the View doesn't need to change. The one I tend to use is Domain Model, which abstracts the details of table design, etc. and supplies an API that is more focused on the business rather than the data access. So if your underlying tables change, the View doesn't have to know about it.
I would expect that if there's a change to the Domain Model, for instance it needs to supply a new type of attribute, then it's likely that your View is changing anyway, to show that new attribute in the UI.
Which technique you choose to decouple one layer from the others depends on what types of changes you expect to be most frequent, and whether these changes will be truly independent changes, or if they will require changes to multiple layers anyway.
The "standard" approach would be to completely prepare the model in the controller (e.g. fetch all teams, including users) and then send that to the View for presentation, but you are not bound by that. The data structures can be whatever you want it to be: Array, ArrayObject or custom Classes - anything you deem appropriate.
I dont use Zend framework, so this is in repsonse to the general MVC Have a look at the ViewModel pattern.
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
I'm comming from a .Net MVC point of view but I believe the concepts will the same.
I will do all my view rendering in the controller bascially like below
model only output dataset/objects (this should contain the most code)
controller assign view and add necessary HTML and make use of models
view only contains placeholder and other presentation stuff and maybe ajax call
So my team can work on each part without interrupting each other, this also add some information security to the project i.e no one can retrieve all the working code they only communicate by variables/object spec.

What exactly is the model in MVC

I'm slightly confused about what exactly the Model is limited to. I understand that it works with data from a database and such. Can it be used for anything else though? Take for example an authentication system that sends out an activation email to a user when they register. Where would be the most suitable place to put the code for the email? Would a model be appropriate... or is it better put in a view, controller, etc?
Think of it like this. You're designing your application, and you know according to the roadmap that version 1 will have nothing but a text based command line interface. version 2 will have a web based interface, and version 3 will use some kind of gui api, such as the windows api, or cocoa, or some kind of cross platform toolkit. It doesn't matter.
The program will probably have to go across to different platforms too, so they will have different email subsystems they will need to work with.
The model is the portion of the program that does not change across these different versions. It forms the logical core that does the actual work of whatever special thing that the program does.
You can think of the controller as a message translator. it has interfaces on two sides, one faces towards the model, and one faces towards the view. When you make your different versions, the main activity will be rewriting the view, and altering one side of the controller to interface with the view.
You can put other platform/version specific things into the controller as well.
In essense, the job of the controller is to help you decouple the domain logic that's in the model, from whatever platform specific junk you dump into the view, or in other modules.
So to figure out whether something goes in the model or not, ask yourself the question "If I had to rewrite this application to work on platform X, would I have to rewrite that part?" If the answer is yes, keep it out of the model. If the answer is no, it may go into the model, if it's part of the essential logic of the program.
This answer might not be orthodox, but it's the only way I've ever found to think of the MVC paradigm that doesn't make my brain melt out of my ear from the meaningless theoretical mumbo jumbo that discussions about MVC are so full of.
Great question. I've asked this same question many times in my early MVC days. It's a difficult question to answer succintly, but I'll do my best.
The model does generally represent the "data" of your application. This does not limit you to a database however. Your data could be an XML file, a web resource, or many other things. The model is what encapsulates and provides access to this data. In an OOP language, this is typically represented as an object, or a collection of objects.
I'll use the following simple example throughout this answer, I will refer to this type of object as an Entity:
<?php
class Person
{
protected $_id;
protected $_firstName;
protected $_lastName;
protected $_phoneNumber;
}
In the simplest of applications, say a phone book application, this Entity would represent a Person in the phone book. Your View/Controller (VC) code would use this Entity, and collections of these Entities to represent entries in your phone book. You may be wondering, "OK. So, how do I go about creating/populating these Entities?". A common MVC newbie mistake is to simply start writing data access logic directly in their controller methods to create, read, update, and delete (CRUD) these. This is rarely a good idea. The CRUD responsibilities for these Entities should reside in your Model. I must stress though: the Model is not just a representation of your data. All of the CRUD duties are part of your Model layer.
Data Access Logic
Two of the simpler patterns used to handle the CRUD are Table Data Gateway and Row Data Gateway. One common practice, which is generally "not a good idea", is to simply have your Entity objects extend your TDG or RDG directly. In simple cases, this works fine, but it bloats your Entities with unnecessary code that has nothing to do with the business logic of your application.
Another pattern, Active Record, puts all of this data access logic in the Entity by design. This is very convenient, and can help immensely with rapid development. This pattern is used extensively in Ruby on Rails.
My personal pattern of choice, and the most complex, is the Data Mapper. This provides a strict separation of data access logic and Entities. This makes for lean business-logic exclusive Entities. It's common for a Data Mapper implementation to use a TDG,RDG, or even Active Record pattern to provide the data access logic for the mapper object. It's a very good idea to implement an Identity Map to be used by your Data Mapper, to reduce the number of queries you are doing to your storage medium.
Domain Model
The Domain Model is an object model of your domain that incorporates behavior and data. In our simple phone book application this would be a very boring single Person class. We might need to add more objects to our domain though, such as Employer or Address Entities. These would become part of the Domain Model.
The Domain Model is perfect for pairing with the Data Mapper pattern. Your Controllers would simply use the Mapper(s) to CRUD the Entities needed by the View. This keeps your Controllers, Views, and Entities completely agnostic to the storage medium. This also allows for differing Mappers for the same Entity. For example, you could have a Person_Db_Mapper object and a Person_Xml_Mapper object; the Person_Db_Mapper would use your local DB as a data source to build Entities, and Person_Xml_Mapper could use an XML file that someone uploaded, or that you fetched with a remote SOAP/XML-RPC call.
Service Layer
The Service Layer pattern defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation. I think of it as an API to my Domain Model.
When using the Service Layer pattern, you're encapsulating the data access pattern (Active Record, TDG, RDG, Data Mapper) and the Domain Model into a convenient single access point. This Service Layer is used directly by your Controllers, and if well-implemented provides a convenient place to hook in other API interfaces such as XML-RPC/SOAP.
The Service Layer is also the appropriate place to put application logic. If you're wondering what the difference between application and business logic is, I will explain.
Business logic is your domain logic, the logic and behaviors required by your Domain Model to appropriately represent the domain. Here are some business logic examples:
Every Person must have an Address
No Person can have a phone number longer than 10 digits
When deleting a Person their Address should be deleted
Application logic is the logic that doesn't fit inside your Domain. It's typically things your application requires that don't make sense to put in the business logic. Some examples:
When a Person is deleted email the system administrator
Only show a maximum of 5 Persons per page
It doesn't make sense to add the logic to send email to our Domain Model. We'd end up coupling our Domain Model to whatever mailing class we're using. Nor would we want to limit our Data Mapper to fetch only 5 records at a time. Having this logic in the Service Layer allows our potentially different APIs to have their own logic. e.g. Web may only fetch 5, but XML-RPC may fetch 100.
In closing, a Service ayer is not always needed, and can be overkill for simple cases. Application logic would typically be put directly in your Controller or, less desirably, In your Domain Model (ew).
Resources
Every serious developer should have these books in his library:
Design Patterns: Elements of Reusable Object-Oriented Software
Patterns of Enterprise Application Architecture
Domain-Driven Design: Tackling Complexity in the Heart of Software
The model is how you represent the data of the application. It is the state of the application, the data which would influence the output (edit: visual presentation) of the application, and variables that can be tweaked by the controller.
To answer your question specifically
The content of the email, the person to send the email to are the model.
The code that sends the email (and verify the email/registration in the first place) and determine the content of the email is in the controller. The controller could also generate the content of the email - perhaps you have an email template in the model, and the controller could replace placeholder with the correct values from its processing.
The view is basically "An authentication email has been sent to your account" or "Your email address is not valid". So the controller looks at the model and determine the output for the view.
Think of it like this
The model is the domain-specific representation of the data on which the application operates.
The Controller processes and responds to events (typically user actions) and may invoke changes on the model.
So, I would say you want to put the code for the e-mail in the controller.
MVC is typically meant for UI design. I think, in your case a simple Observer pattern would be ideal. Your model could notify a listener registerd with it that a user has been registered. This listener would then send out the email.
The model is the representation of your data-storage backend. This can be a database, a file-system, webservices, ...
Typically the model performs translation of the relational structures of your database to the object-oriented structure of your application.
In the example above: You would have a controller with a register action. The model holds the information the user enters during the registration process and takes care that the data is correctly saved in the data backend.
The activation email should be send as a result of a successful save operation by the controller.
Pseudo Code:
public class RegisterModel {
private String username;
private String email;
// ...
}
public class RegisterAction extends ApplicationController {
public void register(UserData data) {
// fill the model
RegisterModel model = new RegisterModel();
model.setUsername(data.getUsername());
// fill properties ...
// save the model - a DAO approach would be better
boolean result = model.save();
if(result)
sendActivationEmail(data);
}
}
More info to the MVC concept can be found here:
It should be noted that MVC is not a design pattern that fits well for every kind of application. In your case, sending the email is an operation that simply has no perfect place in the MVC pattern. If you are using a framework that forces you to use MVC, put it into the controller, as other people have said.

MVC: Data Models and View Models

I've read some MVC advice in the past regarding models stating that you should not reuse the same model objects for the domain and the view; but I haven't been able to find anyone willing to discuss why this is bad.
It is my opinion that creating two separate models - one for the domain, one for the view - and then mapping between them creates a lot of duplication, plus tedious mapping code (some of which might be alleviated by things like AutoMapper) that will likely be error prone.
What makes having a separate model for the two concerns worth the trouble of duplication and mapping code?
At its heart, two models is about Separation of Concerns. I want my View to work off of a single Model. I want my Domain Model to represent the conceptual model I build with the domain experts. ViewModel often has technical constraints. Domain Model is about POCO, and not being bound by technical constraints of either data shown (View) or persisted (in a DB or otherwise).
Suppose I have three entities shown on a screen. Does that mean I need to force a relationship between the three? Or just create a ViewModel component object that contains all three items. With a separate ViewModel, View concerns are separated from my domain.
why? 'cause the view shouldn't have the ability to use the model object!
Imagine you pass the project to a web designer to do the view layer. Suddenly he/she has the ability to mess around with your application's data through the model layer. That's not good.
So always only pass the data the view needs, instead of the object with methods.
J.P. Boodhoo's article Screen Bound DTOs will help you understand the design benefit.
There is also a security benefit that I have written about.
Having a presentation model simplifies your views. This is especially important because views are typically very hard to test. By having a presentation model you move a lot of work out of the view and into the domain->presentation model. Things like formatting, handling null values and flattening object graphs.
I agree that the extra mapping is a pain but I think you probably need to try both approaches in your specific context to see what works best for you.
There are even plainer concerns including the view model's ability to be specially formatted and certainly null-safe.
I guess the idea is that your domain models might extend to other implementations, not just your MVC application and that would break the seperations of concerns principle. If your View Model IS your domain model then your domain model has two reasons to change: a domain change requirement AND a view requirement change.
Seems I have duplication of rules as well.
ie. client object validation on the UI, then mapping to domain object that has to be validated.
What I tend to do however is map my set of domain objects to create a model - ie. a webpage that shows customer info, stock info, etc... my model becomes a structure that holds a Customer object and a Stock object.
CompanyPageModel
public Customer Customer{get;}
public Stock Stock {get;}
then in my mvc project ViewData.Model.Customer.Name ViewData.Model.Stock.CurrentStocks
Separation 'seems' like more work, but later, it's good to have this division of UI/Domain model...sorta like writing tests :)
I have drunk the cool-aide finally, I do like being able to mark my viewmodel with display instructions and have that all auto wired up.
What I demand now is some kind of auto generator of viewmodels from poco entities. I always set some string as an int and it takes me forever to find it. Don't even think of doing this without automapper unless you like pain.

Resources