public void RubberStamp_ValidationRule_When_Valid_AfterCondition_WithValidation_Test()
        {
            var rule = new ValidationRule <TestClass, string>(r => r.Name)
                       .AddCondition(new IsEqualCondition <TestClass, string>(i => i.Firstname, "Tester"))
                       .When(r => r.Firstname != null);

            var result = rule.Validate(new TestClass());

            Assert.That(result, Is.Null);
        }
Exemplo n.º 2
0
 public ValidationRule <Order> RuleCustomersCannotHaveMoreThanFiveOrdersAMonth()
 =>
 ValidationRule.NewRule <Order>()
 .OnlyCheckIf(order => !order.OrderId.HasValue)
 .ValidIf(order =>
 {
     var orders = _orderRepository.GetOrdersForCustomerForMonth(order.CustomerId, order.OrderDateTime);
     return(orders.Count() < 5);
 })
 .SetErrorMessage("Customers can only place 5 orders a month.");
Exemplo n.º 3
0
        private static IValidationRuleSet GetValidationRules()
        {
            var sameInformationAuthorityRule = new ValidationRule <Order>(
                OrderRules.VisitAndPerformingFacilitiesHaveSameInformationAuthority);

            return(new ValidationRuleSet(new[]
            {
                sameInformationAuthorityRule
            }));
        }
Exemplo n.º 4
0
        public void Validate_Returns_True_When_Specification_Returns_True()
        {
            ISpecification<object> mockSpecification = MockRepository.GenerateMock<ISpecification<object>>();
            mockSpecification.Expect(x => x.IsSatisfiedBy(null))
                .IgnoreArguments()
                .Return(true);

            ValidationRule<object> rule = new ValidationRule<object>(mockSpecification, "Error message", "Property");
            Assert.That(rule.Validate(new object()));
        }
