public LoginViewController()
        {
            BrokenRules.Add(new BrokenRule()
            {
                Check   = () => !string.IsNullOrWhiteSpace(InputObject.Username),
                Balance = "The Username is required."
            });

            var emailValidator = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

            BrokenRules.Add(new BrokenRule()
            {
                Check   = () => emailValidator.IsMatch(InputObject.Username),
                Balance = "The Username must be a valid email address."
            });
            BrokenRules.Add(new BrokenRule()
            {
                Check   = () => !(InputObject.Password == null && InputObject.Password.Equals("")),
                Balance = "The Password is required."
            });
        }
        /// <summary>
        /// Creates and returns a string representation of the current exception.
        /// </summary>
        /// <param name="includeState">Boolean</param>
        /// <returns>
        /// A string representation of the current exception.
        /// </returns>
        /// <PermissionSet>
        ///     <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" PathDiscovery="*AllFiles*"/>
        /// </PermissionSet>
        public string ToString(bool includeState)
        {
            var sb = new StringBuilder();

            if (BrokenRules.Count == 1)
            {
                sb.Append("1 broken rule. All rules must pass.");
            }
            else
            {
                sb.AppendFormat("{0} broken rules. All rules must pass.", BrokenRules.Count);
            }

            sb.AppendLine();

            foreach (KeyValuePair <object, List <BrokenRule> > entity in BrokenRules.GroupByEntity())
            {
                if (entity.Key != null && entity.Key is ILinqEntity)
                {
                    sb.AppendLine();
                    sb.AppendFormat("Type: {0}", entity.Key.GetType().Name);
                    sb.AppendLine();
                }

                foreach (BrokenRule rule in entity.Value)
                {
                    sb.AppendFormat("  - {0}", rule.Message);
                    sb.AppendLine();
                }
                sb.AppendLine();

                if (includeState && entity.Key != null && entity.Key is ILinqEntity)
                {
                    sb.AppendLine("  State:");
                    sb.AppendLine(((ILinqEntity)entity.Key).ToEntityString(2, "  "));
                }
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Checks all validation rules against entity values.
        /// </summary>
        public void CheckAllRules()
        {
            Boolean foundBrokenRule = false;
            Boolean hasBrokenRules  = BrokenValidationRulesCount != 0;

            BrokenRules.Clear();

            foreach (String item in ValidationRulesManager.GetAllPropertyNamesWithRules())
            {
                Object value = this.GetType().GetProperty(item).GetValue(this, null);

                if (CheckRulesForProperty(item, value, CalledByCheckAllRules.Yes))
                {
                    foundBrokenRule = true;
                }
            }

            if (foundBrokenRule || hasBrokenRules)
            {
                RaiseBrokenRuleFountNotification(foundBrokenRule);
            }
        }
Exemple #4
0
 /// <summary>
 /// Validate the rules list
 /// </summary>
 /// <param name="list">list of rules</param>
 private void ValidateRulesList(List <ValidateRuleBase> list)
 {
     foreach (ValidateRuleBase rule in list)
     {
         PropertyInfo info = _parentObject.GetType().GetProperty(rule.PropertyName);
         if (info != null)
         {
             object value = info.GetValue(_parentObject, null);
             if (rule.Validate(value))
             {
                 BrokenRules.Remove(rule);
             }
             else
             {
                 BrokenRules.Add(rule);
             }
         }
         else
         {
             throw new ArgumentException(string.Format("Property \"{0}\" not found on object \"{1}\"", rule.PropertyName, _parentObject.GetType().ToString()));
         }
     }
 }
Exemple #5
0
        /// <summary>
        /// Invokes all rules for a specific property.
        /// </summary>
        private List <string> CheckRulesForProperty(Csla.Core.IPropertyInfo property, bool cascade)
        {
            var rules = from r in TypeRules.Rules
                        where ReferenceEquals(r.PrimaryProperty, property)
                        orderby r.Priority
                        select r;
            var affectedProperties = new List <string> {
                property.Name
            };

            BrokenRules.ClearRules(property);
            affectedProperties.AddRange(RunRules(rules));

            if (cascade)
            {
                // get properties affected by all rules
                var propertiesToRun = new List <Csla.Core.IPropertyInfo>();
                foreach (var item in rules)
                {
                    foreach (var p in item.AffectedProperties)
                    {
                        if (!ReferenceEquals(property, p))
                        {
                            propertiesToRun.Add(p);
                        }
                    }
                }
                // run rules for affected properties
                foreach (var item in propertiesToRun.Distinct())
                {
                    CheckRulesForProperty(item, false);
                }
            }

            return(affectedProperties.Distinct().ToList());
        }
 public void AddBrokenRule(BusinessRule error)
 {
     BrokenRules.Add(error);
 }
Exemple #7
0
 protected override void ValidateRules(BrokenRules Verify)
 {
     Verify.IsTrue(!string.IsNullOrEmpty(m_pass), "NOPASS",
                   "A password is required.",
                   "Password");
 }
 public static Exception ConvertToBrokenRulesException(this InvalidStateException invalidStateProblems)
 {
     BrokenRules brokenRules = invalidStateProblems.GetInvalidValues().ToBrokenRules();
     return new BrokenRulesException("Problem writing changes to database. See BrokenRules", brokenRules);
 }
Exemple #9
0
 public CustomValidationException(string errorMessage, Exception ex)
 {
     BrokenRules.Add(string.Empty, errorMessage);
     _innerException = ex;
 }
Exemple #10
0
        /// <summary>
        /// Updates the state on control Property.
        /// </summary>
        protected virtual void UpdateState()
        {
            if (_loading)
            {
                return;
            }

            Popup popup = (Popup)FindChild(this, "popup");

            if (popup != null)
            {
                popup.IsOpen = false;
            }

            if (Source == null || string.IsNullOrEmpty(PropertyName))
            {
                BrokenRules.Clear();
                RuleDescription = string.Empty;
                IsValid         = true;
                CanWrite        = false;
                CanRead         = false;
            }
            else
            {
                var iarw = Source as Csla.Security.IAuthorizeReadWrite;
                if (iarw != null)
                {
                    CanWrite = iarw.CanWriteProperty(PropertyName);
                    CanRead  = iarw.CanReadProperty(PropertyName);
                }

                BusinessBase businessObject = Source as BusinessBase;
                if (businessObject != null)
                {
                    var allRules = (from r in businessObject.BrokenRulesCollection
                                    where r.Property == PropertyName
                                    select r).ToArray();

                    var removeRules = (from r in BrokenRules
                                       where !allRules.Contains(r)
                                       select r).ToArray();

                    var addRules = (from r in allRules
                                    where !BrokenRules.Contains(r)
                                    select r).ToArray();

                    foreach (var rule in removeRules)
                    {
                        BrokenRules.Remove(rule);
                    }
                    foreach (var rule in addRules)
                    {
                        BrokenRules.Add(rule);
                    }

                    IsValid = BrokenRules.Count == 0;

                    if (!IsValid)
                    {
                        BrokenRule worst = (from r in BrokenRules
                                            orderby r.Severity
                                            select r).FirstOrDefault();

                        if (worst != null)
                        {
                            RuleSeverity    = worst.Severity;
                            RuleDescription = worst.Description;
                        }
                        else
                        {
                            RuleDescription = string.Empty;
                        }
                    }
                    else
                    {
                        RuleDescription = string.Empty;
                    }
                }
                else
                {
                    BrokenRules.Clear();
                    RuleDescription = string.Empty;
                    IsValid         = true;
                }
            }
            GoToState(true);
        }
Exemple #11
0
        /// <summary>
        /// Invokes all rules for a specific property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="cascade">if set to <c>true</c> [cascade].</param>
        /// <param name="executionContext">The execute context.</param>
        /// <returns></returns>
        private List <string> CheckRulesForProperty(Csla.Core.IPropertyInfo property, bool cascade, RuleContextModes executionContext)
        {
            var rules = from r in TypeRules.Rules
                        where ReferenceEquals(r.PrimaryProperty, property) &&
                        CanRunRule(r, executionContext)
                        orderby r.Priority
                        select r;

            BrokenRules.ClearRules(property);
            var firstResult = RunRules(rules, cascade, executionContext);

            if (CascadeOnDirtyProperties)
            {
                cascade = cascade || firstResult.DirtyProperties.Any();
            }
            if (cascade)
            {
                // get properties affected by all rules
                var propertiesToRun = new List <Csla.Core.IPropertyInfo>();
                foreach (var item in rules)
                {
                    if (!item.IsAsync)
                    {
                        foreach (var p in item.AffectedProperties)
                        {
                            if (!ReferenceEquals(property, p))
                            {
                                propertiesToRun.Add(p);
                            }
                        }
                    }
                }

                // add PrimaryProperty where property is in InputProperties
                var input = from r in TypeRules.Rules
                            where !ReferenceEquals(r.PrimaryProperty, property) &&
                            r.PrimaryProperty != null &&
                            r.InputProperties != null &&
                            r.InputProperties.Contains(property)
                            select r.PrimaryProperty;

                foreach (var p in input)
                {
                    if (!ReferenceEquals(property, p))
                    {
                        propertiesToRun.Add(p);
                    }
                }
                // run rules for affected properties
                foreach (var item in propertiesToRun.Distinct())
                {
                    var doCascade = false;
                    if (CascadeOnDirtyProperties)
                    {
                        doCascade = firstResult.DirtyProperties.Any(p => p == item.Name);
                    }
                    firstResult.AffectedProperties.AddRange(CheckRulesForProperty(item, doCascade,
                                                                                  executionContext | RuleContextModes.AsAffectedPoperty));
                }
            }

            // always make sure to add PrimaryProperty
            firstResult.AffectedProperties.Add(property.Name);
            return(firstResult.AffectedProperties.Distinct().ToList());
        }
Exemple #12
0
 /// <summary>
 /// Determine any broken business rules
 /// </summary>
 public override void Validate()
 {
     BrokenRules.AddRule("reqGroupId", "Group Id is required", GroupId < 1);
     BrokenRules.AddRule("reqFirstName", "FirstName is required", string.IsNullOrWhiteSpace(FirstName));
     BrokenRules.AddRule("reqLastName", "LastName is required", string.IsNullOrWhiteSpace(LastName));
 }
Exemple #13
0
 /// <summary>
 /// Determine any broken business rules
 /// </summary>
 public override void Validate()
 {
     BrokenRules.AddRule("reqCustomerId", "Customer Id is required", CustomerId < 1);
     BrokenRules.AddRule("reqMake", "Make is required", string.IsNullOrWhiteSpace(Make));
     BrokenRules.AddRule("invYear", "Year can not be in the future", Year != null && Year > DateTime.Now.Year);
 }
Exemple #14
0
 protected void AddBrokenRule(BusinessRule businessRule)
 {
     BrokenRules.Add(businessRule);
 }
Exemple #15
0
        private List <string> RunRules(IEnumerable <IBusinessRule> rules)
        {
            var  affectedProperties = new List <string>();
            bool anyRuleBroken      = false;

            foreach (var rule in rules)
            {
                // implicit short-circuiting
                if (anyRuleBroken && rule.Priority > ProcessThroughPriority)
                {
                    break;
                }
                bool complete = false;
                // set up context
                var context = new RuleContext((r) =>
                {
                    if (r.Rule.IsAsync)
                    {
                        lock (SyncRoot)
                        {
                            // update output values
                            if (r.OutputPropertyValues != null)
                            {
                                foreach (var item in r.OutputPropertyValues)
                                {
                                    ((IManageProperties)_target).LoadProperty(item.Key, item.Value);
                                }
                            }
                            // update broken rules list
                            if (r.Results != null)
                            {
                                foreach (var result in r.Results)
                                {
                                    BrokenRules.SetBrokenRule(result);
                                }
                            }

                            // mark each property as not busy
                            foreach (var item in r.Rule.AffectedProperties)
                            {
                                BusyProperties.Remove(item);
                                _isBusy = BusyProperties.Count > 0;
                                if (!BusyProperties.Contains(item))
                                {
                                    _target.RuleComplete(item);
                                }
                            }
                            if (!RunningRules && !RunningAsyncRules)
                            {
                                _target.AllRulesComplete();
                            }
                        }
                    }
                    else // Rule is Sync
                    {
                        // update output values
                        if (r.OutputPropertyValues != null)
                        {
                            foreach (var item in r.OutputPropertyValues)
                            {
                                ((IManageProperties)_target).LoadProperty(item.Key, item.Value);
                            }
                        }
                        // update broken rules list
                        if (r.Results != null)
                        {
                            foreach (var result in r.Results)
                            {
                                BrokenRules.SetBrokenRule(result);
                            }
                            // is any rules here broken with severity Error
                            if (r.Results.Where(p => !p.Success && p.Severity == RuleSeverity.Error).Any())
                            {
                                anyRuleBroken = true;
                            }
                        }

                        complete = true;
                    }
                });
                context.Rule = rule;
                if (!rule.IsAsync || rule.ProvideTargetWhenAsync)
                {
                    context.Target = _target;
                }

                // get input properties
                if (rule.InputProperties != null)
                {
                    var target = _target as Core.IManageProperties;
                    context.InputPropertyValues = new Dictionary <IPropertyInfo, object>();
                    foreach (var item in rule.InputProperties)
                    {
                        context.InputPropertyValues.Add(item, target.ReadProperty(item));
                    }
                }

                // mark properties busy
                if (rule.IsAsync)
                {
                    lock (SyncRoot)
                    {
                        // mark each property as busy
                        foreach (var item in rule.AffectedProperties)
                        {
                            var alreadyBusy = BusyProperties.Contains(item);
                            BusyProperties.Add(item);
                            _isBusy = true;
                            if (!alreadyBusy)
                            {
                                _target.RuleStart(item);
                            }
                        }
                    }
                }

                // execute (or start executing) rule
                try
                {
                    rule.Execute(context);
                }
                catch (Exception ex)
                {
                    context.AddErrorResult(string.Format("{0}:{1}", rule.RuleName, ex.Message));
                    if (rule.IsAsync)
                    {
                        context.Complete();
                    }
                }

                if (!rule.IsAsync)
                {
                    // process results
                    if (!complete)
                    {
                        context.Complete();
                    }
                    // copy affected property names
                    affectedProperties.AddRange(rule.AffectedProperties.Select(c => c.Name));
                    // copy output property names
                    if (context.OutputPropertyValues != null)
                    {
                        affectedProperties.AddRange(context.OutputPropertyValues.Select(item => item.Key.Name));
                    }
                    if (context.Results != null)
                    {
                        // explicit short-circuiting
                        if (context.Results.Where(r => r.StopProcessing).Any())
                        {
                            break;
                        }
                    }
                }
            }
            // return any synchronous results
            return(affectedProperties);
        }
Exemple #16
0
 public CustomValidationException(BrokenRules brokenRules)
 {
     _brokenRules = brokenRules;
 }
Exemple #17
0
 /// <summary>
 /// Determine any broken business rules
 /// </summary>
 public override void Validate()
 {
     BrokenRules.AddRule("reqGroupName", "GroupName is required", string.IsNullOrWhiteSpace(GroupName));
 }
Exemple #18
0
 public CustomValidationException(string errorMessage)
 {
     BrokenRules.Add(string.Empty, errorMessage);
 }
Exemple #19
0
        /// <summary>
        /// Runs the enumerable list of rules.
        /// </summary>
        /// <param name="rules">The rules.</param>
        /// <param name="cascade">if set to <c>true</c> cascade.</param>
        /// <param name="executionContext">The execution context.</param>
        /// <returns></returns>
        private RunRulesResult RunRules(IEnumerable <IBusinessRule> rules, bool cascade, RuleContextModes executionContext)
        {
            var  affectedProperties = new List <string>();
            var  dirtyProperties    = new List <string>();
            bool anyRuleBroken      = false;

            foreach (var rule in rules)
            {
                // implicit short-circuiting
                if (anyRuleBroken && rule.Priority > ProcessThroughPriority)
                {
                    break;
                }
                bool complete = false;
                // set up context
                var context = new RuleContext((r) =>
                {
                    if (r.Rule.IsAsync)
                    {
                        lock (SyncRoot)
                        {
                            // update output values
                            if (r.OutputPropertyValues != null)
                            {
                                foreach (var item in r.OutputPropertyValues)
                                {
                                    // value is changed add to dirtyValues
                                    if (((IManageProperties)_target).LoadPropertyMarkDirty(item.Key, item.Value))
                                    {
                                        r.AddDirtyProperty(item.Key);
                                    }
                                }
                            }
                            // update broken rules list
                            BrokenRules.SetBrokenRules(r.Results, r.OriginPropertyName);

                            // run rules on affected properties for this async rule
                            var affected = new List <string>();
                            if (cascade)
                            {
                                foreach (var item in r.Rule.AffectedProperties.Distinct())
                                {
                                    if (!ReferenceEquals(r.Rule.PrimaryProperty, item))
                                    {
                                        var doCascade = false;
                                        if (CascadeOnDirtyProperties && (r.DirtyProperties != null))
                                        {
                                            doCascade = r.DirtyProperties.Any(p => p.Name == item.Name);
                                        }
                                        affected.AddRange(CheckRulesForProperty(item, doCascade, r.ExecuteContext | RuleContextModes.AsAffectedPoperty));
                                    }
                                }
                            }

                            // mark each property as not busy
                            foreach (var item in r.Rule.AffectedProperties)
                            {
                                BusyProperties.Remove(item);
                                _isBusy = BusyProperties.Count > 0;
                                if (!BusyProperties.Contains(item))
                                {
                                    _target.RuleComplete(item);
                                }
                            }

                            foreach (var property in affected.Distinct())
                            {
                                // property is not in AffectedProperties (already signalled to UI)
                                if (!r.Rule.AffectedProperties.Any(p => p.Name == property))
                                {
                                    _target.RuleComplete(property);
                                }
                            }

                            if (!RunningRules && !RunningAsyncRules)
                            {
                                _target.AllRulesComplete();
                            }
                        }
                    }
                    else // Rule is Sync
                    {
                        // update output values
                        if (r.OutputPropertyValues != null)
                        {
                            foreach (var item in r.OutputPropertyValues)
                            {
                                // value is changed add to dirtyValues
                                if (((IManageProperties)_target).LoadPropertyMarkDirty(item.Key, item.Value))
                                {
                                    r.AddDirtyProperty(item.Key);
                                }
                            }
                        }

                        // update broken rules list
                        if (r.Results != null)
                        {
                            BrokenRules.SetBrokenRules(r.Results, r.OriginPropertyName);

                            // is any rules here broken with severity Error
                            if (r.Results.Any(p => !p.Success && p.Severity == RuleSeverity.Error))
                            {
                                anyRuleBroken = true;
                            }
                        }

                        complete = true;
                    }
                });
                context.Rule = rule;
                if (rule.PrimaryProperty != null)
                {
                    context.OriginPropertyName = rule.PrimaryProperty.Name;
                }
                context.ExecuteContext = executionContext;
                if (!rule.IsAsync || rule.ProvideTargetWhenAsync)
                {
                    context.Target = _target;
                }

                // get input properties
                if (rule.InputProperties != null)
                {
                    var target = (Core.IManageProperties)_target;
                    context.InputPropertyValues = new Dictionary <IPropertyInfo, object>();
                    foreach (var item in rule.InputProperties)
                    {
                        // do not add lazy loaded fields that have no field data.
                        if ((item.RelationshipType & RelationshipTypes.LazyLoad) == RelationshipTypes.LazyLoad)
                        {
                            if (target.FieldExists(item))
                            {
                                context.InputPropertyValues.Add(item, target.ReadProperty(item));
                            }
                        }
                        else
                        {
                            context.InputPropertyValues.Add(item, target.ReadProperty(item));
                        }
                    }
                }

                // mark properties busy
                if (rule.IsAsync)
                {
                    lock (SyncRoot)
                    {
                        // mark each property as busy
                        foreach (var item in rule.AffectedProperties)
                        {
                            var alreadyBusy = BusyProperties.Contains(item);
                            BusyProperties.Add(item);
                            _isBusy = true;
                            if (!alreadyBusy)
                            {
                                _target.RuleStart(item);
                            }
                        }
                    }
                }

                // execute (or start executing) rule
                try
                {
                    rule.Execute(context);
                }
                catch (Exception ex)
                {
                    context.AddErrorResult(string.Format("{0}:{1}", rule.RuleName, ex.Message));
                    if (rule.IsAsync)
                    {
                        context.Complete();
                    }
                }

                if (!rule.IsAsync)
                {
                    // process results
                    if (!complete)
                    {
                        context.Complete();
                    }
                    // copy affected property names
                    affectedProperties.AddRange(rule.AffectedProperties.Select(c => c.Name));
                    // copy output property names
                    if (context.OutputPropertyValues != null)
                    {
                        affectedProperties.AddRange(context.OutputPropertyValues.Select(c => c.Key.Name));
                    }
                    // copy dirty properties
                    if (context.DirtyProperties != null)
                    {
                        dirtyProperties.AddRange(context.DirtyProperties.Select(c => c.Name));
                    }

                    if (context.Results != null)
                    {
                        // explicit short-circuiting
                        if (context.Results.Any(r => r.StopProcessing))
                        {
                            break;
                        }
                    }
                }
            }
            // return any synchronous results
            return(new RunRulesResult(affectedProperties, dirtyProperties));
        }
Exemple #20
0
 public CustomValidationException(string name, string description)
 {
     BrokenRules.Add(name, description);
 }
Exemple #21
0
 /// <summary>
 /// Determine any broken business rules
 /// </summary>
 public override void Validate()
 {
     BrokenRules.AddRule("reqCustomerId", "Customer Id is required", CustomerId < 1);
     BrokenRules.AddRule("reqLine1", "Dealer Id is required", string.IsNullOrWhiteSpace(Line1));
 }
Exemple #22
0
 protected override void ValidateRules(BrokenRules Verify)
 {
 }