Is this a good aproach to making sure the fields has valid values for a database?
internal class Customer
{
private string _CustomerId;
internal string CustomerId
{
get
{
return (_CustomerId==null?string.Empty:(_CustomerId.Length>20?_CustomerId.Substring(0,20):_CustomerId));
}
set
{
_CustomerId = value;
}
}}
Regards Sven
A cleaner technique would be to annotate your properties with validation attributes and use a library to validate the entities.
Examples include:
Enterprise Library Validation Block
Castle Validator
NHibernate Validator
System.ComponentModel.DataAnnotations namespace
Then, depending on the library selected, your code would resemble:
public class Customer
{
[StringLengthValidator(20)]
public virtual string CustomerId { get; set;}
}
Your way of validating input is very brittle. You are excepting any possible input (for the CustomerId in this case) and sanitize it when it is requested. This might work in this basic scenario, but in a lot of cases you can't sanitize the input. You are basically correcting the mistakes of the user and making assumptions of what he intended. How will you do that with an mail address? For instance, must the mail address 'stevenhotmail.com' be converted to 'steven#hotmail.com' or to 'stevenhot#mail.com'. Besides this, there is also the possibility of a programming error. Would you want your program try to fix your own programming errors. This will give you headache. Or what will you do when two properties of the same entity have to be compared?
A better solution would be to allow the entity to become in an invalid state and check it's validity just before saving it to the database. When it’s state is invalid, don’t try to automatically correct the changes, but just throw an exception or communicate the errors back to the user.
There are multiple approaches of doing this. You can for instance implement an IsValid() method on each entity or use a validation framework.
Related
I am creating a web app in asp.net-mvc in which I am sending a Required ErrorMessage from my model, but the problem is, I want to translate the message as per user's preference,
so I did something like below
[Required(ErrorMessage = convertErrorMessage("Text to translate"))]
public string Reviews { get; set; }
public string convertErrorMessage(string text)
{
//convertingText in different language
return convertedText;
}
but I am getting the below error
an object reference is required for non static field
on the below line
[Required(ErrorMessage = convertErrorMessage("Text to translate"))]
what can I do, if I want to achieve this?
You cannot call methods to initialize attributes, because these values have to be known at compile time. There are two possible other ways though:
ASP.NET MVC supports standard ways to doing localization, which is the recommended way to go. It is a very broad topic, so I can only leave a few links [1], [2] here. Notice that even the RequiredAttribute you are using has properties ErrorMessageResourceName and ErrorMessageResourceType - these are strong hints that you should be using standard tooling for standard tasks.
If you still want to stick to what you have, define your own attribute and implement your custom logic in there:
class RequiredLocalizedAttribute : RequiredAttribute {
// override ErrorMessage get
// or ErrorMessageString get
}
However, I would strongly advise looking into option 1 instead. You may need a bit more time to learn and implement this, and that won't be time wasted, and may save you lots of headache as you application grows
My question is similar to this one: Repository pattern and mapping between domain models and Entity Framework.
I have done a lot of reading on here about the following:
Mapping the ORM directly to the domain model
Mapping the ORM to a data model and then mapping the data model to a domain model (and vice versa)
I understand the benefits and limitations of both approaches. I also understand the scenarios where one approach is favoured over the other.
There are plenty of examples online, which show how to do option 1. However, I cannot find any example code, which shows how to do option 2. I read questions on here about option two like the one referenced on the first line of this post i.e. the question is about option two but the answer is about option one - and there are comments that state that option two may be more appropriate.
Therefore my question is specifically about how to do option one from a mapping and validation perspective:
Mapping
I believe I can do this when mapping the Domain Model to the Data Model:
public PersonDomain GetById(Guid id)
{
return AutoMapper.Mapper.Map<PersonDomain>(Session.Get<PersonData>(id));
}
I believe I have do this when mapping the Data Model to the Domain Model in the repository (to protect the invariants):
protected PersonDomain ToPersonDomain(PersonData personData)
{
return new PersonDomain(personData.ID, personData.Name, personData.DateOfBirth);
}
Validation
I want to do this in the PersonDomain class:
public class PersonDomain
{
public Guid ID{ get; private set; }
public DateTime DateOfBirth { get; private set; }
public string Name { get; private set; }
public PersonDomain(Guid id, DateTime dateOfBirth, string name)
{
if (id == Guid.Empty())
throw new ArgumentException("Guid cannot be empty");
if (name =="")
throw new ArgumentException("Name cannot be empty");
ID = id;
Name = NAME;
DateOfBirth = dateOfBirth;
}
}
However, every example I find tells me not to put validation in the constructor. One idea I had was to avoid primitive obsession as follows:
public class PersonDomain
{
public ID ID{ get; private set; }
public DateOfBirth DateOfBirth { get; private set; }
public Name Name { get; private set; }
public PersonDomain(ID id, DateOfBirth dateOfBirth, Name name)
{
if (id == null)
throw new ArgumentNullException("ID cannot be null");
if (name ==null)
throw new ArgumentNullException("Name cannot be null");
ID = id;
Name = name;
DateOfBirth = dateOfBirth;
}
}
However, in this case; there is still validation in the constructor.
Questions
My two questions are:
Have I understood the mapping between the Domain Model and Data Model (and vice versa) correctly or is there a more elegant way of approaching this (the mapping between the data model and domain model and vice versa)?
Should I be putting any validation logic in the constructor of the PersonDomain Entity in this case?
Update 27/02/18
This link helped me most: http://www.dataworks.ie/Blog/Item/entity_framework_5_with_automapper_and_repository_pattern
every example I find tells me not to put validation in the constructor.
I think you need to find more examples.
It may help to think about what's going on at a deeper level. Fundamentally, what we are trying to do is ensure that a precondition holds. One way to do this is to verify the precondition "everywhere"; but the DRY principle suggests that we would prefer to capture the precondition at a choke point, and ensure that all code paths that require that precondition must pass through that choke point.
In Java (where DDD began) and C#, we can get the type system to do a lot of the heavy lifting; the type system enforces the guarantee that any use of the type has gone through the constructor, so if we establish in the constructor that the precondition holds, we're good to go.
The key idea here isn't "constructor", but "choke point"; using a named constructor, or a factory, can serve just as well.
If your mapping code path passes through the choke point, great.
If it doesn't..., you lose the advantage that the type checking was providing.
One possible answer is to make your domain model more explicit; and acknowledge the existence of unvalidated representations of domain concepts, which can later be explicitly validated.
If you squint, you might recognize this as a way of handling inputs from untrusted sources. We explicitly model untrusted data, and let our mapping code produce it for us, and then within the domain model we arrange for the untrusted data to pass through the choke points, and then do work on the sanitized variants.
Domain Modeling Made Functional covers this idea well; you can get a preview of the main themes by watching Scott Wlaschin's talk Domain Driven Design with the F# type System
1) Have I understood the mapping between the Domain Model and Data
Model (and vice versa) correctly or is there a more elegant way of
approaching this (the mapping between the data model and domain model
and vice versa)?
I would say that the ORM should map the Domain Model (Entity) to the database while you would use a Data Model for representing data to the outside world (UI, REST...).
2) Should I be putting any validation logic in the constructor of the
PersonDomain Entity in this case?
It's ok to put domain validation logic into the domain object constructor. But if you want to do validation that is UI specific it should probably be done in some validation class mapped to the Data Model so that you can return a nice error to the user.
So, i decided to learn DDD as it seems to solve some architectural problems i have been facing. While there are lots of videos and sample blogs, i have not encountered one that guides me to solve the following scenario:
Suppose i have the entity
public class EventOrganizer : IEntity
{
public Guid Id { get; }
public string Name { get; }
public PhoneNumber PrimaryPhone { get; }
public PhoneNumber AlternatePhone { get; private set; }
public Email Email { get; private set; }
public EventOrganizer(string name, PhoneNumber primaryPhoneNr)
{
#region validations
if (primaryPhoneNr == null) throw new ArgumentNullException(nameof(primaryPhoneNr));
//validates minimum length, nullity and special characters
Validator.AsPersonName(name);
#endregion
Id = new Guid();
Name = name;
PrimaryPhone = primaryPhoneNr;
}
}
My problem is: suppose this will be converted and fed to a MVC view and the user wants to update the AlternatePhone, the Email and a lot of other properties that make sense to exist within this entity for the given bounded context (not shown for brevity)
I understand that the correct guidance is to have a method for each operation, but (AND I KNOW ITS KINDA OF ANTI-PATTERN) i cant help but wonder if this wont end up triggering multiple update calls on the database.
How is this handled ? somewhere down the line, will there be something that maps my EventOrganizer to something - say DbEventOrganizer and gathers all changes made to the domain entity and apply those in a single go?
DDD is better suited for task-based UIs. What you describe is very CRUD-oriented. In your case, individual properties are treated as independent data fields where one or many of these can be updated by a single generic business operation (update).
You will have to perform a deeper analysis of your domain than this if you want to be successfull with DDD.
Why would someone update all those fields together? What implicit business operation is the user trying to achieve by doing that? Is there a more concrete business process that is expressed by changing PrimaryPhone, AlternatePhone and Email together?
Perhaps that is changing the ContactInformation of an EventOrganizer? If that's the case then you could model a single ChangeContactInformation operation on EventOrganizer. Your UI would then send a ChangeContactInformation command rather than an update command.
As for the persistence of your aggregate roots (AR), this is usually handled by an ORM like NHibernate if you are using a RDBMS. However, there are other ways to persist your ARs like Event Sourcing, NoSQL DBs and even storing JSON or any other data inter-change formats in a RDBMS.
You question is quite broad!
EventOrganizer itself should not be updating anything. You should keep your update code quite separate from the entity. A different class would take an EventOrganizer object and update the DB. This is called 'persistence ignorance' and makes the code a lot more modular and cohesive.
It would be common to create a View Model - a class whose purpose is to provide the View with the exact data it needs in the exact form it needs. You would need to create the View Model from your EventOrganizer, after which the View can update it - programmatically or with binding. When you're ready to save the changes, you'll need to update your EventOrganizer from the View Model and pass it onto the updater. This seems like a layer you don't need when the project is small and simple, but it is becomes invaluable as the complexity builds.
I have a design issue in my application.
I have a class with fields having some kind of business logic validations.
This class is instantiated and filled with data in two ways..
1st: By consumer of the class: Data sent from Front end and populated into the object and saved in Database.
2nd: While fetching the stored data.
In 2nd requirement I have a problem.
I don't want to validate data since it may be possible the data stored may not comply to the business logic due to deletion or modification in existing data.
So I need to populate the object with saved data without validation.
so kindly suggest me best way to add validation logic in a class, so that when it is used for data save then it should be validated, and when fetching data it should not validate any of the fields if the key field exists in database table.
Eg:
class customer
{
private string customerCode;
private string customerName;
private List<Project> projectList;
//These property contains validation logic for data assigned to them.
public string CustomerCode{get; set;}
public string CustomerName{get; set;}
public List<Project> projectList{get;set;};
public bool SetData(ref string message)
{
//Fetch From Database and set it to fields.
//Here to avoid validation I can use fields directly to skip validation.
this.CustomerCode = DataTable[CustomerCode];
this.CustomerName = DataTable[CustomerName];
//But here its not possbible to skip validation in Project class
foreach(projectID in DataTable[Projects])
{
//**Problem Area**.... every project I add is validated according to business logic, but it may be possible that even after completion of a project users of the system want to list all the projects of that customer.
this.ProjectList.Add(new Project(projectID));
}
}
}
A slightly more general way to see the problem is for an object to have two validation strategies. In this case you say that the second strategy would be to just ignore any validation. However, in the future you might find it useful to add some minor or side validations, hence the idea of the more general approach. As Davis Osborne suggests, the best way to validate objects is by creating specific validation classes. In sum, I would create two validation objects and validate my object with the appropriate one, depending on the context. In this way your methods will be prepared to use any validation you happen to include in the future and the only you will need is to update would be the validation side of your design.
Create a specific validator that sits behind a common interface. Then it can be unit tested and potentially replaced to provide custom validation scenarios, if this strategy were needed.
Provide support for validating the class as a whole and for each property.
I have a business model with many classes in, some logical entities within this model consist of many different classes (Parent-child-grandchild.) On these various classes I define constraints which are invariant, for example that the root of the composite should have a value for Code.
I currently have each class implement an interface like so...
public interface IValidatable
{
IEnumerable<ValidationError> GetErrors(string path);
}
The parent would add a validation error if Code is not set, and then execute GetErrors on each child, which in turn would call GetErrors on each grandchild.
Now I need to validate different constraints for different operations, for example
Some constraints should always be checked because they are invariant
Some constraints should be checked when I want to perform operation X on the root.
Some additional constraints might be checked when performing operation Y.
I have considered adding a "Reason" parameter to the GetErrors method but for a reason I can't quite put my finger on this doesn't feel right. I have also considered creating a visitor and having a concrete implementation to validate for OperationX and another for OperationY but dislike this because some of the constraint checks would be required for multiple operations but not all of them (e.g. a Date is required for OperationX+OperationY but not OperationZ) and I wouldn't like to have to duplicate the code which checks.
Any suggestions would be appreciated.
You have an insulation problem here, as your classes are in charge of doing their own validation, yet the nature of that validation depends on the type of operation you're doing. This means the classes need to know about the kinds of operations that can be performed on them, which creates a fairly tight coupling between the classes and the operations that use them.
One possible design is to create a parallel set of classes like this:
public interface IValidate<T>
{
IEnumerable<ValidationError> GetErrors(T instance, string path);
}
public sealed class InvariantEntityValidator : IValidate<Entity>
{
public IEnumerable<ValidationError> GetErrors(Entity entity, string path)
{
//Do simple (invariant) validation...
}
}
public sealed class ComplexEntityValidator : IValidate<Entity>
{
public IEnumerable<ValidationError> GetErrors(Entity entity, string path)
{
var validator = new InvariantEntityValidator();
foreach (var error in validator.GetErrors(entity, path))
yield return error;
//Do additional validation for this complex case
}
}
You'll still need to resolve how you want to associate the validation classes with the various classes being validated. It sounds like this should occur at the level of the operations somehow, as this is where you know what type of validation needs to occur. It's difficult to say without a better understanding of your architecture.
I would do a kind of attribute-based validation:
public class Entity
{
[Required, MaxStringLength(50)]
public string Property1 { get; set; }
[Between(5, 20)]
public int Property2 { get; set; }
[ValidateAlways, Between(0, 5)]
public int SomeOtherProperty { get; set; }
[Requires("Property1, Property2")]
public void OperationX()
{
}
}
Each property which is passed to the Requires-attribute needs to be valid to perform the operation.
The properties which have the ValidateAlways-attribute, must be valid always - no matter what operation.
In my pseudo-code Property1, Property2 and SomeOtherProperty must be valid to execute OperationX.
Of course you have to add an option to the Requires-attribute to check validation attributes on a child, too. But I'm not able to suggest how to do that without seeing some example code.
Maybe something like that:
[Requires("Property1, Property2, Child2: Property3")]
If needed you can also reach strongly typed property pointers with lambda expressions instead of strings (Example).
I would suggest using the Fluent Validation For .Net library. This library allows you to setup validators pretty easily and flexibly, and if you need different validations for different operations you can use the one that applies for that specific operation (and change them out) very easily.
I've used Sptring.NET's validation engine for exactly the same reason - It allows you to use Conditional Validators. You just define rules - what validation to apply and under what conditions and Spring does the rest. The good thing is that your business logic is no longer polluted by interfaces for validation
You can find more information in documentation at springframework.net I will just copy the sample for the their doc to show how it looks like:
<v:condition test="StartingFrom.Date >= DateTime.Today" when="StartingFrom.Date != DateTime.MinValue">
<v:message id="error.departureDate.inThePast" providers="departureDateErrors, validationSummary"/>
</v:condition>
In this example the StartingFrom property of the Trip object is compared to see if it is later than the current date, i.e. DateTime but only when the date has been set (the initial value of StartingFrom.Date was set to DateTime.MinValue).
The condition validator could be considered "the mother of all validators". You can use it to achieve almost anything that can be achieved by using other validator types, but in some cases the test expression might be very complex, which is why you should use more specific validator type if possible. However, condition validator is still your best bet if you need to check whether particular value belongs to a particular range, or perform a similar test, as those conditions are fairly easy to write.
If you're using .Net 4.0, you can use Code Contracts to control some of this.
Try to read this article from top to bottom, I've gained quite a few ideas from this.
http://codebetter.com/jeremymiller/2007/06/13/build-your-own-cab-part-9-domain-centric-validation-with-the-notification-pattern/
It is attribute based domain validation with a Notification that wraps those validations up to higher layers.
I would separate the variant validation logic out, perhaps with a Visitor as you mentioned. By separating the validation from the classes, you will be keeping your operations separate from your data, and that can really help to keep things clean.
Think about it this way too -- if you mix-in your validation and operations with your data classes, think of what are things going to look like a year from now, when you are doing an enhancement and you need to add a new operation. If each operation's validation rules and operation logic are separate, it's largely just an "add" -- you create a new operation, and a new validation visitor to go with it. On the other hand, if you have to go back and touch alot of "if operation == x" logic in each of your data classes, then you have some added risk for regression bugs/etc.
I rely on proven validation strategy which has implemented in .net framework in 'System.ComponentModel.DataAnnotations Namespace' and for example used in ASP.NET MVC.
This one provides unobtrusive way to apply validation rules (using attributes or implementing IValidatableObject) and facilities to validate rules.
Scott Allen described this way in great article 'Manual Validation with Data Annotations'.
if you want to apply validation attributes on interface then look at MetadataTypeAttribute
to get better understanding how it works look at MS source code