Exemplo n.º 5
0
        private void propertyGrid1_PropertyValueChanged(object s, System.Windows.Forms.PropertyValueChangedEventArgs e)
        {
            ValidationRule vr   = this.propertyGrid1.SelectedObject as ValidationRule;
            Control        ctrl = this._ValidationComponents[this.ControlsDropDownList.SelectedItem] as Control;

            if (vr != null && ctrl != null & vr.IsRequired == true && !ctrl.Text.Equals(string.Empty) && !ctrl.Text.Equals(vr.InitialValue))
            {
                vr.InitialValue = ctrl.Text;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Adds the errortypes to the rule with the specified checkType and  the notEntered-errorType
        /// </summary>
        public void AddErrorTypes(ValidationRule rule, string checkType)
        {
            foreach (var et in _errorTypes.Where(et => et.Check_Type == checkType))
            {
                rule.Errortypes.Add(et);
            }
            var notEntered = _errorTypes.Single(et => et.Check_Type == "Common" && et.Description == "not entered");

            rule.Errortypes.Add(notEntered);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sets the validation rule that is used for this argument.
        /// Validation rules verify the input is valid.
        /// </summary>
        /// <example>
        /// <c>Argument.Create("email").SetValidator(Argument.ValidationRule.Email))</c>
        /// This will cause the email argument to only allow valid emails.
        /// Custom validators can also be created.
        /// </example>
        /// <remarks>
        /// ValidationRules are run when the command is parsed, while <c>CanExecute</c> on the <c>Command</c> object verifies a command can run.
        /// </remarks>
        /// <param name="rule">Represents a rule to validate an argument value on.</param>
        public Argument SetValidator(ValidationRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }

            Rule = rule;
            return(this);
        }
Exemplo n.º 8
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            return(ValidationRules.Validate(validationContext,
                                            new PostalCodeRule(PostalCode, Country, nameof(PostalCode), nameof(Country)),

                                            ValidationRule.For(
                                                (cxt) => cxt.GetSevice <AddressService>()?.PostalCodeExists(PostalCode),
                                                () => "Postal code does not exist.",
                                                nameof(PostalCode))));
        }
Exemplo n.º 9
0
        public void Validation_Validate()
        {
            WorkerResult result = new WorkerResult()
            {
                ReturnID = 123
            };
            ValidationRule <WorkerResult> rule = new ValidationRule <WorkerResult>("ReturnID", x => x.ReturnID > 0);

            Assert.IsTrue(rule.Validate(result) == true, "Did not work");
        }
Exemplo n.º 10
0
        public void DoesAddingANewValidationRuleIncrementListCount()
        {
            var ruleSet = new StringTestSubjectRules();
            var rule    = new ValidationRule <StringTestSubject>(x => !String.IsNullOrEmpty(x.TestString1), "Rule");
            var count   = ruleSet.ValidationRules.Count;

            var newCount = ruleSet.AddRule(rule);

            Assert.AreEqual(count + 1, newCount);
        }
Exemplo n.º 11
0
 public IEnumerable <ValidationResult> Validate(ValidationRule rule)
 {
     if (rule.Object is TextBox)
     {
         yield return(new ValidationResult(rule, ValidationHelper.Range(
                                               decimal.Parse(ValidationHelper.GetValue(rule.Object, Members.Text).ToString()),
                                               decimal.Parse(rule.Criteria.ToString()),
                                               decimal.Parse(rule.SecondCriteria.ToString()))));
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// When implemented in a derived class, returns metadata for client validation.
        /// </summary>
        /// <returns>
        /// The metadata for client validation.
        /// </returns>
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            string message = ValidationRule.GetValidationMessage(Metadata.Model);

            yield return(new ModelClientValidationRule
            {
                ValidationType = "email",
                ErrorMessage = message
            });
        }
Exemplo n.º 13
0
        public void ApplyRuleToSubFieldOrPropertyToAndFromJson()
        {
            var rule = new ValidationRule <Game>
            {
                OperatorToUse          = "GreaterThan",
                ValueToValidateAgainst = new ConstantRule <int> {
                    Value = "3"
                },
                ObjectToValidate = "Name.Length",
                RuleError        = new RuleError {
                    Code = "c1", Message = "Name length must be greater than 3"
                }
            };

            var compileResult = rule.Compile();

            compileResult.Should().BeTrue();
            _testOutputHelper.WriteLine($"{nameof(rule)}:{Environment.NewLine}" +
                                        $"{rule.ExpressionDebugView()}");

            var validationResult = rule.IsValid(_game);

            validationResult.Should().BeTrue();

            var someGameWithShortName = new Game {
                Name = "foo"
            };

            validationResult = rule.IsValid(someGameWithShortName);
            validationResult.Should().BeFalse();
            _testOutputHelper.WriteLine($"with {nameof(someGameWithShortName.Name)}={someGameWithShortName.Name} " +
                                        $"{nameof(rule)} failed. " +
                                        $"Error code={rule.RuleError.Code}, " +
                                        $"message={rule.RuleError.Message}");

            // convert to json
            var ruleJson = JsonConvert.SerializeObject(rule, new JsonConverterForRule());

            _testOutputHelper.WriteLine($"{nameof(ruleJson)}:{Environment.NewLine}{ruleJson}");
            // re-hydrate from json
            var ruleFromJson = JsonConvert.DeserializeObject <ValidationRule <Game> >(ruleJson, new JsonConverterForRule());

            compileResult = ruleFromJson.Compile();
            compileResult.Should().BeTrue();
            _testOutputHelper.WriteLine($"{nameof(ruleFromJson)}:{Environment.NewLine}" +
                                        $"{ruleFromJson.ExpressionDebugView()}");

            var validationResult2 = ruleFromJson.IsValid(_game);

            validationResult2.Should().BeTrue();
            validationResult2 = ruleFromJson.IsValid(new Game {
                Name = "foo"
            });
            validationResult2.Should().BeFalse();
        }
Exemplo n.º 14
0
        internal static ValidationAttribute BuildValidation(Rule cfg, ValidationRule svc)
        {
            var validation = GetValidationAttribute(cfg, svc);

            if (!IsDefaultError(cfg))
            {
                validation.ErrorMessage = cfg.ErrorMessage;
            }

            return(validation);
        }
Exemplo n.º 15
0
 private void AddStringLengthRule(IFieldDefinition <T> definition, IFieldConfiguration <T> configuration, ValidationPropertyInfo validationProperty)
 {
     if (configuration.ValueInteger.HasValue)
     {
         var ruleName = configuration.ConfigurationType == FieldConfigurationType.MinLength ? "MinLength" : "MaxLength";
         var rule     = new ValidationRule {
             Rule = ruleName, Value = configuration.ValueInteger.Value
         };
         validationProperty.Rules.Add(rule);
     }
 }
Exemplo n.º 16
0
        public void Validation_Integration_ValidationRule_SmallerThan_Test()
        {
            var rule = new ValidationRule <TestClass, int>(i => i.Index)
                       .AddCondition(new LessThanCondition <TestClass, int>(1));

            var result = rule.Validate(new TestClass {
                Index = 5
            });

            Assert.IsNotNull(result);
        }
Exemplo n.º 17
0
 public RowValidationError(
     ValidationRule ruleInError,
     Row rowInError,
     object errorContent,
     Exception exception)
 {
     m_ruleInError  = ruleInError;
     m_rowInError   = rowInError;
     m_errorContent = errorContent;
     m_exception    = exception;
 }
Exemplo n.º 18
0
        public void Validation_Integration_ValidationRule_Null_Valid_Test()
        {
            var rule = new ValidationRule <TestClass, string>(i => i.Name)
                       .AddCondition(new IsNotNullCondition <TestClass, string>());

            var result = rule.Validate(new TestClass {
                Name = "Test"
            });

            Assert.IsNull(result);
        }
Exemplo n.º 19
0
        public void Validation_Integration_ValidationRule_GreaterThan_Valid_Test()
        {
            var rule = new ValidationRule <TestClass, int>(i => i.Index)
                       .AddCondition(new GreaterThanCondition <TestClass, int>(t => t.Index, 1));

            var result = rule.Validate(new TestClass {
                Index = 5
            });

            Assert.IsNull(result);
        }
Exemplo n.º 20
0
 private void ControlsDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
 {
     this.NewButton.Enabled  = (this.ControlsDropDownList.SelectedItem != null);
     this.SaveButton.Enabled = this.NewButton.Enabled;
     if (this.NewButton.Enabled)
     {
         ValidationRule vr = this._ValidationProvider.GetValidationRule(
             this._ValidationComponents[this.ControlsDropDownList.SelectedItem]);
         this.propertyGrid1.SelectedObject = vr;
     }
 }
Exemplo n.º 21
0
        public void Validation_Integration_ValidationRule_Equals_Valid_Test()
        {
            var rule = new ValidationRule <TestClass, int>(i => i.Index)
                       .AddCondition(new IsEqualCondition <TestClass, int>(5));

            var result = rule.Validate(new TestClass {
                Index = 5
            });

            Assert.IsNull(result);
        }
Exemplo n.º 22
0
 /// <inheritdoc />
 protected override void SetValidationRules(List <IValidationRule> validationRules)
 {
     base.SetValidationRules(validationRules);
     foreach (var editorFieldInfo in _editorFields.Where(e => e.Attribute.IsRequired))
     {
         var property = Expression.Property(Expression.Constant(this), editorFieldInfo.Property.Name);
         var lambda   = Expression.Lambda <Func <object> >(property).Compile();
         var rule     = new ValidationRule(ValidationType.Error, Validators.GetValidator(editorFieldInfo.Property.PropertyType), editorFieldInfo.Property.Name, lambda);
         validationRules.Add(rule);
     }
 }
        public void SuccedesWhenItHasItems()
        {
            ICollection <string> val = new List <string>
            {
                "a"
            };

            ValidationRule <ICollection <string> > sut = GetSut(val, "a");

            sut.HasItems();
        }
Exemplo n.º 24
0
        private void InitDiffusionInputField(TextBox inputField, ValidationRule validationRule, IValueConverter converter, string bindingPath)
        {
            Binding binding = new Binding(bindingPath)
            {
                Mode = BindingMode.TwoWay, Converter = converter
            };

            binding.ValidationRules.Add(validationRule);
            inputField.SetBinding(TextBox.TextProperty, binding);
            EditingCommands.ToggleInsert.Execute(null, inputField);
        }
Exemplo n.º 25
0
        private static IValidationRuleSet GetValidationRules()
        {
            // modalities must be associated with performing facility
            var modalityAlignsWithPerformingFacilityRule = new ValidationRule <ModalityProcedureStep>(
                OrderRules.ModalityAlignsWithPerformingFacility);

            return(new ValidationRuleSet(new[]
            {
                modalityAlignsWithPerformingFacilityRule
            }));
        }
Exemplo n.º 26
0
        private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            ValidationRule vr = this.propertyGrid1.SelectedObject as ValidationRule;

            if (this.tabControl1.SelectedIndex == 1 && vr != null)
            {
                this.RegExPatternsDropDownList.Text = string.Empty;
                this.RegExPatternTextBox.Text       = vr.RegExPattern;
                this.RegExErrorMessageTextBox.Text  = vr.ErrorMessage;
            }
        }
Exemplo n.º 27
0
        public void RubberStamp_ValidationRule_DifferentCondition_Valid_WithValidation_Test()
        {
            var rule = new ValidationRule <TestClass, string>(r => r.Name)
                       .AddCondition(new IsEqualCondition <TestClass, string>(i => i.Firstname, "Test"));

            var result = rule.Validate(new TestClass {
                Firstname = "Test"
            });

            Assert.That(result, Is.Null);
        }
Exemplo n.º 28
0
        public void RubberStamp_Validator_AddRule_Test()
        {
            var rule = new ValidationRule <TestClass, string>(p => p.Name)
                       .AddCondition(new IsNotNullCondition <TestClass, string>(p => p.Name));

            IValidator <TestClass> validator = new Validator <TestClass>()
                                               .AddRule(rule);

            Assert.AreSame(rule, validator.Rules.Single());
            Assert.That(validator.Rules.Single().Conditions.Single(), Is.Not.Null);
        }
Exemplo n.º 29
0
        public void Category_Is_Valid()
        {
            Category       category = _expenditureCategory;
            ValidationRule rule     = new ValidationRule("name", "required");

            bool expected = true;
            bool actual   = _validator.Validate(rule, category);


            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 30
0
        public void Test3()
        {
            var rule = new ValidationRule <Game>
            {
                OperatorToUse = "AndAlso",
                RuleError     = new RuleError {
                    Code = "c", Message = "m"
                },
                ChildrenRules =
                {
                    new ValidationRule <Game>
                    {
                        OperatorToUse          = "NotEqual",
                        ValueToValidateAgainst = new ConstantRule <Game>{
                            Value = "null"
                        }
                    },
                    new ValidationRule <Game>
                    {
                        ValueToValidateAgainst = new ConstantRule <string>{
                            Value = "null"
                        },
                        ObjectToValidate = "Name",
                        OperatorToUse    = "NotEqual"
                    },
                    new ValidationRule <Game>
                    {
                        ValueToValidateAgainst = new ConstantRule <int>{
                            Value = "3"
                        },
                        ObjectToValidate = "Name.Length",
                        OperatorToUse    = "GreaterThan"
                    }
                }
            };
            var settings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            };

            settings.Converters.Add(new JsonConverterForRule());

            var json = JsonConvert.SerializeObject(rule, settings);

            _testOutputHelper.WriteLine(json);

            var rule2 = JsonConvert.DeserializeObject <Rule>(json, settings);
            var foo   = rule2.Compile();

            foo.Should().BeTrue();
            _testOutputHelper.WriteLine(rule2.ExpressionDebugView());
        }
Exemplo n.º 31
0
        public IEnumerable <ValidationResult> Validate(ValidationRule rule)
        {
            if (rule.Object is TextBox)
            {
                yield return(new ValidationResult(rule, ValidationHelper.StringNullOrWhitespace(ValidationHelper.GetValue(rule.Object, Members.Text).ToString())));
            }

            if (rule.Object is ComboBox)
            {
                yield return(new ValidationResult(rule, ValidationHelper.NotNull(ValidationHelper.GetValue(rule.Object, Members.SelectedValue))));
            }
        }
 public void TestOneValidationRule()
 {
     //---------------Set up test pack-------------------
     ValidationProvider validationProvider = new ValidationProvider(GetControlFactory().CreateErrorProvider());
     ITextBox textBox1 = GetControlFactory().CreateTextBox();
     ValidationRule validationRule1 = new ValidationRule();
     //---------------Execute Test ----------------------
     validationProvider.SetValidationRule(textBox1,validationRule1);
     //---------------Test Result -----------------------
     Assert.AreEqual(1,validationProvider.GetValidationRules(textBox1).Count);
    // Assert.AreEqual(validationRule1,textBox1Rule);
     //---------------Tear down -------------------------
 }
Exemplo n.º 33
0
 public static BaseConstraintGenerator Create(BaseFieldGenerator field, ValidationRule rule)
 {
     if (rule is LengthConstraint)
         return new LengthConstraintGenerator(field, (LengthConstraint)rule);
     if (rule is RangeConstraint)
         return new RangeConstraintGenerator(field, (RangeConstraint)rule);
     if (rule is MatchConstraint)
         return new MatchConstraintGenerator(field, (MatchConstraint)rule);
     if (rule is PredefinedValue)
         return new ListConstraintGenerator(field, (PredefinedValue)rule);
     if (rule is CodedConstraint)
         return new CodeConstraintGenerator(field, (CodedConstraint) rule);
     
     throw new ApplicationException("Invalid constraint type " + rule.GetType());
 }
Exemplo n.º 34
0
		private static IValidationRuleSet GetValidationRules()
		{
			// modalities must be associated with performing facility
			var modalityAlignsWithPerformingFacilityRule = new ValidationRule<ModalityProcedureStep>(
				OrderRules.ModalityAlignsWithPerformingFacility);

			return new ValidationRuleSet(new[]
			{
				modalityAlignsWithPerformingFacilityRule
			});
		}
 public void TestValidation_RequiredFieldOnOneControl()
 {
     //---------------Set up test pack-------------------
     ValidationProvider validationProvider = new ValidationProvider(GetControlFactory().CreateErrorProvider());
     ITextBox textBox1 = GetControlFactory().CreateTextBox();
     ValidationRule validationRule1 = new ValidationRule();
     validationRule1.IsRequired = true;
     validationRule1.DataType = ValidationDataType.Integer;
     validationRule1.MinimumValue = Convert.ToString(2);
     validationRule1.MaximumValue = Convert.ToString(10);
     validationProvider.SetValidationRule(textBox1, validationRule1);
     bool result = false;
     //-------------------Test PreConditions------------
     Assert.IsFalse(result);
     //---------------Execute Test ----------------------
     textBox1.Text = Convert.ToString(5);
     result = validationProvider.Validate();
     //---------------Test Result -----------------------
     Assert.IsTrue(result);
     //---------------Tear down -------------------------
 }
 public void TestValidation_RequiredField_Fails_TwoControls_OneControl_IsIncorrect()
 {
     //---------------Set up test pack-------------------
     ValidationProvider validationProvider = new ValidationProvider(GetControlFactory().CreateErrorProvider());
     ITextBox textBox1 = GetControlFactory().CreateTextBox();
     ITextBox textBox2 = GetControlFactory().CreateTextBox();
     ValidationRule validationRule1 = new ValidationRule();
     validationRule1.IsRequired = true;
     validationProvider.SetValidationRule(textBox1, validationRule1);
     validationProvider.SetValidationRule(textBox2, validationRule1);
     bool result = true;
     //-------------------Test PreConditions------------
     Assert.IsTrue(result);
     //---------------Execute Test ----------------------
     textBox1.Text = "";
     textBox2.Text = "World";
     result = validationProvider.Validate();
     //---------------Test Result -----------------------
     Assert.IsFalse(result);
     //---------------Tear down -------------------------
 }
Exemplo n.º 37
0
		private static IValidationRuleSet GetValidationRules()
		{
			var sameInformationAuthorityRule = new ValidationRule<Order>(
				OrderRules.VisitAndPerformingFacilitiesHaveSameInformationAuthority);

			return new ValidationRuleSet(new[]
			{
				sameInformationAuthorityRule
			});
		}
 public SimulationLogAnalysisMainViewModel(IViewAwareStatus viewAwareStatus,
                                           IMessageBoxService messageBox,
                                           IUIVisualizerService visualizer,
                                           IHRCSaveFileService saveFile)
 {
     _viewAwareStatus = viewAwareStatus;
     _messageBox = messageBox;
     _visualizer = visualizer;
     _saveFile = saveFile;
     _simulationStartTime = new TimeSpan(0);
     _simulationEndTime = new TimeSpan(0);
     _viewAwareStatus.ViewLoaded += () =>
     {
         _dispatcher = ((Window)_viewAwareStatus.View).Dispatcher;
         SelectedFileName = (string)Application.Current.Properties["SelectedFileName"];
     };
     _propertyObserver = new PropertyObserver<SimulationLogAnalysisMainViewModel>(this)
         .RegisterHandler(p => p.SelectedFileName, SelectedFileNameChanged)
         .RegisterHandler(p => p.AreAnyPlatformsSelected, CommandManager.InvalidateRequerySuggested)
         .RegisterHandler(p => p.AreAnyModesSelected, CommandManager.InvalidateRequerySuggested)
         .RegisterHandler(p => p.AreAnySpeciesSelected, CommandManager.InvalidateRequerySuggested)
         .RegisterHandler(p => p.PerformOurOnlyAnalysis, CommandManager.InvalidateRequerySuggested)
         .RegisterHandler(p => p.StartTimeString, StartOrStopTimeStringsChanged)
         .RegisterHandler(p => p.StopTimeString, StartOrStopTimeStringsChanged)
         .RegisterHandler(p => p.AllTimes,
                          () =>
                          {
                              if (!AllTimes || SelectedFileName == null || !File.Exists(SelectedFileName)) return;
                              _filterStartTime = new TimeSpan(_simulationStartTime.Ticks);
                              _filterEndTime = new TimeSpan(_simulationEndTime.Ticks);
                              StartTimeString = _filterStartTime.ToString(TimeSpanFormatString);
                              StopTimeString = _filterEndTime.ToString(TimeSpanFormatString);
                          });
     AddValidationRules(new ValidationRule<SimulationLogAnalysisMainViewModel>
     {
         PropertyName = "StartTimeString",
         Description = "Must be a valid, non-negative time span value in the format hh:mm:ss where 00 <= hh <= 23; 00 <= mm <= 59; 00 <= ss <= 59",
         IsRuleValid = (target, rule) =>
         {
             if (AllTimes) return true;
             if (string.IsNullOrEmpty(target.StartTimeString)) return false;
             TimeSpan timeSpan;
             var isOK = TimeSpan.TryParseExact(target.StartTimeString, TimeSpanFormatString, null, out timeSpan);
             return isOK && timeSpan.Ticks >= 0;
         },
     }, new ValidationRule<SimulationLogAnalysisMainViewModel>
     {
         PropertyName = "StopTimeString",
         Description = "Must be a valid, non-negative time span value in the format hh:mm:ss where 00 <= hh <= 23; 00 <= mm <= 59; 00 <= ss <= 59",
         IsRuleValid = (target, rule) =>
         {
             if (AllTimes) return true;
             if (string.IsNullOrEmpty(target.StopTimeString)) return false;
             TimeSpan timeSpan;
             var isOK = TimeSpan.TryParseExact(target.StopTimeString, TimeSpanFormatString, null, out timeSpan);
             return isOK && timeSpan.Ticks > 0;
         },
     });
     _startTimeValidationRule = new ValidationRule<SimulationLogAnalysisMainViewModel>
     {
         PropertyName = "StartTimeString",
         Description = string.Format("Must be between {0} and {1}", _simulationStartTime.ToString(TimeSpanFormatString), _filterEndTime.ToString(TimeSpanFormatString)),
         IsRuleValid = (target, rule) =>
         {
             if (AllTimes) return true;
             if (_simulationStartTime.Ticks == 0 && _simulationEndTime.Ticks == 0) return true;
             if (string.IsNullOrEmpty(target.StartTimeString)) return false;
             TimeSpan timeSpan;
             var isOK = TimeSpan.TryParseExact(target.StartTimeString, TimeSpanFormatString, null, out timeSpan);
             return isOK && timeSpan >= _simulationStartTime && timeSpan < _filterEndTime;
         },
     };
     _endTimeValidationRule = new ValidationRule<SimulationLogAnalysisMainViewModel>
     {
         PropertyName = "StopTimeString",
         Description = string.Format("Must be between {0} and {1}", _filterStartTime.ToString(TimeSpanFormatString), _simulationEndTime.ToString(TimeSpanFormatString)),
         IsRuleValid = (target, rule) =>
         {
             if (AllTimes) return true;
             if (_simulationStartTime.Ticks == 0 && _simulationEndTime.Ticks == 0) return true;
             if (string.IsNullOrEmpty(target.StopTimeString)) return false;
             TimeSpan timeSpan;
             var isOK = TimeSpan.TryParseExact(target.StopTimeString, TimeSpanFormatString, null, out timeSpan);
             return isOK && timeSpan > _filterStartTime && timeSpan <= _simulationEndTime;
         },
     };
     AddValidationRules(_startTimeValidationRule, _endTimeValidationRule);
 }
Exemplo n.º 39
0
 public ValidationState(ValidationRule rule, EfgGrouping group) : this(rule)
 {
     TakeRateId = group.TakeRateId;
     MarketId = group.MarketId;
     ModelId = group.ModelId;
     FeatureId = group.FeatureId;
     ExclusiveFeatureGroup = group.ExclusiveFeatureGroup;
 }
Exemplo n.º 40
0
		private static IValidationRuleSet GetValidationRules()
		{
			// ensure that not both the procedure type and procedure type groups filters are being applied
			var procedureTypeRule = new ValidationRule<Worklist>(
				delegate(Worklist w)
				{
					var filterByBothProcedureTypeAndProcedureTypeGroup = w.ProcedureTypeFilter.IsEnabled &&
																		 w.ProcedureTypeGroupFilter.IsEnabled;

					return new TestResult(!filterByBothProcedureTypeAndProcedureTypeGroup, SR.MessageValidateWorklistProcedureTypeAndGroupFilters);
				});

			// ensure time filter meets constraints specified in settings
			var timeFilterRule = new ValidationRule<Worklist>(
				delegate(Worklist w)
				{
					var settings = new WorklistSettings();
					var maxDays = settings.TimeWindowMaxSpanDays;
					if (settings.TimeWindowRequired && maxDays > 0)
					{
						return new TestResult(w.CheckTimeFilterSpan(TimeSpan.FromDays(maxDays)),
							string.Format(SR.MessageValidateWorklistTimeFilter, maxDays));
					}
					return new TestResult(true);
				});

			return new ValidationRuleSet(new[] { procedureTypeRule, timeFilterRule });
		}
Exemplo n.º 41
0
        public ValidationState(ValidationRule rule, RawTakeRateSummaryItem summaryItem)
            : this(rule)
        {
            TakeRateId = summaryItem.FdpVolumeHeaderId;
            MarketId = summaryItem.MarketId;
            ModelId = summaryItem.ModelId;
            FdpModelId = summaryItem.FdpModelId;
            Volume = summaryItem.Volume;
            PercentageTakeRate = summaryItem.PercentageTakeRate;

            FdpTakeRateSummaryId = summaryItem.FdpTakeRateSummaryId;
            FdpChangesetDataItemId = summaryItem.FdpChangesetDataItemId;
        }
Exemplo n.º 42
0
		private static IValidationRuleSet GetValidationRules()
		{
			// ensure that not both the procedure type and procedure type groups filters are being applied
			var exactlyOneDefaultContactPointRule = new ValidationRule<ExternalPractitioner>(
				delegate(ExternalPractitioner externalPractitioner)
				{
					// The rule is not applicable to deactivated external practitioner
					if (externalPractitioner.Deactivated)
						return new TestResult(true, "");

					var activeDefaultContactPoints = CollectionUtils.Select(
						externalPractitioner.ContactPoints,
						contactPoint => contactPoint.IsDefaultContactPoint && !contactPoint.Deactivated);
					var success = activeDefaultContactPoints.Count == 1;

					return new TestResult(success, SR.MessageValidateExternalPractitionerRequiresExactlyOneDefaultContactPoint);
				});

			return new ValidationRuleSet(new[] { exactlyOneDefaultContactPointRule });
		}
Exemplo n.º 43
0
        public ValidationState(ValidationRule rule, RawTakeRateDataItem dataItem) : this(rule)
        {
            TakeRateId = dataItem.FdpVolumeHeaderId;
            MarketId = dataItem.MarketId;
            ModelId = dataItem.ModelId;
            FdpModelId = dataItem.FdpModelId;
            FeatureId = dataItem.FeatureId;
            FdpFeatureId = dataItem.FdpFeatureId;
            FeaturePackId = dataItem.FeaturePackId;
            Volume = dataItem.Volume;
            PercentageTakeRate = dataItem.PercentageTakeRate;
            ExclusiveFeatureGroup = dataItem.ExclusiveFeatureGroup;

            FdpVolumeDataItemId = dataItem.FdpVolumeDataItemId;
            FdpChangesetDataItemId = dataItem.FdpChangesetDataItemId;
        }
Exemplo n.º 44
0
		private static IValidationRuleSet GetValidationRules()
		{
			var sameInformationAuthorityRule = new ValidationRule<Procedure>(
				procedure => OrderRules.VisitAndPerformingFacilitiesHaveSameInformationAuthority(procedure.Order));

			var samePerformingFacilityRule = new ValidationRule<Procedure>(
				procedure => OrderRules.AllNonDefunctProceduresHaveSamePerformingFacility(procedure.Order));

			var samePerformingDepartmentRule = new ValidationRule<Procedure>(
				procedure => OrderRules.AllNonDefunctProceduresHaveSamePerformingDepartment(procedure.Order));

			// performing department must be associated with performing facility
			var performingDepartmentIsInPerformingFacilityRule = new ValidationRule<Procedure>(
				OrderRules.PerformingDepartmentAlignsWithPerformingFacility);

			// modalities must be associated with performing facility
			var modalitiesAlignWithPerformingFacilityRule = new ValidationRule<Procedure>(
				OrderRules.ModalitiesAlignWithPerformingFacility);

			// patient must have a profile at the performing facility
			var patientProfileExistsForPerformingFacilityRule = new ValidationRule<Procedure>(
				OrderRules.PatientProfileExistsForPerformingFacility);

			return new ValidationRuleSet(new[]
			{
				sameInformationAuthorityRule,
				samePerformingFacilityRule, 
				samePerformingDepartmentRule, 
				performingDepartmentIsInPerformingFacilityRule,
				modalitiesAlignWithPerformingFacilityRule,
				patientProfileExistsForPerformingFacilityRule
			});
		}
Exemplo n.º 45
0
 public ValidationState(ValidationRule rule)
 {
     ValidationRule = rule;
     ChildStates = Enumerable.Empty<ValidationState>();
 }
Exemplo n.º 46
0
 public ValidationState(ValidationRule rule, IEnumerable<RawTakeRateDataItem> dataItems) : this(rule)
 {
     ChildStates = dataItems.Select(dataItem => new ValidationState(ValidationRule.VolumeForFeatureGreaterThanModel, dataItem));
 }
Exemplo n.º 47
0
 public ValidationState(ValidationRule rule, FeaturePack pack) : this(rule)
 {
     TakeRateId = pack.TakeRateId;
     MarketId = pack.MarketId;
     ModelId = pack.ModelId;
     FeaturePackId = pack.FeaturePackId;
     PackName = pack.PackName;
 }
Exemplo n.º 48
0
 protected void AddValidationRule(ValidationRule rule)
 {
     _validationRules.Add(rule);
 }
Exemplo n.º 49
0
			private static IValidationRuleSet GetRules()
			{
				var rule = new ValidationRule<BarA>(i => new TestResult(false, "This rule always fails."));
				return new ValidationRuleSet(new ISpecification[] { rule });
			}
 public ValidationBreak(ValidationRule Rule, bool breaker = false)
 {
     this.validationRule = Rule;
     this.isBreaker = breaker;
 }
Exemplo n.º 51
0
        public ValidationState(ValidationRule rule, RawTakeRateFeatureMixItem mixItem)
            : this(rule)
        {
            TakeRateId = mixItem.FdpVolumeHeaderId;
            MarketId = mixItem.MarketId;
            FeatureId = mixItem.FeatureId;
            FdpFeatureId = mixItem.FdpFeatureId;
            FeaturePackId = mixItem.FeaturePackId;
            Volume = mixItem.Volume;
            PercentageTakeRate = mixItem.PercentageTakeRate;

            FdpTakeRateFeatureMixId = mixItem.FdpTakeRateFeatureMixId;
            FdpChangesetDataItemId = mixItem.FdpChangesetDataItemId;
        }