ASP.Net MVC 3: Custom data binder to transform data coming from/going to the DB - asp.net-mvc-3

I am working on an ASP.Net MVC 3 project where I would like to encrypt all emails stored in a database for additional protection in case some hacker would ever get access to the db, and I was wondering what was the best way to achieve this.
I read a bit about custom model binders, but this is for the binding between the controller and the view. I am not sure if this is what I want, since I may need to have access to unencrypted email addresses in the code (in the Service Layer, where I have the Business Rules). So I would have preferred the encryption/decryption to occur automatically when the model is saved to/loaded from the database, and this is what I don't know how to do.
We can imagine that I have this POCO model:
public partial class Contact
{
public virtual int ContactId { get; set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
}
What I need is a way to have the Email property encrypted when it is persisted to the database and decrypted when it is loaded from the database.
One way to do it would be to have an extra UnencryptedEmail property in my Contact model that would have a getter and a setter that would decrypt and encrypt the Email property, but I find that having to add an extra property is not as clean a solution.
If, for some reason, using a custom IModelBinder is the way to go, please let me know why and tell me how to get it to be applied only on the Email property of the Contact model. Up to now, I have only seen implementations for applying transformations on all properties of a specific data type.

Consider using the Model View approach instead of directly binding to models and displaying them in the Views.
As for encryption and decryption there are tons of approaches you can employ.

I can see what you are looking for, instead of answering and explaining the whole stuff, I can point you to a related material which is not exactly what your requirement is but you can take a cue from it.
http://codefirstmembership.codeplex.com/
In the above code first membership provider code, the passwords are hashed and stored in database and for comparison the hashing is removed and then they are compared.
I understand it will be time consuming but its worth to take a look at.

I don't think the model binder is the right way to go. The encryption of an email sounds like a business requirement and as such I would place it in the business layer.
When storing the email, your business layer would get the plain email address as input from the application layer, encrypt it and pass the encrypted value to the repository.
When retrieving the email, your business layer would receive the email in an encrypted state from the repository, decrypt it and pass it back to the application layer.
Unless you require it, the application layer would not need to know about the encrypted version of the email as it only deals with the plain version of it. On the other end the repository would not need to know about the decrypted version of the email as it only needs to deal with the encrypted version of it. To that end the business layer does sound like the best place to handle this.

Related

ASP.NET WEB API 2: Role or Claim dependent model validation

I have a unique requirement that I'm not sure how to handle. We are working with an underlying repository that allows for a quite a bit of flexibility with regards to parameters. The Controller services are injected as "service" objects into a "Service" Property for our controller classes and they wrap the calls to entity framework.
eg.
public UserController:ApiController{
public IUserSvc Service {get;set}
public UserController(IUserSvc service){
this.Service=service;
}
}
This part is handled by Autofac and all is well here.
Next, we have the standard GET,POST,PUT,DELETE,PATCH methods in the controller that accept a SINGLE user model. In other words, there is only ONE user model that is ever used, and therein lies the problem.
While the underlying service class just handles the passing of data back and forth, it pushes the requirement of the granular control of validation up the pipe. This isn't abnormal to me.
Given that we have a single API that uses models with validation attributes, we've run into an issue where different apps that call into the api require different types of validation. The model structure is fine. It's just that some properties, depending on "who you are" and what HTTPMethod is sent, either are or are not validated.
ex:
public class User{
public int UserID {get;set}
public string Name {get;set;}
}
Let's take 2 scenarios:
1. Basic User
2. System User
As a basic user, UserID is required for: GET, PUT,PATCH ( and technically delete too but it's not used). It is not required for POST because that would be creating their own user.
As a system user, UserID is NOT required in GET but is required in PUT, PATCH, DELETE.
So I am having a hard time trying to figure out how to do this without making one api for Basic User with their own models and one for System User.
I wanted to keep this high in the pipe so I wasn't doing this in the controller api methods, i.e. Check roles/claims, create/cast/or otherwise map bound model to specific concrete model per role/claim and then run validation and THEN return model binding errors if any. That's a lot of gunk in the method and I would prefer this to be on an attribute of the method or api controller.
Is there any way to do a type of model binding and or model validation based on "who you are"? That could be by role or claim?

Entity Framework in detached mode with MVC application

I have started working out with Entity Framework (EF) for an MVC n-tier application. It would seem that very obvious that this being a web application (which is stateless), I would have to use detached object models. There is no ambiguity with doing an Add operation. However when doing an edit there are here are two ways
Fetch the original object in context, attach the updated object and
then save to database. Something like mentioned in answer to this
question
EF4 Context.ApplyCurrentValues does not update current values
Set individual modified properties explicitly using the IsModified property of individual fields of the object like
mentioned in this article
http://msdn.microsoft.com/en-us/data/jj592677.aspx
Method 1 has disadvantage of having to load object into memory from database each time an update needs to be performed.
Method 2 would require having to manually pass which fields to be set as IsModified to true from wherever the object an be updated. So for e.g. for each object, I may need to create a boolean collection object for each field of the object.
e.g.
SaveEntity(EntityClass e, EntityStateClass ec)
{
context.Entry(e).Property("Name").IsModified = ec.NameState;
context.SaveChanges();
}
class EntityStateClass{ public bool NameState;}
I would prefer method 2 simply for the sake of performance but I am hindered by the n-tier architecture and repository pattern I am using. My Repository interface restricts save method for any object to be
SaveEntity(EntityClass e);
So I cannot pass the "state" object. Context class is not available and should not be available outside DAL. So I cannot set property outside. Is there any "proper" way to achieve this ?
Note: Self-Tracking Entity is also out of question since I cannot send entities with state to client (the browser) since I am intent on keeping the html lightweight.
EDIT: After a lot of thinking, I am trying to use following mechanism to keep track of modified state for each field in my domain class
Declare a partial class for entity class.
For each field that is updateable, declare a boolean property like "IsModified_FieldName"
Set the "IsModified_FieldName" property when the field is set.
However for this I need Entity Framework to generate explicit properties for me instead of implicit properties that it auto-generates. Does EF provide an handle to do this ?
Here is sample code of what I am trying to achieve
//Save Method for class EntityClass.
SaveEntity(EntityClass e)
{
context.Entry(e).Property("Name").IsModified = e.IsModified_Name;
context.SaveChanges();
}
//EntityClass is class autogenerated by EF
public partial class EntityClass
{
//This is auto-generated property by EF
public string Name {get; set;}
/* This is what I would like EF to do
private string name;
public string Name
{
get {return Name;}
set {
name = value;
//this is what I would like to do
this.IsModified_Name = true;
};
}
*/
}
//This is another partial definition for EntityClass that I will provide
public partial class EntityClass
{
//This property will be set to true if "Name" is set
public bool IsModified_Name {get; set;}
}
PS: It seems the information I have provided is not sufficient and therefore there are no responses.
I am using DbContext (Database first model)
EF auto-generates the class files for me. So each time I update my database, the class files are regenerated.
To your concrete question: The entities are generated by a T4 template and it should be possible to modify this template (which is in text format) to generate the entities in a way you want to shape them.
But I have a few remarks about your concept:
In a web application data are usually changed by a user in a browser. To have a definite knowledge what really has been changed you need to track the changes in the browser (probably by some Javascript that sets flags in the data (a ViewModel for example) when a user edits a text box for instance).
If you don't track the changes in the browser what happens? The data get posted back to the server and you don't know at the server side (with MVC in a controller) which property has been changed. So, your only chance is to map all properties that has been posted back to your EntityClass and every property will be marked as Modified, no matter if the user really did a change or not. When you later call SaveChanges EF will write an UPDATE statement that involves all those properties and you have an unnecessary overhead that you you want to avoid.
So, what did you win by setting individual properties instead of setting the whole entity's state to Modified? In both cases you have marked all properties as Modified. Exceptions are partial changes of an entity, for example: You have a Customer entity that has a Name and City property and a view that only allows to edit the Name but not the City and a corresponding ViewModel that only contains a Name property. In this case your procedure would only mark the Name property of the Customer entity as Modified but not the City. You might save here a little bit because you don't save the City property value to the database. But you still save the Name even if it didn't change.
If you use solution 1 (ApplyCurrentValues) you have to load the entity first from the database, yes, but it would only mark the properties as Modified that really changed compared to their values in the database. If the user didn't change anything no UPDATE would be written at all.
Keep in mind that you are only at the beginning to implement your concept. There are other changes to the data that can happen in the browser than only scalar property changes, namely relationship changes. For example a user changes the relationship from an Order to a Customer or you have a view that has an Order and a collection of OrderItems and the user cannot only edit the Order header but also edit the OrderItems and remove and add new OrderItems. How do you want to recognize when the data come back from the browser to the server which collection item has been added and which has been removed - unless you track all those changes in the browser and send tracking information back to the server in addition to the actual data or unless you reload the Order and OrderItems from the database and merge the changes into the original entities from the database?
Personally I would vote for option 1 for these reasons:
You can use real POCOs that don't carry additional tracking information. (BTW: I have some doubt if you aren't reinventing the wheel by implementing your own tracking that EF change tracking proxies provide out of the box.)
You don't need to track changes in the browser which can become quite complex and will require Javascript in every Edit view to write change flags into hidden form fields or something.
You can use standard features of EF without having to implement your own tracking.
You are required to load entities from the database when you want to update an entity, that's true. But is this the real performance bottleneck in a web application where data have to run through the wire back and forth (and reflection (which isn't really known as to be fast) is involved by the model binder)? I have nothing said if your database is remote from the web server and connected by a 9600 baud modem. But otherwise, your plan is not only premature optimization, it is kind of premature architecture. You are starting to build a potentially complex architecture based on "it could be slow" to solve a performance problem that you actually don't know of whether it really exists.

