I want to create a custom attribute that can be used on a property like:
[TrimInputString]
public string FirstName { get; set; }
that will
iam doing this , not very convincing way but its working
demo class
public class User
{
[TitleCase]
public string FirstName { get; set; }
[TitleCase]
public string LastName { get; set; }
[UpperCase]
public string Salutation { get; set; }
[LowerCase]
public string Email { get; set; }
}
Writing Attribute for LowerCase, others can be written in the similar manner
public class LowerCaseAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//try to modify text
try
{
validationContext
.ObjectType
.GetProperty(validationContext.MemberName)
.SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
}
catch (System.Exception)
{
}
//return null to make sure this attribute never say iam invalid
return null;
}
}
Not very elegant way as its actually implementing Validation attribute but it works
That's not how attributes work. You can't access whatever the attribute is attached to from within the constructor.
If you want to make this work, you'll need to make some kind of processor class to which you pass the object, which then goes through the fields and does something depending on the attributes. The operation to do may be defined within the attribute (an abstract base attribute is handy here), but you'll still need to go through the fields by hand to apply the operation.
This can be done with Dado.ComponentModel.Mutations.
public class User
{
[Trim]
public string FirstName { get; set; }
}
// Then to preform mutation
var user = new User() {
FirstName = " David Glenn "
}
new MutationContext<User>(user).Mutate();
You can see more documentation here.
As Matti pointed out, this is not how attributes work. However, you could use the PostSharp AOP framework to accomplish this, probably overriding OnMethodBoundaryAspect. But this is not trivial.