Conditional rule evaluation with FluentValidation.NET - c#

What I want to achieve can be roughly summarized as a simple OR conditional.
Whilst there is support for conditional property validation on OTHER properties with Fluent Validation (When/Unless) there does not appear to be a way to support conditional rules on the same property? Or am I missing something?
Essentially I want to achieve:
RuleFor(x => x.Property).CanEitherValidateThisRule().Or.CanValidateThisRule();
The only alternative to this is to combine the rules in a single custom rule?
However, this tightly couples the rule logic and realistically they are completely separate conditions that I may want to use on other objects/fields.
There was a suggestion to support this in a future version of FluentValidation.NET, does anyone know a way to achieve this with extension methods or if there is a syntax that I've missed?
EDIT: Found the discussion: Fluent Validation for .NET - View Discussion

You can try Chaining Validators for the Same Property
Although its a dirty way to do what you want, its still worth if you are doing the validations for a small part of code.
If you want a cleaner way, then,as of now, I think creating a custom validator class is the most convenient option.
The wiki page I have linked to gives all the necessary tools to start with.

Related

Reuse NUnit's IConstraint in validation

NUnit has an IConstraint interface (documentation here and code here). It seems to me that reusing this type in my core project for validation purposes makes sense.
Are there unforseen side effects I have not yet recognized? Would you reuse the IConstraint type in your core project? why/why not?
This is more an opinion-based question. Beside that, there are two issues that come to my mind.
Firstly, you can write something like Assert.That(foo, Is.EqualTo(bar)), which internally invokes an EqualConstraint. To have your custom constraint to be usable like this, you have to "overload" Is, so you can have Assert.That(foo, Is.AsGoodAs(bar)) (where AsGoodAs is your custom constraint invocation). See NUnit's Custom Constraints documentation for details. With this you will have two classes with the name Is (yours and the NUnit one) and you will also call the default static methods like EqualTo via a derived type. Resharper will warn you about this.
Secondly, writing intelligent assertion failure texts (like expected "this", but was "that") can be a bit tricky to figure out. You will certainly spend some time on this until you get what you want. Of course this depends on your personal feelings about nice texts.

Property attribute in an interface

i have a property attribute that can be defined once per class, and an empty interface called ISql which i just use to mark my objects that are allowed to use my custom buillt ORM.
is there a way to force the class that implements ISql to have that attribute at least once?
No, attributes aren't part of the contract of the interface, in terms of what implementations must provide.
For this sort of thing, I usually just add a unit test which uses reflection to find all implementations and validates it that way. It's not as nice as a compile-time check, but it's the best that's available in this case.
For this kind of code validation I like to use Nitriq. You can write your own rule very easy using Linq.
For personal use you can just call Nitriq to validate the code.
In large projects I used to put a step on continuous integration to run Nitriq console to validate the rules against the code

How to change models editable atttribute based on a condition

Based on user credentials, I will allow users to edit a field or not on a Razor View.
So I currently have one model which I can do this for the properties I forbid:
[Editable(allowEdit=false)]
public string FirstName {get;set;}
but when I add the attribute whether or not a user has permission to edit it, they won't be able to. I cannot change the fields in Razor View either as we use a very different way of rendering model properties.
Any idea how can I overcome this problem?
You might want to create custom validation attribute and use that, in it you can inject your boolean and check and make it conditional (in C#).
The better option is to use Fluent Validation - its much easier to work with in these cases, when you need conditional validation. Also it will keep your models cleaner.
So if you can - use Fluent validation, if not, just define your own property and control it in your code including all conditions. Examples and links to libraries are here
Here is another option for you - complete library built with aim to easy the work you trying to achieve : http://foolproof.codeplex.com/
Hope this helps

Ignore built-in FxCop rules for some specific cases. Custom FxCop rules?

I am developing some async code using Web Api, and I get a lot of FxCop errors that I would like to suppress. For example the following code in my controller would trigger these errors:
UsePropertiesWhereAppropriate
MarkMembersAsStatic
DoNotNestGenericTypesInMemberSignatures
public Task<HttpResponseMessage<IEnumerable<Foo>>> GetAsync()
{
}
I do not want to suppress these rules for the whole assembly, so it seems like the only way to suppress the errors in code is to add a SuppressMessage attribute for each violated rule on each method. Is there a better way to suppress the errors? I am thinking of custom FxCop rules... Is it possible to create a rule like "Ignore DoNotNestGenericTypesInMemberSignatures for Task<T>" or "Ignore these rules for any type inheriting from Bar class"?
No, there is no way to get any of the Microsoft-provided rules to conditionally ignore certain types or members like this. You have three basic choices:
Suppress each violation individually,
Disable the rules entirely for the assemblies containing the "special" types, or
Disable the Microsoft-provided rules, but provide alternate custom rules that are able to ignore your types.
Personally, I would opt for #1, but ymmv...
I believe the closest answer for this is Custom Rule in FxCop to only apply to methods called by particular type's method ? Hopefully, that works for you, otherwise I would say the answer is no

AOP Dirty Tracking

In the past I have used a few different methods for doing dirty checking on my entities. I have been entertaining the idea of using AOP to accomplish this on a new a project. This would require me to add an attribute on every proptery in my classes where I want to invoke the dirty flag logic when the property is set. If I have to add an extra line of code to each property for the attribture, what is the benefit over just calling a SetDirty() method in the setters. I guess I am asking what would be the advantage, if any, of using the AOP approach?
I'd say that not only is there not any advantage in this case: there's a bit of a disadvantage. You're using the same number of lines of code whether you call dirty() or you use AOP, but just calling dirty() is more simple and clear, as far as intent goes.
AOP, honestly, is a bit oversold, I think. It adds another level of indirection, in terms of reading the code, that often it doesn't pay back.
The key thing to think about here is, does it help the next guy reading this (which may be you a few months down the road) understand more quickly and clearly what I'm trying to do. If you have trouble figuring out what's better about the less straightforward approach, you probably shouldn't be using it. (And I say this as a Haskell programmer, which means I'm far from adverse to non-straightforward approaches myself.)
The advantage is that should you decide to change the implementation of how to invoke the dirty flag logic, you'll only need to make one change (in the AOP method's body), not N changes (replacing all your SetDirty calls with something else).
I don't see any benefit if you have to decorate your entities with an attribute. Espeically if all your doing is calling a single method. If the logic was more complex then I could make an argument for using AOP.
If let's say each time you modify a property you wanted to track that change as a version, this might be more complex behavior that could be injected, then having this abstracted out of the property could be beneficul. At the same point you would probally want to version changing several properties at once so I come back to there not being much value.
The use of AOP is for cross cutting concerns. This means that you want to have a feature such as logging, security, ect but the business logic really does not belong in your class. This could be for the Dirty flag logic as the Domain object should not care that it has been changed. That is up to your DirtyLogicUtility or what ever name it has.
For example you want to log every time a method gets called for every you could place this in every function, but later on you want to have logic so that it is logged on every other call.
AOP keeps your classes clean doing what they are supposed to do while leaving the other pieces alone.
Some AOP implementations, specifically PostSharp, allow you to apply the attribute at an Assembly level with wildcards as to which classes it applies to.
Why do you want the dirty check to be the responsibility of the entities? You can manage this somewhere else. The pattern is called Unit of work

Categories