Ejemplo n.º 1
0
        public static void AssertRuleCount(this BrokenRulesCollection @this, IPropertyInfo property, int expectedRuleCount, string message)
        {
            var ruleCount =
                (from brokenRule in @this
                 where brokenRule.Property == property.FriendlyName
                 select brokenRule).Count();
            var assertMessage = string.IsNullOrWhiteSpace(message) ?
                                string.Format(
                "Rule count was unexpected for property {0}", property.FriendlyName) :
                                string.Format(
                "Rule count was unexpected for property {0} : {1}", property.FriendlyName, message);

            Assert.AreEqual(expectedRuleCount, ruleCount, assertMessage);
        }
        public void WhenModelValidationCompletes_ValueExpressionIsValid_IsUpdated()
        {
            // Arrange.
            var model = Mock.Create<UrlCallParameterEdit>();
            var vm = new UrlCallParameterViewModel();
            vm.Initialize(model);

            var nameBrokenRule = Mock.Create<BrokenRule>();
            Mock.Arrange(() => nameBrokenRule.Property).Returns(UrlCallParameterEdit.NameProperty.Name);

            var valueBrokenRule = Mock.Create<BrokenRule>();
            Mock.Arrange(() => valueBrokenRule.Property).Returns(UrlCallParameterEdit.ValueProperty.Name);

            var brokenRules1 = new BrokenRulesCollection { nameBrokenRule };
            var brokenRules2 = new BrokenRulesCollection { valueBrokenRule };

            Mock.Arrange(() => model.BrokenRulesCollection).Returns(brokenRules1);

            bool? validationResult = null;

            vm.PropertyChanged += (sender, e) =>
                {
                    if (e.PropertyName == TestsHelper.ExtractPropertyName(() => vm.ValueExpressionIsValid))
                        validationResult = vm.ValueExpressionIsValid;
                };

            // Act.
            Mock.Raise(() => model.ValidationComplete += null, EventArgs.Empty);

            // Assert.
            Assert.AreEqual(true, validationResult);

            // Arrange.
            Mock.Arrange(() => model.BrokenRulesCollection).Returns(brokenRules2);
            validationResult = null;

            // Act.
            Mock.Raise(() => model.ValidationComplete += null, EventArgs.Empty);

            // Assert.
            Assert.AreEqual(false, validationResult);
        }
Ejemplo n.º 3
0
        public static void AssertBusinessRuleExists <T>(this BrokenRulesCollection @this, IPropertyInfo property, bool shouldExist)
            where T : IBusinessRule
        {
            var ruleTypeName = typeof(T).FullName;

            var foundRule =
                (from brokenRule in @this
                 where (brokenRule.Property == property.FriendlyName &&
                        brokenRule.RuleName == new RuleUri(ruleTypeName, property.Name).ToString())
                 select brokenRule).SingleOrDefault();

            if (shouldExist)
            {
                Assert.IsNotNull(foundRule, string.Format(
                                     "Property {0} does not contain rule {1}", property.FriendlyName, ruleTypeName));
            }
            else
            {
                Assert.IsNull(foundRule, string.Format(
                                  "Property {0} contains rule {1}", property.FriendlyName, ruleTypeName));
            }
        }
Ejemplo n.º 4
0
        public static void AssertValidationRuleExists <T>(this BrokenRulesCollection @this, IPropertyInfo property, bool shouldExist)
            where T : ValidationAttribute
        {
            var ruleTypeName = typeof(T).Name;

            var foundRule =
                (from brokenRule in @this
                 where (brokenRule.Property == property.Name &&
                        brokenRule.RuleName.Replace("/", string.Empty).ToLower().Contains(ruleTypeName.ToLower()))
                 select brokenRule).SingleOrDefault();

            if (shouldExist)
            {
                Assert.IsNotNull(foundRule, string.Format(
                                     "Property {0} does not contain rule {1}", property.Name, ruleTypeName));
            }
            else
            {
                Assert.IsNull(foundRule, string.Format(
                                  "Property {0} contains rule {1}", property.Name, ruleTypeName));
            }
        }
