Exemplo n.º 1
0
        /// <summary> Returns true if a member is enabled. </summary>
        public static bool IsEnabled(IMemberData property, object instance,
                                     out IMemberData dependentProp, out IComparable dependentValue, out bool hidden)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            ITypeData instanceType    = TypeData.GetTypeData(instance);
            var       dependencyAttrs = property.GetAttributes <EnabledIfAttribute>();

            dependentProp  = null;
            dependentValue = 0;
            hidden         = false;
            bool enabled = true;

            foreach (var at in dependencyAttrs)
            {
                bool newEnabled = true;
                dependentProp = instanceType.GetMember(at.PropertyName);

                if (dependentProp == null)
                {
                    // We cannot be sure that the step developer has used this attribute correctly
                    // (could just be a typo in the (weakly typed) property name), thus we need to
                    // provide a good error message that leads the developer to where the error is.
                    log.Warning("Could not find property '{0}' on '{1}'. EnabledIfAttribute can only refer to properties of the same class as the property it is decorating.", at.PropertyName, instanceType.Name);
                    enabled = false;
                    return(false);
                }

                var depValue = dependentProp.GetValue(instance);

                try
                {
                    newEnabled = calcEnabled(at, depValue);
                }
                catch (ArgumentException)
                {
                    // CompareTo throws ArgumentException when obj is not the same type as this instance.
                    newEnabled = false;
                }
                if (!newEnabled && at.HideIfDisabled)
                {
                    hidden = true;
                }

                enabled &= newEnabled;
            }
            return(enabled);
        }