Use the FluentValidation for async rules - c#

I am trying to use fluentvalidation in my WebAPI projects for an asynchronous rules validations (e.g. check username duplication). (respecting the avoidance of manual use inside controllers, I want to validating before accessing the controller)
The documentation provided by the library saying that:
You should not use asynchronous rules when using automatic validation with ASP.NET as ASP.NET’s validation pipeline is not asynchronous. If you use asynchronous rules with ASP.NET’s automatic validation, they will always be run synchronously.
I know it is possible to use manually the validation from the controller. However, I feel it breaks the clean architecture and coding convention in my App. I am trying to keep controllers free from any type of validation and I found it easy when validation does not necessitate database access. However, the need for rules validation Asynchronously will change the situation.
To Sum up:
I need to validate some rules asynchronously for some BM(s)
Documentary advise to use it manually and avoid using auto validation pipeline
I don't want to validateAsync inside the controller
Do you think the utilization of interceptor will make a sense?

Related

Why do we need OperationAuthorizationRequirement for resource-based authorization in ASP.NET Core?

I was reading Resource-based authorization in ASP.NET Core on learn.microsoft.com and I am confused about complexity required to check author of a document.
In this example we need to create Operations and DocumentAuthorizationCrudHandler classes, register DI in Startup, call and await AuthorizeAsync and then perform checks.
Instead of writing 30 lines of code in 4 files we can accomplish everything in just one line of code
if (User.Identity?.Name == Document.Author) return Page();
If we want be able to reuse this we can extract it to a method and still it will be far less complicated solution.
Is there anything wrong with one line solution or I am missing something?
Edit:
To clarify my question - Is there any concrete example why would it be better to implement AuthorizationHandler and OperationAuthorizationRequirement for resource authorization instead of going with simple check? I am genuinely curious about what are the benefits, because I prefer simple solutions but I am afraid that I will hit some case in future that is already covered by AuthorizationHandler/OperationAuthorizationRequirement.
As the doc has said that Operations and DocumentAuthorizationCrudHandler classes enable you to write a single handler instead of an individual class for each operation type.
If we want be able to reuse this we can extract it to a method and still it will be far less complicated solution.
The recommended recourse-based authorization uses DI,which could be more clear and powerful, instead of repeating if / else code everywhere.
Besides,we could also handle different status code (401,403...) in the custom Authorization Handler.We could use IAuthorizationService on view or in blazor razor component.

How do I validate data in C# based on a Struts validation.xml?

I have a validation.xml file from Struts, and am going to implement a server-side validation in .NET based on it. The validation.xml file is accompanied with a validationMessages.properties file. Are there any .NET libraries which are capable of performing a validation based on a Struts validation file?
In case this has never been done I'll have to either create such a class, since the validation file is too long and complex to be implemented as mere C# logic. Which begs the question: How would I even begin?
The end-goal is to be able to populate a C# class with properties for all fields, execute a validation method with that class as a parameter and have it return a list of validation error messages (or no errors in case of success).
I'd be surprised if anything like that existed; it's relatively unusual to move from Java -> .NET.
First, see if there are any custom validators. That code would need to be duplicated.
Then pick apart the different forms (or actions, depending on how they did validation). Put each of those into a C# class (but see below) rather than one giant one. I'm not sure what you mean by "A C# class with properties for all fields"; personally I'd go more granular.
Or just use an existing C# validation package and do a translator from Apache Commons Validation to the C# configuration (or code).
It should be a relatively straight-forward process since the validation config is well-known and documented, and all the code is available.

Does IClientValidatable implementation violate the DRY principle in MVC?

MVC provides a lot of validation attributes which can be used as data annotations to perform simple server-side validations.
However, if I want to do some custom validation using my own business logic, I need to create a custom validation attribute, derived from ValidationAttribute, and override the IsValid method.
So far so good.
However, if I want to perform the same validation on client side, I need to implement the IClientValidatable interface in my validation attribute class, and implement the GetClientValidationRules method, which will tell my application that this validation has to be performed on the client-side too.
The contentious issue however, is that I need to write the logic for this client-side validation as separate JavaScript using jQuery. This is exactly the same logic I already wrote in C# (or VB) when overriding the IsValid method.
Why do I have to write the same logic twice, albeit in different languages? Doesn't this violate the DRY principle? I would have expected MVC to generate the JavaScript for the validation logic itself.
Example illustrating what I am talking about: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/enabling-client-side-validation-on-custom-data-annotations-w/
EDIT:
Also, what if my validation logic requires data from the application config file or application cache? How do I use that in the jQuery method I write for client-side validation? If I can't, is there any other way to do client-side validation, the logic for which uses application data?
Yes, but it's often worth it.
The benefits of client side validation are speed and less server load. The benefit of server validation is security. Implementing both gains the best of both worlds.
DRY is a good rule of thumb, but as with all rules of thumb there are situations in which the rule should be violated.
EDIT to answer your follow up question
If your jQuery needs values from server side config you need to pass that to the client as part of the JavaScript. For example, you could define a variable in your view which holds the server side value.

Audit Logging using ASP.NET MVC 4 ActionFilter

