/// <summary> /// Verify an <see cref="Iteration"/> with respect to a <see cref="Rule"/> /// </summary> /// <param name="iteration"> /// The <see cref="Iteration"/> that is to be verified. /// </param> /// <returns> /// an <see cref="IEnumerable{RuleViolation}"/>, this may be empty of no <see cref="RuleViolation"/>s have been found. /// </returns> public override IEnumerable <RuleViolation> Verify(Iteration iteration) { if (iteration == null) { throw new ArgumentNullException(nameof(iteration), "The iteration may not be null"); } if (!iteration.Element.Any()) { return(Enumerable.Empty <RuleViolation>()); } var violations = new List <RuleViolation>(); foreach (var elementDefinition in iteration.Element) { var validationPass = Regex.IsMatch(elementDefinition.ShortName, @"^[a-zA-Z][a-zA-Z0-9_]*$"); if (!validationPass) { var violation = new RuleViolation(Guid.NewGuid(), elementDefinition.Cache, elementDefinition.IDalUri); violation.Description = "The ShortName must start with a letter and not contain any spaces or non alphanumeric characters."; violation.ViolatingThing.Add(elementDefinition.Iid); violations.Add(violation); } } return(violations); }
public override void Execute(Server server, Context context) { //Arrange RuleViolation ruleViolation = server.RuleViolations.GetRuleViolationByReporter(Player); if (ruleViolation == null) { //Act ruleViolation = new RuleViolation() { Reporter = Player, Message = Message }; server.RuleViolations.AddRuleViolation(ruleViolation); //Notify foreach (var observer in server.Channels.GetChannel(3).GetPlayers()) { context.Write(observer.Client.Connection, new ShowTextOutgoingPacket(0, ruleViolation.Reporter.Name, ruleViolation.Reporter.Level, TalkType.ReportRuleViolationOpen, ruleViolation.Time, ruleViolation.Message)); } base.Execute(server, context); } }
public ServiceResultBaseTests() { ruleViolation = new RuleViolation("foo", "bar"); serviceResult = new Mock <ServiceResultBase>(new List <RuleViolation> { ruleViolation }); }
/// <summary> /// Removes a violation from the view /// </summary> /// <param name="aViolation">The violation to remove</param> public void RemoveViolation(RuleViolation aViolation) { ListViewItem item = _violationMap.First(p => p.Value.Equals(aViolation)).Key; lvViolations.Items.Remove(item); _violationMap.Remove(item); }
/// <summary>Uses the subject for rule violation.</summary> /// <typeparam name="TContext">The type of the context.</typeparam> /// <typeparam name="TSubject">The type of the subject.</typeparam> /// <typeparam name="TContextObject">The type of the context object.</typeparam> /// <param name="ruleBuilder">The rule builder.</param> /// <param name="propertyExpression">The property expression.</param> /// <returns>A Context Object Provider Rule Builder.</returns> public static IContextObjectProviderRuleBuilder <TContext, TSubject, TContextObject> UseSubjectForRuleViolation <TContext, TSubject, TContextObject> ( this IContextObjectProviderRuleBuilder <TContext, TSubject, TContextObject> ruleBuilder, Expression <Func <TSubject, object> > propertyExpression) where TContext : RuleEngineContext <TSubject> { ruleBuilder.ElseThen( (s, ctx) => { var failedConstraints = ctx.WorkingMemory.GetContextObject <List <IConstraint> > (ruleBuilder.Rule.Name); foreach (var constraint in failedConstraints) { if (!(constraint is IHandleAddingRuleViolations)) { var propertyName = ctx.NameProvider.GetName(s, propertyExpression); var formatedMessage = constraint.Message.FormatRuleEngineMessage(propertyName); var ruleViolation = new RuleViolation( ruleBuilder.Rule, s, formatedMessage, PropertyUtil.ExtractPropertyName(propertyExpression)); ctx.RuleViolationReporter.Report(ruleViolation); } } failedConstraints.Clear(); }); return(ruleBuilder); }
/// <summary> /// Verify the <see cref="RequirementsGroup"/> against this <see cref="ParameterizedCategoryRule"/> /// </summary> /// <param name="requirementsContainer">The <see cref="RequirementsContainer"/> container to check</param> /// <param name="violations">The collection of <see cref="RuleViolation"/> to update</param> private void VerifyGroup(RequirementsContainer requirementsContainer, List <RuleViolation> violations) { foreach (var group in requirementsContainer.Group) { if (group.IsMemberOfCategory(this.Category)) { var missingParameterTypes = new List <ParameterType>(); foreach (var parameterType in this.ParameterType) { var parameter = group.ParameterValue.SingleOrDefault(p => p.ParameterType == parameterType); if (parameter == null) { missingParameterTypes.Add(parameterType); } } if (missingParameterTypes.Count > 0) { var iids = string.Join(",", missingParameterTypes.Select(x => x.Iid)); var shortnames = string.Join(",", missingParameterTypes.Select(x => x.ShortName)); var violation = new RuleViolation(Guid.NewGuid(), this.Cache, this.IDalUri); violation.RuleViolatedClassKind.Add(group.ClassKind); violation.ViolatingThing.Add(group.Iid); violation.Description = $"The RequirementsGroup {@group.Name} does not contain parameters that reference the following parameter types {iids} with shortnames: {shortnames}"; violations.Add(violation); } } this.VerifyGroup(group, violations); } }
/// <summary> /// Verify the <see cref="ElementDefinition"/> against this <see cref="ParameterizedCategoryRule"/> /// </summary> /// <param name="iteration">The <see cref="Iteration"/> to check</param> /// <param name="violations">The collection of <see cref="RuleViolation"/> to update</param> private void VerifyElementDefinition(Iteration iteration, List <RuleViolation> violations) { foreach (var elementDefinition in iteration.Element) { if (elementDefinition.IsMemberOfCategory(this.Category)) { var missingParameterTypes = new List <ParameterType>(); foreach (var parameterType in this.ParameterType) { var parameter = elementDefinition.Parameter.SingleOrDefault(p => p.ParameterType == parameterType); if (parameter == null) { missingParameterTypes.Add(parameterType); } } if (missingParameterTypes.Count > 0) { var iids = string.Join(",", missingParameterTypes.Select(x => x.Iid)); var shortnames = string.Join(",", missingParameterTypes.Select(x => x.ShortName)); var violation = new RuleViolation(Guid.NewGuid(), this.Cache, this.IDalUri); violation.RuleViolatedClassKind.Add(elementDefinition.ClassKind); violation.ViolatingThing.Add(elementDefinition.Iid); violation.Description = $"The Element Definition {elementDefinition.Name} does not contain parameters that reference the following parameter types {iids} with shortnames: {shortnames}"; violations.Add(violation); } } } }
public void ReportViolation(RuleViolation violation) { switch (violation.Severity) { case RuleViolationSeverity.Warning: WarningCount++; break; case RuleViolationSeverity.Error: ErrorCount++; break; case RuleViolationSeverity.Off: break; default: throw new ArgumentOutOfRangeException(); } Report(string.Format("{0}({1},{2}): {3} {4} : {5}.", violation.FileName, violation.Line, violation.Column, violation.Severity.ToString().ToLowerInvariant(), violation.RuleName, violation.Text)); }
public void WriteViolation(RuleViolation ruleViolation) { switch (ruleViolation.ViolationType) { case ViolationType.Warning: _log.LogWarning( null, null, null, ruleViolation.Dependency.FileName, (int)ruleViolation.Dependency.StartLine, (int)ruleViolation.Dependency.StartColumn, (int)ruleViolation.Dependency.EndLine, (int)ruleViolation.Dependency.EndColumn, ruleViolation.Dependency.QuestionableMessage()); break; case ViolationType.Error: _log.LogError( null, null, null, ruleViolation.Dependency.FileName, (int)ruleViolation.Dependency.StartLine, (int)ruleViolation.Dependency.StartColumn, (int)ruleViolation.Dependency.EndLine, (int)ruleViolation.Dependency.EndColumn, ruleViolation.Dependency.IllegalMessage()); break; default: throw new ArgumentOutOfRangeException(); } }
public void Add_RaisesValidationFailedEvent_WhenPatientIsNotAChildAndDoesNotAttendForTheSecondTimeAndPeriodIsNotStopped() { // Arrange var rttPeriod = GetCancerPeriod(); var completedEvent = new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.DidNotAttend }, EventDate = new DateTime(2001, 1, 8), Period = rttPeriod }; rttPeriod.Pathway.Patient.DateOfBirth = new DateTime(1980, 3, 5); rttPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.DidNotAttend }, EventDate = new DateTime(2001, 1, 9) }); RuleViolation eventRaised = null; rttPeriod.ValidationFailed += delegate { eventRaised = new RuleViolation(); }; // Act rttPeriod.Add(completedEvent); // Assert Assert.IsNotNull(eventRaised); }
private void OnViolationRemoved(RuleViolation violation) { if (ViolationRemoved != null) { ViolationRemoved(this, new RuleViolationEventArgs(violation)); } }
public override void Execute(Server server, Context context) { //Arrange Player reporter = server.Map.GetPlayers() .Where(p => p.Name == Name) .FirstOrDefault(); if (reporter != null) { RuleViolation ruleViolation = server.RuleViolations.GetRuleViolationByReporter(reporter); if (ruleViolation != null && ruleViolation.Assignee == null) { //Act ruleViolation.Assignee = Player; //Notify foreach (var observer in server.Channels.GetChannel(3).GetPlayers()) { context.Write(observer.Client.Connection, new RemoveRuleViolationOutgoingPacket(ruleViolation.Reporter.Name)); } base.Execute(server, context); } } }
/// <summary> /// Verifies that the target of the <see cref="BinaryRelationship"/> violates the <see cref="BinaryRelationshipRule"/> /// </summary> /// <param name="binaryRelationship"> /// The <see cref="BinaryRelationship"/> to verify /// </param> /// <returns> /// An instance of <see cref="RuleViolation"/> if the <see cref="BinaryRelationshipRule"/> has been violated, null otherwise /// </returns> private RuleViolation VerifyTarget(BinaryRelationship binaryRelationship) { var targetCategorizableThing = binaryRelationship.Target as ICategorizableThing; if (targetCategorizableThing == null) { var violation = new RuleViolation(Guid.NewGuid(), this.Cache, this.IDalUri); violation.ViolatingThing.Add(binaryRelationship.Iid); violation.ViolatingThing.Add(binaryRelationship.Target.Iid); violation.Description = $"The Target [{binaryRelationship.Target.ClassKind}:{binaryRelationship.Target.Iid}] of the BinaryRelationShip is not a CategorizableThing"; return(violation); } var isMemberOfCategory = targetCategorizableThing.IsMemberOfCategory(this.TargetCategory); if (!isMemberOfCategory) { var violation = new RuleViolation(Guid.NewGuid(), this.Cache, this.IDalUri); violation.ViolatingThing.Add(binaryRelationship.Iid); violation.ViolatingThing.Add(binaryRelationship.Target.Iid); violation.Description = $"The Target [{binaryRelationship.Target.ClassKind}:{binaryRelationship.Target.Iid}] of the BinaryRelationShip {binaryRelationship.Iid} is not a member of Category {this.TargetCategory.Iid} with shortname {this.TargetCategory.ShortName} or any of it's super categories"; return(violation); } return(null); }
public RuleViolation PathRuleViolation(RuleDescription description, IReadOnlyList <IDependencyPathBasedRuleTarget> violationPath) { return(RuleViolation.Create( description, "Violating path: ", _reportFragmentsFormat.ApplyToPath(violationPath))); }
public void MapEventMilestoneToCompletedEvent_DoesNotRaiseValidationFailedEvent_WhenCurrentEventHasTargetReferenceEvent() { //Arrange var non18WeekPeriod = new Non18WeekPeriod { Pathway = new Pathway { Patient = new Patient { Name = "John Doe", DateOfBirth = new DateTime(1990, 2, 2) }, PPINumber = "ppi" }, Name = "period 1" }; var completedEvent = new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.AttendedOutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 20), Period = non18WeekPeriod }; non18WeekPeriod.Add(new ClockStartingCompletedEvent { Name = new EventName { Code = EventCode.ReferralReceived }, EventDate = new DateTime(2014, 5, 6) }); non18WeekPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.ReferralReview }, EventDate = new DateTime(2014, 5, 10) }); non18WeekPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.BookedOutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 12) }); non18WeekPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.OutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 14) }); non18WeekPeriod.Add(completedEvent); var eventMilestone = new EventMilestone { Name = new EventName { Code = EventCode.OutcomedOutpatientFirstAppointment } }; RuleViolation eventRaised = null; non18WeekPeriod.ValidationFailed += delegate { eventRaised = new RuleViolation(); }; //Act non18WeekPeriod.MapEventMilestoneToCompletedEvent(completedEvent, eventMilestone, new EventName { Code = EventCode.AttendedOutpatientFirstAppointment, Description = "Attended Outpatient First Appointment" }); //Assert Assert.IsNull(eventRaised); }
public RuleViolation NoCyclesRuleViolation( RuleDescription description, //bug remove AssemblyName projectAssemblyName, IReadOnlyList <NamespaceDependencyPath> cycles) { return(RuleViolation.Create( description, $"Discovered cycle(s) in project {projectAssemblyName}:{Environment.NewLine}", _reportFragmentsFormat.ApplyTo(cycles, "Cycle"))); }
public RuleViolation NoUsingsRuleViolation( RuleDescription description, AssemblyName projectAssemblyName, IReadOnlyList <NamespaceDependencyPath> pathsFound) { return(RuleViolation.Create( description, $"Discovered violation(s) in project {projectAssemblyName}:{Environment.NewLine}", _reportFragmentsFormat.ApplyTo(pathsFound, "Violation"))); }
public bool Remove(RuleViolation item) { bool res = _list.Remove(item); if (res) { OnViolationRemoved(item); } return(res); }
public void RuleViolation_ShouldBeCreated() { var ruleViolation = new RuleViolation( new ValidationResult(true, "Description"), Severity.Error, new Version(1), new Version(2), true); Assert.NotNull(ruleViolation); }
public override IEnumerable <RuleViolation> Verify(Iteration iteration) { var ruleviolation = new RuleViolation(Guid.NewGuid(), null, null); ruleviolation.Description = "a test violation"; var violations = new List <RuleViolation>(); violations.Add(ruleviolation); return(violations); }
public void MapEventMilestoneToCompletedEvent_RaisesValidationFailedEvent_WhenCurrentEventDoesNotHaveTargetReferenceEvent() { //Arrange var rttPeriod = new RTT18WeekPeriod { Pathway = new Pathway() }; var completedEvent = new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.AttendedOutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 20), Period = rttPeriod }; rttPeriod.Add(new ClockStartingCompletedEvent { Name = new EventName { Code = EventCode.ReferralReceived }, EventDate = new DateTime(2014, 5, 6) }); rttPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.ReferralReview }, EventDate = new DateTime(2014, 5, 10) }); rttPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.BookedOutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 12) }); rttPeriod.Add(new ClockTickingCompletedEvent { Name = new EventName { Code = EventCode.OutpatientFirstAppointment }, EventDate = new DateTime(2014, 5, 14) }); var eventMilestone = new EventMilestone { Name = new EventName { Code = EventCode.OutcomedOutpatientFirstAppointment } }; RuleViolation eventRaised = null; rttPeriod.ValidationFailed += delegate { eventRaised = new RuleViolation(); }; //Act rttPeriod.MapEventMilestoneToCompletedEvent(completedEvent, eventMilestone, new EventName { Code = EventCode.AttendedOutpatientFirstAppointment, Description = "Attended Outpatient First Appointment" }); //Assert Assert.IsNotNull(eventRaised); }
/// <summary> /// Adds a violation to the view /// </summary> /// <param name="aViolation">The violation to add</param> public void AddViolation(RuleViolation aViolation) { String[] entry = new String[4]; entry[0] = aViolation.ViolatedRule.Name; entry[1] = aViolation.File; entry[2] = aViolation.FirstToken.Line.ToString(); entry[3] = aViolation.FirstToken.Column.ToString(); ListViewItem theItem = new ListViewItem(entry); lvViolations.Items.Add(theItem); _violationMap.Add(theItem, aViolation); }
public void ViolationListControllerShouldIgnoreFileAndRemoveViolationsFromViolationListOnViewIgnoreViolationFile() { RuleViolation violation = new RuleViolation("file.cs", null, new List <TokenBase>()); Expect.Call(() => _projectModel.IgnoredFile("file.cs")).Repeat.Once(); Mocker.ReplayAll(); _controller = new ViolationListController(_view, _projectModel, _violationList); _view.Raise(x => x.IgnoreViolation += null, this, new RuleViolationIgnoreCommandEventArgs(violation, RuleViolationIgnoreType.File)); Mocker.VerifyAll(); }
public void ViolationListControllerShouldRemoveViolationFromViewWhenViolationListViolationRemoved() { RuleViolation violation = new RuleViolation(String.Empty, null, new List <TokenBase>()); Expect.Call(() => _view.RemoveViolation(violation)).Repeat.Once(); Mocker.ReplayAll(); _controller = new ViolationListController(_view, _projectModel, _violationList); _violationList.Raise(x => x.ViolationRemoved += null, this, new RuleViolationEventArgs(violation)); Mocker.VerifyAll(); }
/// <summary> // 유효성 검사 결과의 메시지 상자를 표시합니다. /// </summary> /// <param name="ex">표시할 유효성 검사 결과 개체</param> public static MessageBoxWindowResult Show(RuleViolation ruleViolation) { RuleViolation rule = ruleViolation; MessageBoxViewModel viewModel = new MessageBoxViewModel() { Caption = "Error", Header = String.Format("{0}이(가) 유효하지 않습니다.", rule.PropertyName), HeaderIcon = MessageBoxWindowIcons.Warning, Description = rule.ErrorMessage }; return(Show(viewModel)); }
public Example1SubjectRules() { NewRule(() => StartDateMustBeBeforeEndDate) .When(example1Subject => example1Subject.StartDate > example1Subject.EndDate) .Then((example1Subject, ruleEngineContext) => { var ruleViolation = new RuleViolation( StartDateMustBeBeforeEndDate, example1Subject, Resource.SectionB_StartDateMustComeAfterEndDate); ruleEngineContext.RuleViolationReporter.Report(ruleViolation); }); }
private void CheckAddClauses() { When( (s, ctx) => { var whenClauseResult = true; var value = GetContextObject(ctx.WorkingMemory); var failedConstraints = new List <IConstraint> (); ctx.WorkingMemory.AddContextObject(failedConstraints, Rule.Name); foreach (var constraint in Constraints) { var constraintIsCompliant = constraint.IsCompliant(value, ctx); if (!constraintIsCompliant) { whenClauseResult = false; failedConstraints.Add(constraint); } } return(whenClauseResult); }); if (!_addedElseThen) { _addedElseThen = true; ElseThen( (s, ctx) => { var failedConstraints = ctx.WorkingMemory.GetContextObject <List <IConstraint> > (Rule.Name); foreach (var constraint in failedConstraints) { if (!(constraint is IHandleAddingRuleViolations)) { var contextObject = ctx.WorkingMemory.GetContextObject <TContextObject> (_contextObjectName); var propertyName = _isBuildingPropertyRule ? ctx.NameProvider.GetName(contextObject, _contextPropertyExpression) : ctx.NameProvider.GetName(contextObject); var formatedMessage = constraint.Message.FormatRuleEngineMessage(propertyName); var ruleViolation = new RuleViolation( Rule, contextObject, formatedMessage, PropertyUtil.ExtractPropertyName(_contextPropertyExpression)); ctx.RuleViolationReporter.Report(ruleViolation); } } }); } }
public void Apply(RuleContext context) { Violations = new RuleViolationCollection(); var lines = context.SourceCode.ToLines(); lines.ForEachWithIndex((i, line) => { if (line.Length > MaxLineLength) { var violationText = "Line {0} has {1} symbols".Formatted(i + 1, line.Length); var violation = new RuleViolation(violationText); Violations.Add(violation); } }); }
/// <summary> /// Serialize the <see cref="RuleViolation"/> /// </summary> /// <param name="ruleViolation">The <see cref="RuleViolation"/> to serialize</param> /// <returns>The <see cref="JObject"/></returns> private JObject Serialize(RuleViolation ruleViolation) { var jsonObject = new JObject(); jsonObject.Add("classKind", this.PropertySerializerMap["classKind"](Enum.GetName(typeof(CDP4Common.CommonData.ClassKind), ruleViolation.ClassKind))); jsonObject.Add("description", this.PropertySerializerMap["description"](ruleViolation.Description)); jsonObject.Add("excludedDomain", this.PropertySerializerMap["excludedDomain"](ruleViolation.ExcludedDomain.OrderBy(x => x, this.guidComparer))); jsonObject.Add("excludedPerson", this.PropertySerializerMap["excludedPerson"](ruleViolation.ExcludedPerson.OrderBy(x => x, this.guidComparer))); jsonObject.Add("iid", this.PropertySerializerMap["iid"](ruleViolation.Iid)); jsonObject.Add("modifiedOn", this.PropertySerializerMap["modifiedOn"](ruleViolation.ModifiedOn)); jsonObject.Add("revisionNumber", this.PropertySerializerMap["revisionNumber"](ruleViolation.RevisionNumber)); jsonObject.Add("thingPreference", this.PropertySerializerMap["thingPreference"](ruleViolation.ThingPreference)); jsonObject.Add("violatingThing", this.PropertySerializerMap["violatingThing"](ruleViolation.ViolatingThing.OrderBy(x => x, this.guidComparer))); return(jsonObject); }
public void Apply(RuleContext context) { Violations = new RuleViolationCollection(); var lines = context.SourceCodeCleaned .ToLines(); lines.ForEachWithIndex((i, line) => { if (Regex.Match(line, "\\s+$").Captures.Count > 0) { var violationText = "Line {0} has trailing white spaces".Formatted(i + 1); var violation = new RuleViolation(violationText); Violations.Add(violation); } }); }
internal static void WriteViolation(RuleViolation ruleViolation) { Logger.WriteViolation(ruleViolation); }