FluentValidation "Only MemberExpressions an be passed to BuildResourceAccessor" - fluentvalidation

I have got some problem with FluentValidation. Does anyone have idea about this problem ?
I have Resource files in App_GlobalResources folder.
Error : "Only MemberExpressions an be passed to BuildResourceAccessor, eg () => Messages.MyResource"
public class ProductValidator : AbstractValidator<Product>
{
public static string prefix = "{PropertyName}";
public ProductValidator()
{
RuleFor(product => product.Name).NotNull().NotEmpty().WithLocalizedMessage(() => Resources.Validators.NotNullOrEmpty.Replace(prefix,Resources.Entity_Product.Name));
}
}

I found the solution;
ResourceManager validatorResources = new ResourceManager("OpusERP.Web.UI.App_GlobalResources.Validators", Assembly.GetExecutingAssembly());
string message = NotNullOrEmpty.Replace(prefix, productResources.GetString("Name", Thread.CurrentThread.CurrentCulture));
RuleFor(product => product.Name).NotNull().NotEmpty().WithMessage(message);

Related

AutoMapper - Map destination object's property that does not exist in source object

I'm casting class Process to ProcessDTO. The ProcessDTO object have a property named ProcessSteps that does not exist in Process. I want the ProcessSteps-property to be casted to ProcessStepsDto. I'm using a global configuration for AutoMapper.
I have tried using
CreateMap<Process, ProcessDto>()
.ForMember(dest=>dest.Steps, opt => opt.MapFrom(s => Mapper.Map<ProcessStepDto>(s)));
But this is wrong..
public class Process
{
}
public class ProcessDto
{
//This property does not exists in source object and get's created on get. I want this to be cast to "ProcessStepDto[]"
public ProcessStep[] Steps
{
get
{
ProcessStepRepository repository = new ProcessStepRepository();
return repository.Select(x => x.ProcessId == this.Id && x.Active).OrderBy(x=>x.Position).ToArray();
}
}
}
public class ProcessStep
{
...
}
public class ProcessStepDto
{
...
}
UPDATE
After i use AutoMapper to mapp my object Process to ProcessDto i also want the property of Stepsto be mapped to ProcessStepsDto. Currently it stays as ProcessStep.
If you want to return ProcessDto with ProcessStepDto[], the ProcessDto should define the property with type ProcessStepDto[] instead of ProcessStep[].
public class ProcessDto
{
public ProcessStepDto[] Steps
{
get
{
ProcessStepRepository repository = new ProcessStepRepository();
return repository.Select(x => x.ProcessId == this.Id && x.Active).Select(s => new ProcessStepDto { PropertyInProcessStepDto = s.PropertyInProcessStep }).OrderBy(x=>x.Position).ToArray();
}
}
}

Public access to objects propery on aurelia validation