I'm building a web app using ASP.NET MVC 4, with data storage provided by T-SQL database via Entity Framework. I'm integrating audit logging as I go, and I'd like to provide a nice human-readable summary of the action, so that I can present a friendly logs view with clear statements like "User Bob logged in", "User Alice updated article 'Foo'", etc.
An audit record currently consists of:
GUID
timestamp
user ID
action category (controller name)
action (action method name)
IsError (boolean; true means either this is a record of an error, or this action did not complete successfully)
blob of serialised details
At the moment, my logging uses a custom attribute which implements IActionFIlter; the OnActionExecuting() method logs the attempted action (serialising things like URL, parameters etc to the detail blob) and the OnActionExecuted() method goes back and sets IsError to true if there are no errors, and appends either the returned result or exception with error message and stack trace etc to the details. I want to add another column for description strings, but I can't see a tidy way to do it.
The furthest I got was to pass a string to the attribute, something like "User $user logged in" and then have the log method scan the string for the $ character and replace that word with anything from the parameters dictionary whose key value matches that word (minus the $ character). This is a little limited; for example, if articles are stored by ID number, then the best you can manage is "User 18 edited article 37". There's no real way to get at the username or article title; you can't pass instance data to the attribute because it's baked in at compile time, and I don't really want my logging method to be making all sorts of database calls to get that sort of data, not least because it then becomes impossible (or at least a real pain) to have a single generic logging method.
The alternative to all this is to have a static audit logging class and call something like AuditRecord.WriteLog(foo); all over the place, perhaps with some kind of descriptor class I can use (or inherit from) to describe different types of action, storing all the parameters and generating a description string as needed, but seems less elegant to me; I really like being able to just tag [AuditLog] on top of a method and know that it'll be recorded.
I'd like to avoid huge amounts of conditional logic, like using the controller and action names in some big switch statement to select the correct string template. If I could just get hold of things like article titles in the logging method then it'd be fine. Is there a neat, simple way to do this?
We recently had a similar discussion at work regarding both logging audit history and applying more complex security rules across our new MVC project.
In the end the most "elegant" solution that we came up with was to have the method calls within the controller actions (Your alternative method).
For example:
[HttpPost]
public ActionResult CreateItem(Item item)
{
//Simplified
CheckSecurity(SecurityTypes.ItemCreation);
LogActivity("Created an item");
//Rest of action code
}
This gave us the flexibility to account for all possible use cases, and allowed us to wrap up the logic into simple to use methods to reduce code repetition.
It may be late to answer, but I think there is a good alternative to keep using action filter attributes and to be able to access per-request lifecycle objects.
As anaximander noted it above, the underlying problem is that attributes are resolved by the CLR, so their lifetime cannot be controlled and they don't mix very well with an IoC container (to make them transient, per request instance, etc.).
Usually, in .NET a new instance of attribute is created each time it is resolved by reflection (GetCustomAttribute method).
Furthermore, in the case of MVC/webapi, action filter attributes are cached, so they normally are created just once.
The conclusion is that attributes are designed to annotate only, in other word, they should contain only metadata (they are DTO). Unfortunately, my understanding is MVC and WebApi frameworks are not designed in this way. To restrict action filter attributes to simple DTOs and to be able to manage lifecycle of the logic part around them, special means must be taken.
I think your use case fits perfectly to the solution provided in a Steven van Deursen's great article. It demonstrates how to separate attributes data from logic and it is based on an action filter registered globally, the so called "dispatcher", with the ioc container as a dependency.
The container is not resolved statically. It is provided in the constructor of the global filter when it is registered at the application initialization.
So each time it is executed, it looks for any attribute marker on the action being executed and it resolves a generic interface where the attribute is the generic parameter. Instead of having an action filter attribute which merge data and behavior, you end up using two classes: a plain old attribute - the marker - and the corresponding implementation of the generic interface for its logic counterpart. The container is used to resolve the generic interface. If your filter depends on per-request components, you can create an implementation of the generic interface with the services you need. If it does not depend on other services but you need a per-request lifetime (to measure time between the beginning and the end of an action for example), it also does the job, thank to the use of the container to resolve the generic interface. The aforementioned article contains code examples for WebApi, MVC and ASP.NET 5.
Also, Mark Seemann has made an article on the same approach.
I think it does not provide a good solution for all cases, like authorizations filters and perhaps exception filters, but to me it is the most elegant way for many action filters.
The better way would be to format this data when you view it, rather than build these things during the logging process.
If the action is "login", and the recorded user is available (which you should do) then you build that message in the viewer.
So you log all the raw events, then build the "view model" or "read model" based on this data that is more descriptive. this can allow you to even re-parse all the raw data if you want to change it's description. You could log a lot of data that isn't used yet so you could implement it later within the description.
IMO, sprinkling methods this way inside actions doesn't seem like a good idea and an Action Filter on the controller or base controller is cleaner. if you wanted to do that you could use an AOP (aspect oriented programming) framework to avoid cross cutting...

Encapsulate Use Cases in a software

I usually write use cases for all the software that I develop. For each use case I generally write a controller which directs the flow (implements a use case).
I have recently started developing web apps using Asp.net MVC. One of the best practices of Asp.net MVC is to keep very less logic in the controllers. I am not able to figure out how will I change my design to reflect this.
I basically want a way to encapsulate my use cases.
I think having a fat model and skinny controller is generally a good practice in any language and not specifically .NET MVC. Checkout this nice article that goes through a sample scenario showing the advantages of a fat mode in Ruby on Rails (but the ideas apply to any language).
For representing the use-cases in your code, I think a much better place for them is in test-cases rather than the controller.
Push as much business logic to your models and helper classes as possible, and use controllers mainly for handling URL calls and instantiating the relevant models, retrieving data from them, and pushing data to the views. Views and controllers should have as few decisions to make as possible.
Create a business component to encapsulate use cases. For instance if you have a leave management system you would have use cases like apply for a leave, approve a leave request, reject a leave request, etc. For this you can create a business component (class) called Leave Manager with methods (functions/operations) like "Apply", "Approve", "Reject", etc. These methods will encapsulate your use cases. These methods would take your business entities and data store classes as input and execute the use case.
class LeaveManager{
int Apply(from, to);
bool Approve(leaveApplicationId, approverId);
bool Reject(leaveApplicationId, approverId);
}
You can then use this business component in your controllers to execute the use case by supplying the required parameters.

Categories