CompareAttribute and comparing against properties on a complex type

I've just read about MVC3's new CompareAttribute that you can apply to a model's property to define another property that it should match - the classic use case is confirming email address has been entered correctly, or having a Password and ConfirmPassword field. I've run into a problem with trying to implement it in my own project.
We've got a fairly standard User object which, among other things, has these properties:
public class User {
....
[Required, RegularExpression(RegularExpressions.Email, ErrorMessage = "Please supply a valid email address")]
public string EmailAddress
[Required]
public string Password
....
}
I've then incorporated User and a couple of other objects that we need into a view model:
public class SignUpViewModel {
....
public User user { get; set; }
....
}
Which, when passed to the form in the UI, allows the ModelBinder to run the Data Annotation validation for the User object as well as the other objects and primitive types in SignUpViewModel when the user submits the form. I was really pleased when this all "just worked" because it meant that we could define validation in just one place and not have too much work to do in persisting out to the database or map UI models to domain models etc.
Noticing that the Html.EditorFor(model => model.User.Password) emits an with the name set to "User.Password", I added the following to SignUpViewModel:
[Required, Compare("User.Password")]
public string ConfirmPassword { get; set; }
but submitting the form now triggers a validation error along the lines of "Could not find a property named User.Password". I was hoping that it would follow the same kind of convention, but it would appear not :(
I don't really want to put ConfirmPassword into the User object as ConfirmPassword is purely a UI concern, and it seems wrong to have that in a domain object like that. I also don't really want to flatten out the various objects within SignUpViewModel as that starts to feel like duplication of where validation rules are defined, and we're trying to keep our code as DRY as possible.
Has anyone come across a way to get CompareAttribute working with comparing against properties of sibling objects rather than sibling properties as it would appear the attribute expects to?
Get rid of the User property on your SignUpViewModel and put the necessary properties from the User domain object on the SignUpViewModel.
You said you want your concerns separated, and having a domain object as a property on the view model is an example of not having your concerns separated.
This might seem like it could result in your writing more code, but look into a solution like Automapper to automate mapping your domain object properties to view model properties.
Even though smartcaveman's response is great from the architectural standpoint it does not address the original question about inability to leverage CompareAttribute's client-side validation in MVC3 inside models contained within some parent model (complex model). I know of a situation where some reusable [sub]model can be reused from within several parent container models and CompareAttribute is used inside the submodel. The server-side validation in MVC3 will work just fine (when javascript is disabled on the client), but there is a bug in javascript provided by Microsoft that breaks client-side validation. Please follow the link below for the resolution:
MVC3 CompareAttribute Client-side Bug (stackoverflow)
I recently ran into this problem myself; here's how I solved it.
[Compare("OriginalPassword")]
public string ConfirmPassword { get; set; }
public string OriginalPassword
{
get
{
return User.Password;
}
}

Where to store feedback UI data in ASP.NET MVC 2?

I'm really new to both ASP.NET MVC and the MVC pattern generally.
For context, I'm currently running .NET 4.0, MVC 2.
I know that MCV 2 has a bunch of built in features for:
validation (both client and server side, through a variety of ways)
error handling (via attributes and other methods)
But what should be used to return feedback to the user that is neither an error nor validation?
For example, I have a simple form that returns a csv (using myController.base.file()) IF data is found.
If data is not found, I'd like to return the View with the Model as-is plus a message, like, "no data found, try a different date range"
Now,
should that kind of feedback message be stored in the model itself?, or
is there a cleaner mechanism for this?
Is that what the ModelStateDictionary is for?
UPDATE
just to clarify. I know there may be many ways to do what I want, but what's the correct MVC way of doing it.
Keep in mind the feedback data is not an error, and I don't want to redirect to some other view.
I think what might clear the air is the idea of a ViewModel. Except for the most simple scenarios, you'll find more than one kind of model in your project. They can go by many names, but I find these names helpful:
Pure domain models (Models)
This is where you have your ideal representations of our data model.
Application models (ViewModels)
These models account for the realities of displaying your domain model in a view. They contain data specifically needed for a specific view. It's perfectly acceptable to put something like a status message in this kind of a model.
I would recommend this insightful blog post which shows when, why and how to use ViewModels.
Example:
public class WidgetDataExportViewModel {
public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}
public MyEnum SomeOtherProperty {get;set;}
public string StatusMessage {get;set;}
public IEnumerable<Widget> Widgets {get;set;}
}
If you're talking about a message that you want to code for somewhere in your view, you ought to have that on your model and have your view consume it.
If you want to be able to handle system messages generally in the same way across your application (with a message at the top or side of the window, e.g.), you might create a utility method that puts the information in ViewData with a special key that could get picked up by your master page. If you use TempData instead, the message could be persisted across a redirect.
I have previously used ModelState.AddModelError successfuly to show a summary message. Just make sure you use a key that is not a Model field name.
Note: I have adapted my design from Steven Sanderson's book (see the index on RulesException)
Good luck
Validation errors directly stemming from user actions on your model (e.g. too short a password)
is at home as close to the model as possible.
General error messages of the "no data found" kind are easier addressed through having a dedicated Error View of some sort.
Added:
If I understand you correct, you prefer to stick with one view; be it validation gold or burning SQL servers ;-)
Not madly MVC2 experienced mysef, but being consistent and always create own models, never what you might be served by what(not) ORM you're using (Linq<->SQL, EF) should give you the fine-graininess you need.
If my memory serves me correct I think the Nerddinner could be enlightening; and if you really
want to take the plunge, why don't go Deep Inside ASP.NET MVC 2 Model Metadata and Validation
I've gotten my MVC mainly from books, but the blogosphere has definitely started producing golden material on the more "foreign" parts of ASP.NET MVC.
My real aha moment regarding the M of MVC came while reading
Steve Michelotti's ASP.NET MVC View Model Patterns (a great source for MVC2 info all round)

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.

Resources