Why is ruleSet not recognized in WebForms? - fluentvalidation

Given this validator:
public ThingValidator()
{
RuleSet("Subgroup", () =>
{
RuleFor(x => x.Apple).NotEmpty();
RuleFor(x => x.Peach).NotEmpty();
});
}
According to the documentation, the 'ruleSet' option should use my named ruleset. However, the suleSet symbol cannot be resolved.
var validator = new ThingValidator();
var thing = new Constituent();
var results = validator.Validate(thing, ruleSet: "Subgroup");
What am I missing?

I was stuck on this as well, but when I looked into the code, I found that while IValidator<T> has a Validate method, there are also Validate extensions methods in DefaultValidatorExtensions. The call with the ruleSet parameter in #mmcglynn's answer is actually to this extension method from DefaultValidatorExtensions:
public static ValidationResult Validate<T>(
this IValidator<T> validator, T instance,
IValidatorSelector selector = null,
string ruleSet = null)
This is why Resharper thinks that the ruleSet variable is unused - because it is not actually passed in. The string "children" passed in is for the 3rd parameter called ruleset, whereas the second parameter (which can take the RulesetValidatorSelector object) defaults to null.

This is extension method, declare namespace using FluentValidation and you can use it.

I think what you need it:
var results = validator.Validate(constituent, new RulesetValidatorSelector("Subgroup"));
or, closer to the example in the FluentValidation documentation
RulesetValidatorSelector ruleSet = new RulesetValidatorSelector();
var results = validator.Validate(constituent, ruleSet: "Children");
This will work, but ReSharper thinks that the ruleSet local variable is unused.

Related

Replacing Type with var for all 'Class class = new Class()' usages in Java project

I recently switched to Java 11 for a rather big project, and would like to switch to using var class = new Class() instead of Class class = new CLass().
I tried using Intellij Structural Search (and replace) for this, but its turning out to be more complex than expected.
My first attempt was $Type$ $Inst$ = new $Constructor$($Argument$);, which also matches global variables (which don't allow var).
My second attempt is:
class $Class$ {
$ReturnType$ $Method$ ($ParameterType$ $Parameter$) throws $ExceptionType$ {
$Statements$;
final $Type$ $Inst$ = new $Constructor$($Argument$);
$Statements2$;
}
}
Which misses all calls inside e.g. try blocks (since they get matched by the expressions)
Any help would be greatly appreciated!
Use your first template
$Type$ $Inst$ = new $Constructor$($Argument$);
But add a Script modifier on the $Inst$ variable with the following text:
Inst instanceof com.intellij.psi.PsiLocalVariable
Alternatively you may want to try the Local variable type can be omitted inspection that is available in IntelliJ IDEA.

Inject Method with Mono.Cecil

How can I inject a custom method into a .net assembly using mono.cecil, and then call it in the entrypoint?
I like to do this to implement security methods after the binary is built.
To inject method you need to get the type you want to add it the method and then add a MethoDefinition.
var mainModule = ModuleDefinition.ReadModule(assemblyPath);
var type = module.Types.Single(t => t.Name == "TypeYouWant");
var newMethodDef= new MethodDefinition("Name", MethodAttributes.Public, mainModule.TypeSystem.Void);
type.Methods.Add(newMethodDef);
To call this method form the entry point, you need to get the entry point MethodDefinition and the new injected MethodReference and add instruction in the entry point method to call the new injected method.
var newMethodRef = type.Methods.Single(m => m.Name == "Name").Resolve();
var entryPoint= type.Methods.Single(m => m.Name == "YourEntryPoint");
var firstInstruction = entryPoint.Body.Instructions.First();
var il = entryPoint.Body.GetILProcessor();
il.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Callvirt, newMethodRef));
mainModule.Write(assemblyPath);
Note: Yes I know its C# and not VB but I'm sure once you got the idea you can easily convert it to VB.
You can make use of the Module.Import() function.
Example Class can be seen in the video:
https://www.youtube.com/watch?v=heTCisgYjhs
Credits to TheUnknownProgrammer's importer class.

Ability to set the context of the expression

