Model Validation in .Net Core - asp.net-core

Are the DataAnnotations executed in the same order as they are specified or in a random order.
Example :
public class Model1
{
[Required]
[Range(3,45,ErrorMessage="out of range")]
[emailaddress]
public string email_id {get;set;}
}
Does the annotations are checked in the same way as declared or how?

it's probably checked in the order of logic and performance, not the order you wrote it. If the field is required, it would be pointless to check Range first. For controls at the same level, it is checking according to performance. it checks the least costly one first so that it does not spend much effort in the case it does not comply with the condition.

Related

How to utilize Value Objects validation properly when doing Domain Driven Design?

I have a simple Entity Order in pseudo code:
class Order{
private int quantity;
private Date orderDate;
private Date shippingDate;
public Order(int quantity, Date orderDate, Date shippingDate){
if(quantity <= 0){ throw new Exception("Invalid quantity")}
if(shippingDate < orderDate){ throw new Exception("Invalid shippingDate")}
if(...more validation...){....throw Exceptions...}
//assign values if everything is OK
}
}
description, quantity, orderDate and shippingDate are all read from a web form where each is a text field that is configured by a number of validators:
quantityField= new TextField('txt_quantity');
quantityFiled.addNotNullValidator().addNumaricValidator().addPositiveIntegerValidator()
As you can see the validation logic is duplicated between the TextField validation and the Entity validation.
I tried to introduce the concept of value object to my entity by creating Quantity class, OrderDate class and ShippingDate class. So my Order entity becomes like this instead:
class Order{
private Quantity quantity;
private OrderDate orderDate;
private ShippingDate shippingDate;
public Order(Quantity quantity, OrderDate orderDate, ShippingDate shippingDate){
//assign values without validation I think??!!
}
}
and class Quantity for example will be:
class Quantity{
private int quantity;
public Quantity(int quantity){
if(quantity <= 0){ throw new Exception("Invalid quantity")}
this.quantity=quantity;
}
}
Now the questions:
Aren't Aggregate Roots supposed to be the ones responsible for validating the entire aggregate? Isn't my Quantity class violating that?
How can I reuse the validation in the constructor of Quantity in the web form validation? I think the validation code is duplicated so how can I validate it once or at least reuse the validation logic.
Since all value object will be validating themselves, does that mean I shouldn't validate anything in the Entity?
Since ShippingDate depends on OrderDate for validation, How should I validate the shipping date?
Where do the DDD Factories fit in all of this?
if any Quantity cannot be negative in your domain, regardless of context, this makes perfect sense
IMHO the validation in your Quantity constructor serves to assure the correct usage of the class by the application. It throws an exception, those are meant for exceptional states, not for expected workflow. Thus it has a totally different purpose than web form validation, which assures the correct usage of your appliation by the user. It expects invalid input and handles it. I don't see real duplication here, at least not such that could be eliminated without violating the Single Responsibility Principle.
I don't think that's the case. You have if(shippingDate < orderDate) - how did you plan to validate this within the value objects?
Ah, you see the problem. Same answer: this validation belongs to the Order entity. Also, you do not have to use value objects for everything. If an order date or a shipping date have no inherent constraints on each own, just keep using Date.
This seems to be a separate question, I don't see any relevance to the value objects.
Aggregate roots are supposed to enforce invariants in their aggregate, but they don't do all validation. Especially not validation at construction time, which is generally handled in constructors or Factories.
As a matter of fact, moving as many (non context-specific) invariants as you can to constructors and Factories can be beneficial. I think it's a much better idea to have always valid entities rather than relying on the repeated use of ValidateThis() and ValidateThat() methods on the Aggregate root or the entities themselves.
There are basically 3 kinds of validation : client-side validation, application validation (in controllers or Application layer services) and domain validation (Domain layer). Client-side validation is needed and can't be reused. Application validation can rely on domain validation, which in your example means just calling the Quantity constructor and handling exceptions thrown by it. But it can also have its own set of application specific, non-domain rules - for instance, validating a password field against its password_confirm.
Much in the same spirit as the always valid entities one, value objects are best made immutable, which means you only have to validate once when you new them up. However this is intrinsic validation, you can perfectly have peripheral validation in the containing entity (e.g., you can't have more than 3 value objects of that kind in your list, value object A always goes with value object B, etc.)
This is situational validation, not validation of a ShippingDate-intrinsic invariant. Thus Order should be responsible for checking that ShippingDate >= OrderDate independently from the validity of each of these value objects.
Factories should be used when an object's construction logic is complex enough that it is a responsibility in itself, and as such doesn't fit in the object's constructor or in the consumer, by virtue of SRP. Factories do contain construction-time validation logic, just like constructors, which makes them invariant enforcers of sorts as well.
These are many questions, you might want to break them down to single questions.
Questions 2 through 5 very much depend on various factors and are subject to opinion.
But here's my answer to question 1 (and somewhat to question 3 and 4):
The Aggregate is responsible for its integrity. Not the Aggregate Root. Every item inside the Aggregate can do their own validation as long as the Aggregate stays valid as a whole.
State validation (as a correct amount or an amount not being negative) can be done inside the respective class. Interdependent state validation like ShippingDate >= OrderDate can be done on a higher level, e.g. in the Aggregate Root.

Hibernate Search automatic update of composed fields

I have a Person entity with multiple name related properties (firstName, lastName, title).
All the name related properties should be stored in a single lucene index field "fullName".
#Indexed
#Entity
public class Person {
...
private String firstName;
private String lastName;
private String title;
#Field(store=Store.NO, index=Index.TOKENIZED)
public String getFullName() {
return firstName + " " + lastName + " " + title;
}
}
The only problem I'm facing is to automatically update the fullName in the index when a name related property is updated.
Is there some way to tell Hibernate Search that fullName is a composed field and must be updated when one of the parts changes? Maybe something like this?
#ComposedOf({"firstName", "lastName", "title"})
Thank you!
There are several solutions for your problem and it the solution you are choosing is probably a matter of taste (you might also apply a combination of them):
Check the property _hibernate.search.​enable_dirty_check_ and make it sure it is set to false in your case. The default is true. See the online docs for more information - http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/
Add the #Field annotation also to firstName, lastName and title. You get a bigger index size, but often that does not matter. As a side effect the dirty checking will work (assuming btw that your JPA annotations are correct. For example I am assuming getFullName is transient)
Use a class bridge and optionally remove getFullName. Using a class bridge will also automatically disable the dirty check optimisation
#Indexed
#Entity
public class Person {
...
#Field(name="fullName") String firstName;
#Field(name="fullName") String lastName;
#Field(name="fullName") String title;
}
This is possible as you have chosen TOKENIZED and I'm assuming your analyzer is set to split the tokens on whitespace as you're adding whitespace to separate them: you can have multiple repetitions of a same field, the result is almost the same as splitting the compound terms
(I say almost as it won't be able to determine ordering of terms in case you need a PhraseQuery looking for a specific order of keywords).
For more complex cases you would use a ClassBridge which disables the dirty-checking optimisation which has been annoying you in this case: Hibernate Search tracks if any persistent field was actually written to to decide if it can skip expensive reindexing operations but is then unable to detect such tricks.

Objects with two properties only

I am trying to decide on the best approach to the following problem:
I have a class called Desk. A desk has lots of properties. A Desk may have some objects on it. The current application specifies that it can have Pencils, Computers, or Cups on the desk. A few more objects may be added in the future. It can have one or none of each object. The Pencils have a property of Color, all of the objects have an ID and name. All of this information must be persistent so is stored in a database in some form.
Do I:
public class Desk {
public int property1;
public int property2;
...
public ISet<DeskObject> deskObjects;
}
public DeskObject {
public int deskObjectID;
public String name;
public DeskObject(name) {
this.name = name;
}
}
public Computer extends DeskObject {
DeskObject("Computer");
}
public Pencil extends DeskObject {
DeskObject("Pencil);
public Color color;
}
I also need to easily tell which objects a Desk contains in O(1) time. This means I will have to override hashcode and equals (probably by just returning the ID) for the DeskObjects so I can do set.contains(object). It seems like overkill and a misuse of objects. Surely there is a better solution?
If your domain is about desks and the objects they contain, then an object model like this is entirely warranted. The only question you need to ask yourself is this: Is this my domain model, or is it a computation model?
From the phrasing of your question, I would infer its rather the latter. Your objects do not contain any behavior (such as Desk.CleanNonRecentlyUsed()).
A domain model contains data and behavior (a true object model, I call this domain model), a computation model is data and separated behavior (procedural code).
If all your model needs to do is provide efficient lookups, you can chose any abstract representation that suits you. A lightweight object that captures just data is ok, but you could also use tuples (or to be .net specific since you mentioned GetHashCode: Annonymous classes) or just a Hashtable for the desk. Your computation model can be anything from an Index in your database (sounds reasonable in your example), a special object model, or dedicated algorithms over plain arrays.
Most of the time, it is not warranted to create a computation model when you already have a domain model. But sometimes it is.

NHibernate - truly dynamic sorting

Using NHibernate, I need to be able to configure my application to sort a specific collection of entities exactly as needed.
The configurable sort:
can involve multiple properties
can specify the sorted properties in any order
can specify asc/desc on the sorted properties
can sort by custom properties (i.e. there is no corresponding SQL/C# property - it is calculated)
This functionality is inherited from an existing app where parts of the SQL are specified by an administrator and the SQL statement is built/executed dynamically.
Every time I try thinking through a solution I start getting in muddy waters with all kinds of alarms going off in my head regarding maintainability, performance, scalability, security, etc..
For example, I figure the admin can specify a comma delimited string like so:
"Date asc, FirstName asc, LastName desc"
I can split the string and go through a loop matching the property/sort pairings in a case statement and calling .AddOrder(Order.Asc("FirstName")) as necessary. But then, how do I handle custom properties? I could allow the user to specify SQL for calculating custom properties and then allow the user to sort on those like they would FirstName, but I'm seemingly back at dirty/kludge again.
Is there a clean/appropriate way to handle this requirement?
After much thought and a stroke of luck, I may have a solution.
public class CustomOrder : Order
{
private string customOrderSql;
public CustomOrder(string customOrderSql) : base("", true)
{
this.customOrderSql = customOrderSql;
}
public override NHibernate.SqlCommand.SqlString ToSqlString(
ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new NHibernate.SqlCommand.SqlString(this.customOrderSql);
}
}
I can pass a custom sort string to my repository where I add my CustomOrder as follows:
.AddOrder(new CustomOrder(customSort))
I still can't sort by custom properties but maybe I can get away with applying case statements in the order by clause. I'm still open for better suggestions if they exist.

WCF Data Contract and Reference Entity Data?

Soliciting feedback/options/comments regarding a "best" pattern to use for reference data in my services.
What do I mean by reference data?
Let's use Northwind as an example. An Order is related to a Customer in the database. When I implement my Orders Service, in some cases I'll want the reference a "full" Customer from an Order and other cases when I just want a reference to the Customer (for example a Key/Value pair).
For example, if I were doing a GetAllOrders(), I wouldn't want to return a fully filled out Order, I'd want to return a lightweight version of an Order with only reference data for each order's Customer. If I did a GetOrder() method, though, I'd probably want to fill in the Customer details because chances are a consumer of this method might need it. There might be other situations where I might want to ask that the Customer details be filled in during certain method calls, but left out for others.
Here is what I've come up with:
[DataContract]
public OrderDTO
{
[DataMember(Required)]
public CustomerDTO;
//etc..
}
[DataContract]
public CustomerDTO
{
[DataMember(Required)]
public ReferenceInfo ReferenceInfo;
[DataMember(Optional)]
public CustomerInfo CustomerInfo;
}
[DataContract]
public ReferenceInfo
{
[DataMember(Required)]
public string Key;
[DataMember(Required)]
public string Value;
}
[DataContract]
public CustomerInfo
{
[DataMember(Required)]
public string CustomerID;
[DataMember(Required)]
public string Name;
//etc....
}
The thinking here is that since ReferenceInfo (which is a generic Key/Value pair) is always required in CustomerDTO, I'll always have ReferenceInfo. It gives me enough information to obtain the Customer details later if needed. The downside to having CustomerDTO require ReferenceInfo is that it might be overkill when I am getting the full CustomerDTO (i.e. with CustomerInfo filled in), but at least I am guaranteed the reference info.
Is there some other pattern or framework piece I can use to make this scenario/implementation "cleaner"?
The reason I ask is that although we could simply say in Northwind to ALWAYS return a full CustomerDTO, that might work fine in the simplistic Northwind situation. In my case, I have an object that has 25-50 fields that are reference/lookup type data. Some are more important to load than others in different situations, but i'd like to have as few definitions of these reference types as possible (so that I don't get into "DTO maintenance hell").
Opinions? Feedback? Comments?
Thanks!
We're at the same decision point on our project. As of right now, we've decided to create three levels of DTOs to handle a Thing: SimpleThing, ComplexThing, and FullThing. We don't know how it'll work out for us, though, so this is not yet an answer grounded in reality.
One thing I'm wondering is if we might learn that our services are designed at the "wrong" level. For example, is there ever an instance where we should bust a FullThing apart and only pass a SimpleThing? If we do, does that imply we've inappropriately put some business logic at too high of a level?
Amazon Product Advertising API Web service is a good example of the same problem that you are experiencing.
They use different DTOs to provide callers with more or less detail depending on their circumstances. For example there is the small response group, the large response group and in the middle medium response group.
Having different DTOs is a good technique if as you say you don't want a chatty interface.
It seems like a complicated solution to me. Why not just have a customer id field in the OrderDTO class and then let the application decide at runtime whether it needs the customer data. Since it has the customer id it can pull the data down when it so decides.
I've decided against the approach I was going to take. I think much of my initial concerns were a result of a lack of requirements. I sort of expected this to be the case, but was curious to see how others might have tackled this issue of determining when to load up certain data and when not to.
I am flattening my Data Contract to contain the most used fields of reference data elements. This should work for a majority of consumers. If the supplied data is not enough for a given consumer, they'll have the option to query a separate service to pull back the full details for a particular reference entity (for example a Currency, State, etc). For simple lookups that really are basically Key/Value pairs, we'll be handling them with a generic Key/Value pair Data Contract. I might even use the KnownType attribute for my more specialized Key/Value pairs.
[DataContract]
public OrderDTO
{
[DataMember(Required)]
public CustomerDTO Customer;
//in this case, I think consumers will need currency data,
//so I pass back a full currency item
[DataMember(Required)]
public Currency Currency;
//in this case, I think consumers are not likely to need full StateRegion data,
//so I pass back a "reference" to it
//User's can call a separate service method to get full details if needed, or
[DataMember(Required)]
public KeyValuePair ShipToStateRegion;
//etc..
}
[DataContract]
[KnownType(Currency)]
public KeyValuePair
{
[DataMember(Required)]
public string Key;
[DataMember(Required)]
public string Value;
//enum consisting of all possible reference types,
//such as "Currency", "StateRegion", "Country", etc.
[DataMember(Required)]
public ReferenceType ReferenceType;
}
[DataContract]
public Currency : KeyValuePair
{
[DataMember(Required)]
public decimal ExchangeRate;
[DataMember(Required)]
public DateTime ExchangeRateAsOfDate;
}
[DataContract]
public CustomerDTO
{
[DataMember(Required)]
public string CustomerID;
[DataMember(Required)]
public string Name;
//etc....
}
Thoughts? Opinions? Comments?
We've faced this problem in object-relational mapping as well. There are situations where we want the full object and others where we want a reference to it.
The difficulty is that by baking the serialization into the classes themselves, the datacontract pattern enforces the idea that there's only one right way to serialize an object. But there are lots of scenarios where you might want to partially serialize a class and/or its child objects.
This usually means that you have to have multiple DTOs for each class. For example, a FullCustomerDTO and a CustomerReferenceDTO. Then you have to create ways to map the different DTOs back to the Customer domain object.
As you can imagine, it's a ton of work, most of it very tedious.
One other possibility is to treat the objects as property bags. Specify the properties you want when querying, and get back exactly the properties you need.
Changing the properties to show in the "short" version then won't require multiple round trips, you can get all of the properties for a set at one time (avoiding chatty interfaces), and you don't have to modify your data or operation contracts if you decide you need different properties for the "short" version.
I typically build in lazy loading to my complex web services (ie web services that send/receive entities). If a Person has a Father property (also a Person), I send just an identifier for the Father instead of the nested object, then I just make sure my web service has an operation that can accept an identifier and respond with the corresponding Person entity. The client can then call the web service back if it wants to use the Father property.
I've also expanded on this so that batching can occur. If an operation sends back 5 Persons, then if the Father property is accessed on any one of those Persons, then a request is made for all 5 Fathers with their identifiers. This helps reduce the chattiness of the web service.