I would do like to have public access the private property where objects are stored on the current ValidationController as when we issue addObject().
From this blog:
http://www.jujens.eu/posts/en/2017/Jan/24/aurelia-validation/
I am trying to validate not only a WELL KNOWN object but ALL objects registered in the ValidationController
Let me explain a little bit, I had an interface called
export interface IRuleValidator {
addRules(model:any): void;
}
and classes that implement such interface
export class AddressRuleValidator implements IRuleValidator {
addRules(address: Address) {
ValidationRules
.ensure((a: Address) => a.address)
.required()
.on(address);
}
}
export class EmailRuleValidator implements IRuleValidator {
addRules(email: Email) {
ValidationRules
.ensure((e: Email) => e.email)
.required()
.on(email);
}
}
export class PhoneRuleValidator implements IRuleValidator {
addRules(phone: Phone) {
ValidationRules
.ensure((p: Phone) => p.phone)
.required()
.on(phone);
}
}
#inject(AddressRuleValidator, PhoneRuleValidator, EmailRuleValidator)
export class PlayerRuleValidator implements IRuleValidator {
private readonly addressRuleValidator: IRuleValidator;
private readonly phoneRuleValidator: IRuleValidator;
private readonly emailRuleValidator: IRuleValidator;
constructor(addressRuleValidator: IRuleValidator, phoneRuleValidator: IRuleValidator, emailRuleValidator: IRuleValidator) {
this.addressRuleValidator = addressRuleValidator;
this.phoneRuleValidator = phoneRuleValidator;
this.emailRuleValidator = emailRuleValidator;
}
addRules(player: Player) {
ValidationRules
.ensure((p: Player) => p.firstName)
.required()
.on(player);
if (player.addresses && player.addresses.length > 0)
player.addresses.map(address => this.addressRuleValidator.addRules(address));
if (player.phones && player.phones.length > 0)
player.phones.map(phone => this.phoneRuleValidator.addRules(phone));
if (player.emails && player.emails.length > 0)
player.emails.map(email => this.emailRuleValidator.addRules(email));
}
}
#inject(PlayerRuleValidator)
export class ScoreRuleValidator implements IRuleValidator {
private readonly playerRuleValidator: IRuleValidator;
constructor(playerRuleValidator: IRuleValidator) {
this.playerRuleValidator = playerRuleValidator;
}
addRules(score: Score) {
ValidationRules
.ensure((s: Score) => s.factor)
.required()
.on(score);
if (score.player) { this.playerRuleValidator.addRules(score.player); }
}
}
Each class knows how to validate the object passed to it and delegates to other classes the validation of "child" objects.
i.e.: score has a player and a player has emails.
Score knows how to validate to itself and delegates to player his own validation and player do the same with emails, phones, buildin all "the chain" down.
Thus the entire process of building a "validation chain" starts calling addRules() on the root object of the graph.
Suppose that we have an score object: We resolve from "the container" a ruleValidator for Score and starts buildind the validation chain as follows.
#inject(ScoreRuleValidator)
export class ScoreList extends BaseViewModel {
public isOk: boolean;
public score: Score
................ code removed for brevity (validation controller code )
#inject(ScoreRuleValidator)
constructor(ruleValidator: IRuleValidator) {
................ code removed for brevity (validation score object creation)
ruleValidator.addRules(this.score) //this call will start all the validation chain registration
this.validationController.validateTrigger = validateTrigger.changeOrBlur;
this.validationController.subscribe(event => this.validateAll())
}
}
private validateAll() {
this.validator
.validateObject(this.model)
.then(results => this.isOk = results.every(result => result.valid));
//HERE GOES THE PROBLEM SINCE ONLY SCORE is known, and what about score.player, and score.player.addresss[], score.player.phones[], score.player.emails[] and so on in the graph
//I WILL NEED to traverse all the chain and since ValidationController has track of those object will be greet to have access to them
}
HERE GOES THE PROBLEM SINCE ONLY SCORE is known, and what about score.player, and score.player.addresss[], score.player.phones[], score.player.emails[] and so on in the graph?.
I WILL NEED to traverse all the chain and since ValidationController has track of those object will be great to have access to it.
Meanwile an option is refactor the interface a rewrite the validator classes as follows:
export interface IRuleValidator {
addRules(model:any, models:any[]): void;
}
and pass an empty array from the root of the chain collecting all those objects.. like so..
export class AddressRuleValidator implements IRuleValidator {
addRules(address: Address, models: any[]) {
ValidationRules
.ensure((a: Address) => a.type)
.required()
.on(address);
models.push(address);
}
and kick the process.. with an empty array []
const objects: any[] = [];
ruleValidator.addRules(this.score, [])
But since we alreay have this property private on the ValidationController, please make it public.. (I will take care of not touching it, just read it)
BR
(then... the final method for validateAll should be like this)
private async validateAll() {
for (let model of this.models) {
let results = await this.validator.validateObject(model);
if (results.some(result => !result.valid)) {
this.isOk = false;
return;
}
}
this.isOk = true;
}
A deep look to the callback is the answer.
validationController.subscribe(event => this.validateAll())
the event object passed to the callback is an array of ValidateResult[]
the ValidateResult type implements the following interface.
export declare class ValidateResult {
rule: any;
object: any;
propertyName: string | null;
valid: boolean;
message: string | null;
private static nextId;
/**
* A number that uniquely identifies the result instance.
*/
id: number;
/**
* #param rule The rule associated with the result. Validator implementation specific.
* #param object The object that was validated.
* #param propertyName The name of the property that was validated.
* #param error The error, if the result is a validation error.
*/
constructor(rule: any, object: any, propertyName: string | null, valid: boolean, message?: string | null);
toString(): string | null;
}
so the object/s validated is already there in the event object
we could simplyfy the code as follow to update a field to signal if the htlm for is ready.
this.validationController.subscribe(validateEvent => this.isFormValid = validateEvent.results.every(result => result.valid));

How to use ElasticSearch MinHash plugin in NEST

I want to use MinHash elastic search plugin in NEST Elasticsearch.net.
How can I use minhash plugin in nest?
Create index with following mapping:
elasticClient.CreateIndex(descriptor => descriptor
.Index("my_index")
.Analysis(
analysis => analysis.Analyzers(bases => bases.Add("minhash_analyzer", new CustomAnalyzer
{
Tokenizer = "standard",
Filter = new[] {"minhash"}
})))
.AddMapping<IndexElement>(
mappingDescriptor =>
mappingDescriptor
.Properties(p => p
.String(s => s.Name(element => element.Message).CopyTo("minhashvalue"))
.Custom(new MiniHashMapping()))));
class MiniHashMapping : BinaryMapping
{
[JsonProperty("minhash_analyzer")]
public string Analyzer { get { return "minhash_analyzer"; } }
public MiniHashMapping()
{
Type = "minhash";
Name = "minhashvalue";
}
}
class IndexElement
{
public string Message { get; set; }
}
Index sample document:
elasticClient.Index(new IndexElement
{
Message = "Fess is Java based full text search server provided as OSS product."
}, descriptor => descriptor.Index("my_index"));
Tell elasticsearch to include fields in response:
var searchResponse = elasticClient.Search<IndexElement>(s => s.Query(q => q.MatchAll()).Fields("*"));
You can get hash value from searchResponse.Hits[..].Fields or searchResponse.FieldSelections.
Hope this helps.

NancyFx Authentication per Route

From what I saw in the source code RequiresAuthentication() does an Authentication check for the whole module. Is there any way to do this per Route?
I had the same problem. However it turns out the RequiresAuthentication works at both the module level and the route level. To demonstrate, here is some code ripped out my current project (not all routes shown for brevity).
public class RegisterModule : _BaseModule
{
public RegisterModule() : base("/register")
{
Get["/basic-details"] = _ => View["RegisterBasicDetailsView", Model];
Get["/select"] = _ =>
{
this.RequiresAuthentication();
return View["RegisterSelectView", Model];
};
}
}
Of course the only problem with doing it this way is that all the protected routes in the module need to call RequiresAuthentication. In the case of my module above, I have another 5 routes (not shown) all of which need protecting, so that makes six calls to RequiresAuthentication instead of one at the module level. The alternative would be to pull the unprotected route into another module, but my judgement was that a proliferation of modules is worse than the additional RequiresAuthentication calls.
namespace Kallist.Modules {
#region Namespaces
using System;
using Nancy;
#endregion
public static class ModuleExtensions {
#region Methods
public static Response WithAuthentication(this NancyModule module, Func<Response> executeAuthenticated) {
if ((module.Context.CurrentUser != null) && !string.IsNullOrWhiteSpace(module.Context.CurrentUser.UserName)) {
return executeAuthenticated();
}
return new Response { StatusCode = HttpStatusCode.Unauthorized };
}
#endregion
}
}
I ran into the same issue, here's how I solved it.
var module = new MyModule();
module.AddBeforeHookOrExecute(context => null, "Requires Authentication");
_browser = new Browser(with =>
{
with.Module(module);
with.RequestStartup((container, pipelines, ctx) =>
{
ctx.CurrentUser = new User { UserId = "1234", UserName = "test"};
});
});
I can now use this.RequiresAuthentication() at the module level and run my unit tests.

Yii: Catching all exceptions for a specific controller

I am working on a project which includes a REST API component. I have a controller dedicated to handling all of the REST API calls.
Is there any way to catch all exceptions for that specific controller so that I can take a different action for those exceptions than the rest of the application's controllers?
IE: I'd like to respond with either an XML/JSON formatted API response that contains the exception message, rather than the default system view/stack trace (which isn't really useful in an API context). Would prefer not having to wrap every method call in the controller in its own try/catch.
Thanks for any advice in advance.
You can completely bypass Yii's default error displaying mechanism by registering onError and onException event listeners.
Example:
class ApiController extends CController
{
public function init()
{
parent::init();
Yii::app()->attachEventHandler('onError',array($this,'handleError'));
Yii::app()->attachEventHandler('onException',array($this,'handleError'));
}
public function handleError(CEvent $event)
{
if ($event instanceof CExceptionEvent)
{
// handle exception
// ...
}
elseif($event instanceof CErrorEvent)
{
// handle error
// ...
}
$event->handled = TRUE;
}
// ...
}
I wasn't able to attach events in controller, and I did it by redefinition CWebApplication class:
class WebApplication extends CWebApplication
{
protected function init()
{
parent::init();
Yii::app()->attachEventHandler('onError',array($this, 'handleApiError'));
Yii::app()->attachEventHandler('onException',array($this, 'handleApiError'));
}
/**
* Error handler
* #param CEvent $event
*/
public function handleApiError(CEvent $event)
{
$statusCode = 500;
if($event instanceof CExceptionEvent)
{
$statusCode = $event->exception->statusCode;
$body = array(
'code' => $event->exception->getCode(),
'message' => $event->exception->getMessage(),
'file' => YII_DEBUG ? $event->exception->getFile() : '*',
'line' => YII_DEBUG ? $event->exception->getLine() : '*'
);
}
else
{
$body = array(
'code' => $event->code,
'message' => $event->message,
'file' => YII_DEBUG ? $event->file : '*',
'line' => YII_DEBUG ? $event->line : '*'
);
}
$event->handled = true;
ApiHelper::instance()->sendResponse($statusCode, $body);
}
}
In index.php:
require_once(dirname(__FILE__) . '/protected/components/WebApplication.php');
Yii::createApplication('WebApplication', $config)->run();
You can write your own actionError() function per controller. There are several ways of doing that described here
I'm using the following Base controller for an API, it's not stateless API, mind you, but it can serve just aswell.
class BaseJSONController extends CController{
public $data = array();
public $layout;
public function filters()
{
return array('mainLoop');
}
/**
* it all starts here
* #param unknown_type $filterChain
*/
public function filterMainLoop($filterChain){
$this->data['Success'] = true;
$this->data['ReturnMessage'] = "";
$this->data['ReturnCode'] = 0;
try{
$filterChain->run();
}catch (Exception $e){
$this->data['Success'] = false;
$this->data['ReturnMessage'] = $e->getMessage();
$this->data['ReturnCode'] = $e->getCode();
}
echo json_encode($this->data);
}
}
You could also catch dbException and email those, as they're somewhat critical and can show underlying problem in the code/db design.
Add this to your controller:
Yii::app()->setComponents(array(
'errorHandler'=>array(
'errorAction'=>'error/error'
)
));