Is there a way to set the context of the expression in Dynamic Expresso library, so that we can do something like the following:
interpreter.Eval("FirstName", new Parameter("person", new { FirstName="Homer", LastName="Simpson"}));
rather than
interpreter.Eval("person.FirstName", new Parameter("person", new { FirstName="Homer", LastName="Simpson"}));
Maybe we could have a another option that would say that the first parameter is to be used as the context for the expression.
I guess there could also be another version of Parse and Eval methods that simply takes the expression text and a simple object value that will serve as the expression context.
Other than that and the lack of support for dynamic types, I am really liking this library. I had worked on something similar, but had not added support for extension methods and generic method calls.
Thanks for the great library,
Neal
There isn't a built-in solution but you can simulate it in many ways:
Option 1: Inject an expression
var workingContext = new { FirstName = "homer" };
var workingContextExpression = Expression.Constant(workingContext);
var firstNameExpression = Expression.Property(workingContextExpression, "FirstName");
var interpreter = new Interpreter();
interpreter.SetExpression("FirstName", firstNameExpression);
Assert.AreEqual(workingContext.FirstName, interpreter.Eval("FirstName"));
Basically I inject an expression using SetExpression method. The injected expression is the property that you want to be available.
Option 2: Use this/me/it variable
You can inject a variable that will contain your working object. I usually call it this (or me or it depending on the application).
var workingContext = new { FirstName = "homer" };
var interpreter = new Interpreter();
interpreter.SetVariable("this", workingContext);
Assert.AreEqual(workingContext.FirstName, interpreter.Eval("this.FirstName"));
Option 3: A combination of the previous solutions
var workingContext = new { FirstName = "homer" };
var interpreter = new Interpreter();
interpreter.SetVariable("this", workingContext);
var firstNameExpression = interpreter.Parse("this.FirstName").LambdaExpression.Body;
interpreter.SetExpression("FirstName", firstNameExpression);
Assert.AreEqual(workingContext.FirstName, interpreter.Eval("FirstName"));
Equal to the first solution but I generate the expression using the parser itself.
Consider that all solutions assume that you must have an Interpreter instance for each context.
Disclaimer: I'm the author of Dynamic Expresso library.
Starting with DynamicExpresso v2.13.0, it's possible to define a variable named "this", that will be used for implicit resolution:
var target = new Interpreter();
target.SetVariable("this", new { FirstName="Homer", LastName="Simpson"});
// 'this' variable is used implicitly
Assert.AreEqual("Homer", target.Eval("FirstName"));
// 'this' variable can also be used explicitly
Assert.AreEqual("Homer", target.Eval("this.FirstName"));

Get exception when stubbing a property

When I run the following test:
[TestMethod]
public void MyTest()
{
var wizardCatalog = MockRepository.GenerateStub<IWizardCatalog>();
var firstQuestion = MockRepository.GenerateStub<IWizardQuestion>();
wizardCatalog.Stub(i => i.GetFirstQuestion()).Return(firstQuestion);
var choices = new List<IWizardChoice>();
firstQuestion.Stub(i => i.Choices).Return(choices);
}
I get this exception:
You are trying to set an expectation on a property that was defined to
use PropertyBehavior. Instead of writing code such as this:
mockObject.Stub(x => x.SomeProperty).Return(42); You can use the
property directly to achieve the same result: mockObject.SomeProperty
= 42;
Everything I read tells me that this stub operation is valid:
var choices = new List<IWizardChoice>();
firstQuestion.Stub(i => i.Choices).Return(choices);
What is going on?
PropertyBehaviour is on by default on stubs, but not on mocks. So you can either continue using a stub and change to the syntax suggested in the exception, or create a mock with GenerateMock<IWizardQuestion>() and use your existing .Stub(...).Return(...) syntax.

Resolving HttpRequestScoped Instances outside of a HttpRequest in Autofac

Suppose I have a dependency that is registered as HttpRequestScoped so there is only one instance per request. How could I resolve a dependency of the same type outside of an HttpRequest?
For example:
// Global.asax.cs Registration
builder.Register(c => new MyDataContext(connString)).As<IDatabase>().HttpRequestScoped();
_containerProvider = new ContainerProvider(builder.Build());
// This event handler gets fired outside of a request
// when a cached item is removed from the cache.
public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r)
{
// I'm trying to resolve like so, but this doesn't work...
var dataContext = _containerProvider.ApplicationContainer.Resolve<IDatabase>();
// Do stuff with data context.
}
The above code throws a DependencyResolutionException when it executes the CacheItemRemoved handler:
No scope matching the expression 'value(Autofac.Builder.RegistrationBuilder`3+<>c__DisplayClass0[MyApp.Core.Data.MyDataContext,Autofac.Builder.SimpleActivatorData,Autofac.Builder.SingleRegistrationStyle]).lifetimeScopeTag.Equals(scope.Tag)' is visible from the scope in which the instance was requested.
InstancePerLifetimeScope(), rather than HttpRequestScoped(), will give the result you need.
There is a caveat though - if IDatabase requires disposal, or depends on something that requires disposal, this won't happen if you resolve it from the ApplicationContainer. Better to do:
using (var cacheRemovalScope =
_containerProvider.ApplicationContainer.BeginLifetimeScope())
{
var dataContext = cacheRemovalScope.Resolve<IDatabase>();
// Do what y' gotta do...
}