Question

I've developed a custom aspect for PostSharp, which used to work fine, but fails now that I have updated my project to use the latest PostSharp NuGet. The aspect is as follows:

[HasConstraint]
public sealed class NotDefaultAttribute : LocationContractAttribute, ILocationValidationAspect<ValueType>, ILocationValidationAspect, IAspect
{
    public NotDefaultAttribute()
    {
        ErrorMessage = "The {2} cannot be empty.";
    }

    public Exception ValidateValue(ValueType value, string locationName, LocationKind locationKind)
    {
        if (value == null)
            return null;

        var type = value.GetType();
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            if (value.Equals(Activator.CreateInstance(type.GetGenericArguments()[0])))
                return CreateArgumentException(value, locationName, locationKind);
        }
        else if (value.Equals(Activator.CreateInstance(type)))
            return CreateArgumentNullException(value, locationName, locationKind);

        return null;
    }
}

And a sample use of the aspect would be:

public class Example
{
    [NotDefault]
    public DateTime Timestamp { get; set; }
}

When code tries to set the property, as in this example...

new Example().Timestamp = DateTime.UtcNow;

... I get the following MissingMethodException:

System.MissingMethodException: Method not found: 'System.Exception NotDefaultAttribute.ValidateValue(System.ValueType, System.String, PostSharp.Reflection.LocationKind)'.
   at Example.set_Timestamp(DateTime value)

Downgrading PostSharp to 3.0.36 fixes this issue. But, this isn't really an option as we're about to switch to .NET 4.5.1 which requires 3.0.38 or better. (Not to mention, being stuck on an old release is a pain.)

Was it helpful?

Solution

The support for the described use case has been implemented in PostSharp version 3.1.27. Starting with that version it's possible to apply validation aspect with method ValidateValue(ValueType value, ...) on any value type property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top