Let's say I have an interface:
public interface ISomeInterface
{
bool SomeBool { get; set; }
string ValueIfSomeBool { get; set; }
}
And I have a number of classes that implement that. i.e.
public class ClassA : ISomeInterface
{
#region Implementation of ISomeInterface
public bool SomeBool { get; set; }
public string ValueIfSomeBool { get; set; }
#endregion
[NotNullValidator]
public string SomeOtherClassASpecificProp { get; set; }
}
And I have a Validation logic for the properties of this interface in a custom validator like so:
public class SomeInterfaceValidator : Validator<ISomeInterface>
{
public SomeInterfaceValidator (string tag)
: base(string.Empty, tag)
{
}
protected override string DefaultMessageTemplate
{
get { throw new NotImplementedException(); }
}
protected override void DoValidate(ISomeInterface objectToValidate, object currentTarget, string key, ValidationResults validationResults)
{
if (objectToValidate.SomeBool &&
string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool cannot be null or empty when SomeBool is TRUE", currentTarget, key, string.Empty, null));
}
if (!objectToValidate.SomeBool &&
!string.IsNullOrEmpty(objectToValidate.ValIfSomeBool))
{
validationResults.AddResult(new ValidationResult("ValIfSomeBool must be null when SomeBool is FALSE", currentTarget, key, string.Empty, null));
}
}
}
And I have an attribute for applying this validator that I decorate ISomeInterface with.
[AttributeUsage(AttributeTargets.Interface)]
internal class SomeInterfaceValidatorAttribute : ValidatorAttribute
{
protected override Validator DoCreateValidator(Type targetType)
{
return new SomeInterfaceValidator(this.Tag);
}
}
When I call Validation.Validate it doesn't seem to be firing the validation in SomeInterfaceValidator. It does the validation specific to ClassA but not that of the interface ISomeInterface.
How do I get this to work?
EDIT:
I found one way to get this to work and that is to do SelfValidation, where I cast to ISomeInterface and validate like so. This will suffice, but still leaving the question open to see if there are any other ways to accomplish this.
[SelfValidation]
public void DoValidate(ValidationResults results)
{
results.AddAllResults(Validation.Validate((ISomeInterface)this));
}
This is a limitation of the Validation Application Block. Here is an article that describes how to add Validator inheritance for VAB.
One approach to validate interfaces is to use the ValidationFactory to create a Validator for the interface instead of using the Validator.Validate() static facade or CreateValidator() based on the concrete type. For example this should work given your approach:
var validator = ValidationFactory.CreateValidator<ISomeInterface>();
ValidationResults validationResults = validator.Validate(someInterfaceInstance);
Related
I have a scenario for login user. I write this code for check user if validate return success message.
I am using the chain responsibility pattern for this validation but it seems ugly because I need to more new in this class.
Now I want to write clean and best practice for using this pattern.
How can I do this ?
public abstract class ValidateUser
{
protected readonly ValidateUser _validateUser;
public ValidateUser(ValidateUser validateUser)
{
_validateUser = validateUser;
}
public abstract UserContext ValidateUserLogin(UserContext request);
}
CheckIsActive :
public class CheckIsActive : ValidateUser
{
public CheckIsActive(ValidateUser validateUser) : base(validateUser)
{
}
public override UserContext ValidateUserLogin(UserContext request)
{
if (request.Context.IsActive)
{
return _validateUser.ValidateUserLogin(request);
}
return new UserContext
{
Message = "User Not Active"
};
}
}
CheckPhoneConfirmed :
public class CheckPhoneConfirmed : ValidateUser
{
public CheckPhoneConfirmed(ValidateUser validateUser) : base(validateUser)
{
}
public override UserContext ValidateUserLogin(UserContext request)
{
if (request.Context.ConfirmPhoneNumber)
{
return _validateUser.ValidateUserLogin(request);
}
return new UserContext
{
Message="Phone Number Not confirmed"
};
}
}
CheckIsLockedAccount :
public class CheckIsLockedAccount : ValidateUser
{
public CheckIsLockedAccount(ValidateUser validateUser) : base(validateUser)
{
}
public override UserContext ValidateUserLogin(UserContext request)
{
if (!request.Context.IsLockedEnd)
{
return new UserContext
{
Context = request.Context
};
}
return new UserContext
{
Message = $"Your account is deactivated from to date {request.Context.LockedEnd}"
};
}
}
and I use this Validate by this way :
var validate = new CheckIsActive(new CheckPhoneConfirmed(new CheckIsLockedAccount(null)));
var validateUserContext = validate.ValidateUserLogin(new UserContext
{
Context = findUSer.Result,
Message = null
});
You can use .net core Middleware pipeline, which is based upon Chain of Responsibility pattern only.
app.Use(async (context, next) =>
{
if (context.Request.HttpContext.User.HasClaim("IsLockedEnd", "true"))
{
await next();
}
});
app.Use(async (context, next) =>
{
if (context.Request.HttpContext.User.HasClaim("ConfirmPhoneNumber", "true"))
{
await next();
}
});
app.Use(async (context, next) =>
{
if (context.Request.HttpContext.User.HasClaim("IsActive", "true"))
{
await next();
}
});
I dont feel like this pattern fits here for validation.
If you google you find following description of your pattern:
Chain of Responsibility is behavioral design pattern that allows
passing request along the chain of potential handlers until one of
them handles request. The pattern allows multiple objects to handle
the request without coupling sender class to the concrete classes of
the receivers
I dont think any of that is the case in your solution. Since I feel you dont wanna handle different validations at different places?? I think you are missusing this pattern as a decorator pattern.
Instead try the following:
How about you split your objects into following:
First you need a abstract class so you can define later you validation rule
public abstract class ValidationRule
{
public string Property { get; set; }
public string Error { get; set; }
public ValidationRule(string property)
{
Property = property;
Error = property + " is not valid";
}
public ValidationRule(string property, string error)
: this(property)
{
Error = error;
}
// validation method. To be implemented in derived classes
public abstract bool Validate(Validator validator);
// gets value for given business object's property using reflection
protected object GetPropertyValue(Validator validator)
{
// note: reflection is relatively slow
return validator.GetType().GetProperty(Property).GetValue(validator, null);
}
}
Then you can this class to make a more concrete validator. Maybe a finished rule or something you can even reuse more as for example:
public class ValidateRegex : ValidationRule
{
protected string Pattern { get; set; }
public ValidateRegex(string propertyName, string pattern)
: base(propertyName)
{
Pattern = pattern;
}
public ValidateRegex(string propertyName, string errorMessage, string pattern)
: this(propertyName, pattern)
{
Error = errorMessage;
}
public override bool Validate(Validator validator)
{
return Regex.Match(GetPropertyValue(validator).ToString(), Pattern).Success;
}
}
and then make a final rule out of it
public class ValidateEmail : ValidateRegex
{
public ValidateEmail(string propertyName) :
base(propertyName, #"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")
{
Error = propertyName + " is not a valid email address";
}
public ValidateEmail(string propertyName, string errorMessage) :
this(propertyName)
{
Error = errorMessage;
}
}
The Validator can look something like this:
public abstract class Validator
{
// list of business rules
List<ValidationRule> rules = new List<ValidationRule>();
// list of validation errors (following validation failure)
List<string> errors = new List<string>();
// gets list of validations errors
public List<string> Errors
{
get { return errors; }
}
// adds a business rule to the business object
protected void AddRule(ValidationRule rule)
{
rules.Add(rule);
}
// determines whether business rules are valid or not.
// creates a list of validation errors when appropriate
public bool IsValid()
{
bool valid = true;
errors.Clear();
foreach (var rule in rules)
{
if (!rule.Validate(this))
{
valid = false;
errors.Add(rule.Error);
}
}
return valid;
}
}
You can use now the validator as following (Note if constructor when you implement a lot of different validation rules):
public class Person : Validator
{
public Person ()
{
AddRule(new ValidateEmail("Email"));
AddRule(new ValidateId("MemberId"));
AddRule(new ValidateRequired("Email"));
AddRule(new ValidateLength("Email", 1, 100));
AddRule(new ValidateRequired("CompanyName"));
AddRule(new ValidateLength("CompanyName", 1, 40));
AddRule(new ValidateRequired("City"));
AddRule(new ValidateLength("City", 1, 15));
AddRule(new ValidateRequired("Country"));
AddRule(new ValidateLength("Country", 1, 15));
}
public int MemberId { get; set; }
public string Email { get; set; }
public string CompanyName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int NumOrders { get; set; }
public DateTime LastOrderDate { get; set; }
}
If you call now the IsValid() method all your validationrules get executed.
I feel like this is kinda what you want. If you dont wanna tie it to an object, you could try to create a standalone validator and composite the validator into the class where you need it instead from deriving from it.
I am trying to create a custom attribute in console application but it is not working. My custom attribute never gets called. I found a good example here Custom Attribute not being hit
but not happy with its implementation.
I am wondering how data annotations works in MVC. we don't have to call it separately.
Is MVC calling those data annotations attribute behind the scene?
I wish to create custom attribute that I can use it on any class property same like data annotations attribute. But calling it separately like in above link is not what i am looking.
Here is what I have tried:
using System;
namespace AttributePractice
{
[AttributeUsage(AttributeTargets.Property)]
public class CustomMessageAttribute : Attribute
{
public static readonly CustomMessageAttribute Default = new CustomMessageAttribute();
protected string Message { get; set; }
public CustomMessageAttribute() : this(string.Empty)
{
Console.WriteLine("Default message is empty");
}
public CustomMessageAttribute(string message)
{
Message = message;
}
public string MyMessage =>
Message;
public override bool Equals(object obj)
{
if (obj == this)
return true;
if (obj is CustomMessageAttribute customMessageAttribute)
return customMessageAttribute.Message == MyMessage;
return false;
}
public override int GetHashCode()
{
return MyMessage.GetHashCode();
}
public override bool IsDefaultAttribute()
{
return Equals(Default);
}
}
public class Person
{
//This never works
// I am looking to use this attribute anywhere without calling it
// separately , same like data annotations
[CustomMessage("Hello world")]
public string Name { get; set; }
public int Age { get; set; }
public void DisplayPerson()
{
Console.WriteLine(Name);
Console.WriteLine(Age);
}
}
internal static class Program
{
private static void Main(string[] args)
{
var personObj = new Person
{
Name = "Tom",
Age = 28
};
personObj.DisplayPerson();
}
}
}
Can anybody tell me how to make my custom attribute works like data annotation way?
yes, if you need 10 custom attributes, you should create 10 separate.
There is tons of info about skipping Properties based on conditionals, but I would like to skip the entire object based on conditions within the object's class. I would like a solution that is contained within the object's class if at all possible. Keep in mind this is a collection of myObj that I am serializing.
public class myObj
{
bool conditional;
ShouldSerialize()
{
return conditional;
}
}
Or
public class myObj
{
[JsonCondition]
public bool conditional{get;}
}
Or even
[JsonCondition(typeof(MyConditionChecker))]
public class myObj
{
public bool conditional{get;}
}
class MyConditionChecker: JsonCondition
{
public override bool CanConvert(object sourceObj)
{
return (sourceObj as myObj).conditional;
}
}
What I got from your comments you would be best served creating your own wrapper around Json that applies the filtering.
public interface IConditionalSerializer
{
bool ShouldBeSerialized();
}
public static class FilteredSerializer
{
public static string SerializeConditional<T>(IEnumerable<T> input)
where T : IConiditionalSerializer
{
return JsonConvert.SerializeObject(input.Where(e => e.ShouldBeSerialized()));
}
}
public class Demo : IConditionalSerializer
{
public bool ShouldBeSerialized() => false;
}
You might also replace the interface with a reflection approach, but keep in mind the performance loss.
public interface IConiditionChecker
{
bool ShouldBeSerialized(object instance);
}
public class ConditionAttribute : Attribute
{
public Type ConditionChecker { get; set; }
}
public static class FilteredSerializer
{
public static string SerializeConditional(IEnumerable<object> input)
{
var matches = (from entry in input
let att = entry.GetType().GetCustomAttribute<ConditionAttribute>()
let hasChecker = att != null && att.ConditionChecker != null
let checker = hasChecker ? (IConiditionChecker)Activator.CreateInstance(att.ConditionChecker) : null
where checker.ShouldBeSerialized(entry)
select entry);
return JsonConvert.SerializeObject(matches);
}
}
[Condition(ConditionChecker = typeof(SomeChecker))]
public class Demo
{
}
Edit: Based on your comment you could do this. Only must decide wether to use opt-in or opt-out in the where-statement. It must ether be casted != null && casted.ShouldBeSerialized or what it currently says.
public interface IShouldBeSerialized
{
bool ShouldBeSerialized();
}
public static class FilteredSerializer
{
public static string SerializeConditional(IEnumerable<object> input)
{
var matches = (from entry in input
let casted = entry as IShouldBeSerialized
where casted == null || casted.ShouldBeSerialized()
select entry);
return JsonConvert.SerializeObject(matches);
}
}
public class Demo : IShouldBeSerialized
{
public bool ShouldBeSerialized()
{
return false;
}
}
If you're able to use the JSON.NET serializer, in terms of not serializing specific items within a collection, you could make the main collection non serializable, then add another filtered collection that does serialize.
public class Manager
{
[JsonIgnore]
public Employee[] Employees { get; set; }
[JsonProperty("Employees")]
public Employee[] SerializableEmployees
{
get { return Employees.Where(e => e.Name != "Bob").ToArray(); }
set { Employees = value; }
}
}
Alternatively, you could mark your class with the [JsonConverter] attribute and use a custom converter to check your condition. A similar approach that ignores a class entirely is detailed here.
I'm trying to make a design for some sort of IExecutable interface. I will not get into details, but the point is that I have several Actions that need to be executed from a base class. They may take different parameters (no big deal), and they may/may not return a value.
So far, this is my design:
public abstract class ActionBase
{
// ... snip ...
}
public abstract class ActionWithResultBase<T>: ActionBase
{
public abstract T Execute();
}
public abstract class ActionWithoutResultBase: ActionBase
{
public abstract void Execute();
}
So far, each of my concrete actions need to be a child from either ActionWithResultBase or ActionWithoutResult base, but I really don't like that. If I could move the definition of Execute to ActionBase, considering that the concrete class may or may not return a value, I will have achieved my goal.
Someone told me this could be done with using Func and Action, for which I totally agree, but I can't find a way to have that into one single class so that the caller would know if the action is going to return a value or not.
Brief: I want to do something like:
// Action1.Execute() returns something.
var a = new Action1();
var result = a.Execute();
// Action2.Execute() returns nothing.
var b = new Action2();
b.Execute();
If you want a lightweight solution, then the easiest option would be to write two concrete classes. One will contain a property of type Action and the other a property of type Func<T>:
public class ActionWithResult<T> : ActionBase {
public Func<T> Action { get; set; }
}
public class ActionWithoutResult : ActionBase {
public Action Action { get; set; }
}
Then you can construct the two types like this:
var a1 = new ActionWithResult<int> {
CanExecute = true,
Action = () => {
Console.WriteLine("hello!");
return 10;
}
}
If you don't want to make Action property read/write, then you could pass the action delegate as an argument to the constructor and make the property readonly.
The fact that C# needs two different delegates to represent functions and actions is quite annoying. One workaround that people use is to define a type Unit that represents "no return value" and use it instead of void. Then your type would be just Func<T> and you could use Func<Unit> instead of Action. The Unit type could look like this:
public class Unit {
public static Unit Value { get { return null; } }
}
To create a Func<Unit> value, you'll write:
Func<Unit> f = () => { /* ... */ return Unit.Value; }
The following interfaces should do the trick -- it's essentially copying the Nullable pattern
public interface IActionBase
{
bool HasResult { get; }
void Execute() { }
object Result { get; }
}
public interface IActionBase<T> : IActionBase
{
new T Result { get; }
}
public sealed class ActionWithReturnValue<T> : IActionBase<T>
{
public ActionWithReturnValue(Func<T> action) { _action = action; }
private Func<T> _action;
public bool HasResult { get; private set; }
object IActionBase.Result { get { return this.Result; } }
public T Result { get; private set; }
public void Execute()
{
HasResult = false;
Result = default(T);
try
{
Result = _action();
HasResult = true;
}
catch
{
HasResult = false;
Result = default(T);
}
}
}
public sealed class ActionWithoutReturnValue : IActionBase
{
public bool HasResult { get { return false; } }
object IActionBase.Result { get { return null; } }
public void Execute() { //... }
}
You know that you can ignore the return value of a method right? You don't have to use it.
what about something simple:
public class ActionExecuter
{
private MulticastDelegate del;
public ActionExecuter(MulticastDelegate del)
{
this.del = del;
}
public object Execute(params object[] p)
{
return del.DynamicInvoke(p);
}
}
Is it possible to do something like the following:
public class ChildClass : BaseClass
{
public ChildClass(BaseClass o)
{
base = o;
}
}
Basically, I want a transparent way to wrap a base class inside of other functionality. One example I've thought of is a custom Settings Provider which transparently audits the settings passed through it.
public class SettingsAuditor : SettingsProvider
{
public SettingsAuditor(SettingsProvider o)
{
base = o;
}
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals)
{
// Log the property change to a file
base.SetPropertyValues(context, propvals);
}
}
Then I could do the following:
mySettingsProvider = new SettingsAuditor(mySettingsProvider);
And all changes would go through the overridden SetPropertyValues before passing to the original object.
I could use a private SettingsProvider member, but then I either cannot inherit from SettingsProvider, or have an entire SettingsProvider (base) not being used at all.
I'm using C# 4.0 and .Net 4.0.
You cannot do base = o;
What you're looking for is the Decorator Pattern), which is a way to compositionally add functionality at runtime (vs. inheritance).
Instead of trying to set the base, you just contain the inner member. As long as the wrapper implements the same interface or base class as the inner object, you can pass back the new wrapper. You can wrap as many decorators as you want.
Consider:
public interface ICar
{
void Drive();
}
public class Car : ICar
{
public void Drive()
{
Console.WriteLine("vroom");
}
}
public class BuckleUp : ICar
{
ICar car;
public BuckleUp(ICar car) { this.car = car; }
public void Drive()
{
Console.WriteLine("click!");
car.Drive();
}
}
public class CheckMirrors : ICar
{
ICar car;
public CheckMirrors(ICar car) { this.car = car; }
public void Drive()
{
Console.WriteLine("mirrors adjusted");
car.Drive();
}
}
Now consider you have a method that accepts an ICar and tells it to drive. You could give it a Car, and it would work, but you could also wrap that car in a BuckleUp and a CheckMirrors and you wouldn't have to change that method at all. You've modified functionality through composition using the Decorator Pattern.
No. This looks like it should be a Composition vs Inheritance issue. You need to evaluate whether you are a "is a" or a "has a."
A little help for your journey
This is not a complete implmentation and it could probably be done much cleaner with expression trees... but this was a quick swing at faking AOP using DynamicObject with .Net 4.0.
public class MyDynamicWrapper<T> : DynamicObject
{
public T Wrapped { get; private set; }
public Action<T> Pre { get; private set; }
public Action<T> Post { get; private set; }
public MyDynamicWrapper(T wrapped, Action<T> pre, Action<T> post)
{
this.Wrapped = wrapped;
this.Pre = pre;
this.Post = post;
}
public override bool TryGetMember(
GetMemberBinder binder,
out object result)
{
var type = typeof(T);
var method = type.GetMethod(binder.Name);
if (method != null)
{
Func<object> func = () =>
{
if (Pre != null)
Pre(Wrapped);
// support for input parameters could be added here
var ret = method.Invoke(Wrapped, null);
if (Post != null)
Post(Wrapped);
return ret;
};
result = func;
return true;
}
return base.TryGetMember(binder, out result);
}
}
public class MyDynamicWrapper
{
public static MyDynamicWrapper<T> Create<T>(
T toWrap,
Action<T> pre = null,
Action<T> post = null)
{
return new MyDynamicWrapper<T>(toWrap, pre, post);
}
}
public class MyObject
{
public void MyMethod()
{
Console.WriteLine("Do Something");
}
}
class Program
{
static void Main()
{
var myobject = new MyObject();
dynamic mydyn = MyDynamicWrapper.Create(
myobject,
p => Console.WriteLine("before"),
p => Console.WriteLine("after"));
// Note that you have no intellisence...
// but you could use the old implmentation before you
// changed to this wrapped version.
mydyn.MyMethod();
/* output below
before
Do Something
after
*/
}
}
No, but you could fake it:
public class SettingsAuditor
{
SettingsProvider #base;
public SettingsAuditor(SettingsProvider o)
{
#base = o;
}
public void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals)
{
// Log the property change to a file
#base.SetPropertyValues(context, propvals);
}
}
Note here, #base isn't the actual base, just a varaible named base