Ejemplo n.º 5
0
        private static void ValidateEntity(Entity target, BrokenRulesCollection res, ValidatorActions actions, Func<IRule, bool> filter)
        {
            var stopOnFirst = HasAction(actions, ValidatorActions.StopOnFirstBroken);

            var rules = ValidationHelper.GetTypeRules(target.FindRepository() as ITypeValidationsHost, target.GetType());
            if (rules != null)
            {
                //先验证所有属性。
                foreach (var de in rules.PropertyRules)
                {
                    CheckRules(target, de.Value, res, actions, filter);
                    if (stopOnFirst && res.Count > 0) return;
                }

                //再验证整个实体。
                CheckRules(target, rules.TypeRules, res, actions, filter);
                if (stopOnFirst && res.Count > 0) return;
            }

            if (HasAction(actions, ValidatorActions.ValidateChildren))
            {
                foreach (var child in target.GetLoadedChildren())
                {
                    var list = child.Value as EntityList;
                    if (list != null)
                    {
                        list.EachNode(childEntity =>
                        {
                            ValidateEntity(childEntity, res, actions, filter);
                            if (stopOnFirst && res.Count > 0) return true;
                            return false;
                        });
                        if (stopOnFirst && res.Count > 0) return;
                    }
                    else
                    {
                        ValidateEntity(child.Value as Entity, res, actions, filter);
                        if (stopOnFirst && res.Count > 0) return;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private static void CheckRules(
            Entity target,
            RulesContainer rules, BrokenRulesCollection brokenRulesList,
            ValidatorActions actions, Func<IRule, bool> ruleFilter
            )
        {
            var list = rules.GetList(true);

            var ignoreDataSourceValidations = HasAction(actions, ValidatorActions.IgnoreDataSourceValidations);
            var stopOnFirstBroken = HasAction(actions, ValidatorActions.StopOnFirstBroken);

            for (int index = 0; index < list.Count; index++)
            {
                IRule rule = list[index];

                //连接数据源的验证规则可能需要被过滤掉。
                if (ignoreDataSourceValidations && rule.ValidationRule.ConnectToDataSource) { continue; }

                //如果与指定的范围不符合,也需要过滤掉。
                if (ruleFilter != null && !ruleFilter(rule)) { continue; }

                var args = new RuleArgs(rule);

                try
                {
                    args.BrokenDescription = null;
                    rule.ValidationRule.Validate(target, args);
                }
                catch (Exception ex)
                {
                    throw new ValidationException("Properties.Resources.ValidationRulesException" + args.Property.Name + rule.Key, ex);
                }

                if (args.IsBroken)
                {
                    brokenRulesList.Add(rule, args);

                    if (stopOnFirstBroken) { break; }
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 检查整个实体对象是否满足规则
        /// </summary>
        /// <param name="target">要验证的实体。</param>
        /// <param name="actions">验证时的行为。</param>
        /// <param name="ruleFilter">要验证的规则的过滤器。</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">target</exception>
        public static BrokenRulesCollection Validate(
            this Entity target,
            ValidatorActions actions,
            Func<IRule, bool> ruleFilter
            )
        {
            if (target == null) throw new ArgumentNullException("target");

            var res = new BrokenRulesCollection();

            ValidateEntity(target, res, actions, ruleFilter);

            return res;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 检查某个属性是否满足规则
        /// </summary>
        /// <param name="target">要验证的实体。</param>
        /// <param name="property">托管属性</param>
        /// <param name="actions">验证时的行为。</param>
        /// <param name="ruleFilter">要验证的规则的过滤器。</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">target
        /// or
        /// property</exception>
        public static BrokenRulesCollection Validate(
            this Entity target, IManagedProperty property,
            ValidatorActions actions,
            Func<IRule, bool> ruleFilter
            )
        {
            if (target == null) throw new ArgumentNullException("target");
            if (property == null) throw new ArgumentNullException("property");

            var res = new BrokenRulesCollection();

            //获取指定实体的规则容器
            var rulesManager = ValidationHelper.GetTypeRules(target.FindRepository() as ITypeValidationsHost, target.GetType());
            if (rulesManager != null)
            {
                // get the rules list for this property
                RulesContainer rulesList = rulesManager.GetRulesForProperty(property, false);
                if (rulesList != null)
                {
                    // get the actual list of rules (sorted by priority)
                    CheckRules(target, rulesList, res, actions, ruleFilter);
                }
            }

            return res;
        }
Ejemplo n.º 9
0
    void IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit)
    {
      if (((IUndoableObject)this).EditLevel > 0)
      {
        if (((IUndoableObject)this).EditLevel - 1 < parentEditLevel)
          throw new UndoException(string.Format(Properties.Resources.EditLevelMismatchException, "UndoChanges"));

        SerializationInfo state = _stateStack.Pop();
        OnSetState(state, StateMode.Undo);

        lock (SyncRoot)
          _brokenRules = null;

        if (state.Values.ContainsKey("_rules"))
        {
          byte[] rules = Convert.FromBase64String(state.GetValue<string>("_rules"));

          lock (SyncRoot)
            _brokenRules = (BrokenRulesCollection)MobileFormatter.Deserialize(rules);
        }
      }
    }
Ejemplo n.º 10
0
    /// <summary>
    /// Override this method to retrieve your child object
    /// references from the MobileFormatter serialzation stream.
    /// </summary>
    /// <param name="info">
    /// Object containing the data to serialize.
    /// </param>
    /// <param name="formatter">
    /// Reference to MobileFormatter instance. Use this to
    /// convert child references to/from reference id values.
    /// </param>
    protected override void OnSetChildren(SerializationInfo info, MobileFormatter formatter)
    {
      if (info.Children.ContainsKey("_brokenRules"))
      {
        int referenceId = info.Children["_brokenRules"].ReferenceId;
        _brokenRules = (BrokenRulesCollection)formatter.GetObject(referenceId);
      }

      base.OnSetChildren(info, formatter);
    }
Ejemplo n.º 11
0
 public ValidatorException(string message, BrokenRulesCollection brokenRules)
     : base(message)
 {
     _brokenRules = brokenRules;
 }
Ejemplo n.º 12
0
 public static bool Contains(this BrokenRulesCollection brokenRules, string ruleName)
 {
     return(brokenRules.Any(brokenRule => brokenRule.RuleName == ruleName));
 }
Ejemplo n.º 13
0
 public static void AssertRuleCount(this BrokenRulesCollection @this, IPropertyInfo property, int expectedRuleCount)
 {
     @this.AssertRuleCount(property, expectedRuleCount, string.Empty);
 }
Ejemplo n.º 14
0
 public static void AssertRuleCount(this BrokenRulesCollection @this, int expectedRuleCount)
 {
     Assert.AreEqual(expectedRuleCount, @this.Count);
 }