public void Should_Construct_Correctly() { var SubjectUnderTest = new Violation(errorMessage, property, this.o); Assert.AreEqual(errorMessage, SubjectUnderTest.ErrorMessage); Assert.AreEqual(property, SubjectUnderTest.Property); Assert.AreEqual(this.o, SubjectUnderTest.AttemptedValue); }
public void AddIncident(ulong id, string user, string violationDesc, string channel) { // it is not a violation if the message is a DM to @HassBot if (channel.Contains(user)) { return; } Violation newIncident = new Violation(); newIncident.ViolationChannel = channel; newIncident.ViolationDateTime = DateTime.Now; newIncident.ViolationDescription = violationDesc; // get current list of incidents for that user List <Violation> incidents = GetIncidentsByUser(id); if (null == incidents) { // first time violator ViolatorDTO violation = new ViolatorDTO(); violation.ViolatorId = id; violation.ViolatorName = user; violation.Violations.Add(newIncident); _violations.Add(violation); } else { incidents.Add(newIncident); } SaveViolations(); }
private void Now_Click(object sender, RoutedEventArgs e) { Grid grid = ((Grid)((TextBlock)(sender as Hyperlink).Parent).Parent); Violation violation = (grid.DataContext as Violation); violation.ViolationState = ViolationType.OPEN; }
public ActionResult Edit(ViolationViewModel vm) { if (ModelState.IsValid) { Violation existingViolation = this.eventTasks.GetViolation(vm.Name); if (existingViolation == null || (existingViolation != null && existingViolation.Id == vm.Id)) { Violation violation = this.eventTasks.GetViolation(vm.Id); violation.Name = vm.Name; violation.Keywords = vm.Keywords; violation.Description = vm.Description; violation.ConditionalityInterest = vm.ConditionalityInterest; if (vm.ParentViolationID.HasValue) { violation.ParentViolation = this.eventTasks.GetViolation(vm.ParentViolationID.Value); } else { violation.ParentViolation = null; } violation = this.eventTasks.SaveViolation(violation); return(RedirectToAction("Details", new { id = vm.Id })); } else { ViewData.ModelState.AddModelError("Name", "A violation with that name already exists."); } } return(Edit(vm.Id)); }
public ActionResult Create(ViolationViewModel vm) { if (ModelState.IsValid) { // TODO would be nice to have a unique constraint annotation we could use on the view model if (this.eventTasks.GetViolation(vm.Name) == null) { Violation violation = new Violation(); violation.Name = vm.Name; violation.Keywords = vm.Keywords; violation.Description = vm.Description; violation.ConditionalityInterest = vm.ConditionalityInterest; if (vm.ParentViolationID.HasValue) { violation.ParentViolation = this.eventTasks.GetViolation(vm.ParentViolationID.Value); } violation = this.eventTasks.SaveViolation(violation); return(RedirectToAction("Details", new { id = violation.Id })); } else { ViewData.ModelState.AddModelError("Name", "A violation with that name already exists."); } } return(Create()); }
public IEnumerable <StyleCopCodeIssue> GetCodeIssues( ISourceCode sourceCode, Func <ElementTypeFilter, IEnumerable <IElement> > enumerate, Violation violation, CsElement csElement) { CodePoint startPoint = null; CodePoint endPoint = null; bool emptyLine = true; foreach (var token in csElement.ElementTokens.Flatten().Where(x => x.LineNumber == violation.Line)) { if (startPoint == null) { startPoint = token.Location.StartPoint; endPoint = token.Location.EndPoint; emptyLine = token.CsTokenType == CsTokenType.WhiteSpace || token.CsTokenType == CsTokenType.EndOfLine; } if (token.CsTokenType != CsTokenType.WhiteSpace && token.CsTokenType != CsTokenType.EndOfLine) { if (emptyLine) { startPoint = token.Location.StartPoint; emptyLine = false; } endPoint = token.Location.EndPoint; } else if (token.CsTokenType == CsTokenType.EndOfLine) { yield return(new StyleCopCodeIssue(CodeIssueType.CodeSmell, new SourceRange(startPoint.LineNumber, startPoint.IndexOnLine + 1, endPoint.LineNumber, endPoint.IndexOnLine + 2))); } } }
public ActionResult Edit(int id) { Violation v = this.eventTasks.GetViolation(id); if (v != null) { ViolationViewModel vm = new ViolationViewModel(); vm.Id = v.Id; vm.Name = v.Name; vm.Keywords = v.Keywords; vm.Description = v.Description; vm.ConditionalityInterest = v.ConditionalityInterest; if (v.ParentViolation != null) { vm.ParentViolationID = v.ParentViolation.Id; } IList <Violation> parentCandidates = this.eventTasks.GetViolations(); parentCandidates.Remove(v); vm.PopulateDropDowns(parentCandidates); return(View(vm)); } else { return(new HttpNotFoundResult()); } }
private User GetUserBy(string userId) { var user = this.FindUserBy(userId); Fail.IfNull(user, Violation.Of("There is no user with id '{0}'", userId)); return(user !); }
public List <Target> GetTargets(Violation v) { List <Target> targets = new List <Target>(); targets.Add(new Target() { Hardware = this.Model.HardwareModel.FullyQualifiedSymbolMap["x86/x86_pae"].Clone() as Hardware, OperatingSystem = this.Model.OperatingSystemModel.FullyQualifiedSymbolMap["windows/seven/rtm/32bit"].Clone() as MSModel.OperatingSystem, Application = this.Model.ApplicationModel.FullyQualifiedSymbolMap["windows/ie/ie8/32bit"].Clone() as MSModel.Application, Violation = v }); targets.Add(new Target() { Hardware = this.Model.HardwareModel.FullyQualifiedSymbolMap["x86/x86_pae"].Clone() as Hardware, OperatingSystem = this.Model.OperatingSystemModel.FullyQualifiedSymbolMap["windows/eight/rtm/32bit"].Clone() as MSModel.OperatingSystem, Application = this.Model.ApplicationModel.FullyQualifiedSymbolMap["windows/ie/ie9/32bit"].Clone() as MSModel.Application, Violation = v }); targets.Add(new Target() { Hardware = this.Model.HardwareModel.FullyQualifiedSymbolMap["x86/x86_pae"].Clone() as Hardware, OperatingSystem = this.Model.OperatingSystemModel.FullyQualifiedSymbolMap["windows/eight/rtm/64bit"].Clone() as MSModel.OperatingSystem, Application = this.Model.ApplicationModel.FullyQualifiedSymbolMap["windows/ie/ie10/64bit"].Clone() as MSModel.Application, Violation = v }); return(targets); }
private void SetFormatViolation() { SetCellFormat("Сумма штрафа", "N0"); SetRightAligment("Сумма штрафа"); ViolationList violationList = ViolationList.getInstance(); foreach (DataGridViewRow row in _dgv.Rows) { int id; int.TryParse(row.Cells[0].Value.ToString(), out id); Violation violation = violationList.getItem(id); if (violation.Sent) { row.Cells["№ постановления"].Style.BackColor = Color.MediumPurple; } if (violation.FilePay != string.Empty) { row.Cells["Дата оплаты"].Style.BackColor = Color.MediumPurple; } } }
public IEnumerable <StyleCopCodeIssue> GetCodeIssues( ISourceCode sourceCode, Func <ElementTypeFilter, IEnumerable <IElement> > enumerate, Violation violation, CsElement csElement) { CodeLocation issueLocation = null; foreach (var token in this.getTokens(csElement).Flatten().Where(x => x.LineNumber == violation.Line)) { if (this.reportIssueFor(token, violation)) { issueLocation = token.Location; } else if (this.bannedFollowers.Contains(token.CsTokenType) && issueLocation != null) { yield return(new StyleCopCodeIssue(CodeIssueType.CodeSmell, new SourceRange(issueLocation.StartPoint.LineNumber, issueLocation.StartPoint.IndexOnLine + 1, issueLocation.EndPoint.LineNumber, issueLocation.EndPoint.IndexOnLine + 2))); issueLocation = null; } else { issueLocation = null; } } }
public IEnumerable <StyleCopCodeIssue> GetCodeIssues( ISourceCode sourceCode, Func <ElementTypeFilter, IEnumerable <IElement> > enumerate, Violation violation, CsElement csElement) { foreach (var operation in from x in enumerate(new ElementTypeFilter(LanguageElementType.LogicalOperation)) let logicalOperation = (LogicalOperation)x.ToLanguageElement() where logicalOperation.RecoveredRange.Start.Line == violation.Line && (logicalOperation.LeftSide.ElementType == LanguageElementType.LogicalOperation || logicalOperation.RightSide.ElementType == LanguageElementType.LogicalOperation) select logicalOperation) { var parentType = operators[operation.Name]; var leftChildType = operation.LeftSide.ElementType == LanguageElementType.LogicalOperation ? operators[operation.LeftSide.Name] : parentType; var rightChildType = operation.RightSide.ElementType == LanguageElementType.LogicalOperation ? operators[operation.RightSide.Name] : parentType; if (rightChildType > parentType) { yield return(new StyleCopCodeIssue(CodeIssueType.CodeSmell, operation.RightSide.RecoveredRange)); } else if (leftChildType > parentType) { yield return(new StyleCopCodeIssue(CodeIssueType.CodeSmell, operation.LeftSide.RecoveredRange)); } } }
public InitializeDestinationContentPrimitive( string name = "initialize content at destination address of write", MemoryAddress destinationAddress = null, MemoryAccessParameterState newContentState = MemoryAccessParameterState.Controlled, Expression <Func <SimulationContext, bool> > constraints = null, PrimitiveTransitionSuccessDelegate onSuccess = null ) : base(ExploitationPrimitiveType.Identity, "initialize_destination_content", name) { this.DestinationAddress = destinationAddress; this.NewContentState = newContentState; this.ConstraintList.Add( (context) => ( (context.Global.AssumeContentInitializationPossible == false) && (context.AttackerFavorsEqual(context.CurrentViolation.Method, MemoryAccessMethod.Write) == true) && ( (context.AttackerFavorsEqual(context.CurrentViolation.ContentDstState, MemoryAccessParameterState.Uninitialized) == true) || (context.AttackerFavorsEqual(context.CurrentViolation.ContentDstState, MemoryAccessParameterState.Unknown) == true) ) && (context.AttackerFavorsEqual(context.CurrentViolation.Address, this.DestinationAddress) == true) && (context.CanCorruptMemoryAtAddress(this.DestinationAddress) == true) ) ); this.NextViolationDelegate = (context) => { Violation v = context.CurrentViolation.CloneViolation(); v.ContentDstState = this.NewContentState; v.Address = this.DestinationAddress; return(v); }; this.OnSuccess += onSuccess; if (constraints != null) { this.ConstraintList.Add(constraints); } }
private void OnViolationEncountered(object sender, ViolationEventArgs e) { if (e.SourceCode != null) { var violation = new Violation(e.Violation.Rule.CheckId, e.Message, e.LineNumber); this.violations.AddViolationToFile(e.SourceCode.Path, violation); } }
public List <Contractor> GetContractorsAged(DateTime minDate, DateTime?maxDate) { Fail.IfNotDate(minDate, Violation.Of("minDate must be a midnight")); Fail.IfNotDate(maxDate, Violation.Of("maxDate must be a midnight")); // WARN: Below is sample code with no sense at all return(new List <Contractor>(0)); }
public void ToStringReturnsViolationAsLine() { var expectedResult = "Line 666: [SA666] You cannot do this."; var violation = new Violation("SA666", "You cannot do this.", 666); Assert.AreEqual(expectedResult, violation.ToString()); }
public ActionResult DeleteConfirmed(int id) { Violation violation = db.Violations.Find(id); violation.Is_Deleted = true; db.SaveChanges(); return(RedirectToAction("Index")); }
protected ThreadStaticContextScope() { // WARN: nested scopes are not supported as it it to erroneous Fail.IfNotNull(ThreadStaticContextScope <T> .Sack, Violation.Of(nameof(ThreadStaticContextScope <T>) + " was not cleared properly - are you trying to nest the scope? It is forbidden.")); ThreadStaticContextScope <T> .Sack = new SackOf <T>(); }
public IEnumerable <StyleCopCodeIssue> GetCodeIssues( ISourceCode sourceCode, Func <ElementTypeFilter, IEnumerable <IElement> > enumerate, Violation violation, CsElement csElement) { return(Enumerable.Empty <StyleCopCodeIssue>()); }
public IEnumerable <StyleCopCodeIssue> GetCodeIssues( ISourceCode sourceCode, Func <ElementTypeFilter, IEnumerable <IElement> > enumerate, Violation violation, CsElement csElement) { return(this.issueLocators.SelectMany(locator => locator.GetCodeIssues(sourceCode, enumerate, violation, csElement))); }
public ActionResult DeleteConfirmed(int id) { Violation violation = db.Violations.Find(id); db.Violations.Remove(violation); db.SaveChanges(); return(RedirectToAction("Index")); }
public void IfFalseSuccess() { // ARRANGE var someTrueValue = true; // ACT Fail.IfFalse(someTrueValue, Violation.Of("this should be true")); }
public void IfTrueSuccess() { // ARRANGE var someFalseValue = false; // ACT Fail.IfTrue(someFalseValue, Violation.Of("this should be false")); }
public void Delete(int idViolation) { Violation violation = getItem(idViolation); list.Remove(violation); violation.Delete(); }
public void IfEmptyWithMessageSuccess() { // ARRANGE Guid notEmptyGuid = Guid.NewGuid(); // ACT Fail.IfEmpty(notEmptyGuid, Violation.Of("guid is empty and it shouldn't be")); }
// data modification methods public virtual void AddViolation(Violation v) { if (this.Violations.Contains(v)) { return; } this.Violations.Add(v); }
public async Task <bool> SetViolation(ViolationDto violationDto, ClaimsPrincipal user) { Violation violation = _mapper.Map <ViolationDto, Violation>(violationDto); User policeman = await _userManager.FindByEmailFromClaimsPrincipals(user); return(await _policeService.SetViolation(violation, policeman)); }
public void OrFailIfEmptyWithMessage([CanBeNull] IEnumerable collection) { var exception = Assert.Throws <DesignByContractViolationException>( () => collection.OrFailIfCollectionEmpty(Violation.Of("collection cannot be null or empty")) ); // ASSERT Assert.That(exception.Message, Is.EqualTo("collection cannot be null or empty")); }
private static void DoError(XmlWriter writer, Violation violation, Location location) { writer.WriteStartElement("Error"); DoLocation(writer, location); DoViolation(writer, violation); writer.WriteEndElement(); }
public void Add(Violation violation) { if (list.Exists(item => item.Id == violation.Id)) { return; } list.Add(violation); }
/// <summary> /// Builds a new <see cref="ListViewItem"/> for the violation. /// </summary> /// <param name="violation">The violation to use.</param> /// <returns>A new <see cref="ListViewItem"/> object.</returns> private static ListViewItem BuildListViewItem(Violation violation) { ListViewItem item = new ListViewItem(); item.Text = violation.Rule.CheckId; item.SubItems.Add(violation.Message); return(item); }
public void Should_match_the_alpha_node() { _result = null; using (Session session = _engine.CreateSession()) { session.Add(new Order {OrderId = "123", Amount = 10001.0m}); session.Run(); List<FactHandle<Violation>> violations = session.Facts<Violation>().ToList(); Assert.AreEqual(1, violations.Count); Assert.IsNotNull(_result); Assert.AreEqual("123", _result.Value); } }
private static void DoWriteViolation(TextWriter stream, int counter, Violation violation, List<Location> locations) { string countStr = DoGetCounter(counter, locations.Count); stream.WriteLine("<h2 class = \"category\">{0} {1}</h2>", countStr, violation.TypeName); HtmlHelpers.WriteSeverity(stream, "Severity", violation.Severity.ToString()); HtmlHelpers.WriteText(stream, "Breaking", violation.Breaking ? "Yes" : "No"); HtmlHelpers.WriteText(stream, "CheckId", violation.CheckID); foreach (Location loc in locations) { stream.WriteLine("<table border = \"2\" rules = \"none\" class = \"location\">"); stream.WriteLine("<tr>"); stream.WriteLine("<td>File:</td>"); stream.WriteLine("<td>"); if (loc.Line >= 0) stream.WriteLine("{0}:{1}", HtmlHelpers.Escape(loc.File), loc.Line); else if (loc.File != null && loc.File.Length > 0) stream.WriteLine(HtmlHelpers.Escape(loc.File)); else stream.WriteLine("<unknown>"); stream.WriteLine("</td>"); stream.WriteLine("</tr>"); stream.WriteLine("<tr>"); stream.WriteLine("<td>Name:</td>"); stream.WriteLine("<td>"); stream.WriteLine(HtmlHelpers.Escape(loc.Name)); stream.WriteLine("</td>"); stream.WriteLine("</tr>"); if (loc.Details != null && loc.Details.Length > 0) { stream.WriteLine("<tr>"); stream.WriteLine("<td>Details:</td>"); stream.WriteLine("<td>"); stream.WriteLine(HtmlHelpers.Escape(loc.Details)); stream.WriteLine("</td>"); stream.WriteLine("</tr>"); } stream.WriteLine("</table>"); } HtmlHelpers.WriteText(stream, "Cause", BaseReport.Expand(violation.Cause)); HtmlHelpers.WriteText(stream, "Description", BaseReport.Expand(violation.Description)); HtmlHelpers.WriteText(stream, "Fix", violation.Fix); if (violation.Csharp.Length > 0) { string code = Reformat.Code(violation.Csharp); code = HtmlHelpers.Escape(code); code = HtmlHelpers.ProcessLinks(code); code = HtmlHelpers.ColorizeCode(code); stream.WriteLine("<pre class = \"code\">{0}</pre>", code); } stream.WriteLine("<hr class = \"separator\">"); }
protected ViolationException(SerializationInfo info, StreamingContext context) : base(info, context) { Violations = new Violation[] {}; }
public ViolationException(string message, Exception innerException) : base(message, innerException) { Violations = new Violation[] {}; }
public ViolationException() { Violations = new Violation[] {}; }
public void Add(Violation violation) { violations.Add(violation); }
private static void DoViolation(XmlWriter writer, Violation violation) { writer.WriteStartElement("Violation"); writer.WriteAttributeString("checkID", violation.CheckID); writer.WriteAttributeString("typeName", violation.TypeName); writer.WriteAttributeString("category", violation.Category); writer.WriteAttributeString("severity", violation.Severity.ToString()); writer.WriteAttributeString("breaking", violation.Breaking ? "true" : "false"); writer.WriteStartElement("Cause"); writer.WriteString(BaseReport.Expand(Reformat.Text(violation.Cause))); writer.WriteEndElement(); writer.WriteStartElement("Description"); writer.WriteString(BaseReport.Expand(Reformat.Text(violation.Description))); writer.WriteEndElement(); writer.WriteStartElement("Fix"); writer.WriteString(BaseReport.Expand(Reformat.Text(violation.Fix))); writer.WriteEndElement(); writer.WriteStartElement("CSharp"); writer.WriteString(Reformat.Code(violation.Csharp)); writer.WriteEndElement(); writer.WriteEndElement(); }
private static void DoWriteViolation(TextWriter stream, Violation violation) { stream.WriteLine("<a name = \"{0}\">", violation.TypeName); stream.WriteLine("<h2 class = \"category\">{0}</h2>", violation.TypeName); stream.WriteLine("</a>"); HtmlHelpers.WriteText(stream, "CheckId", violation.CheckID); HtmlHelpers.WriteSeverity(stream, "Severity", violation.Severity.ToString()); HtmlHelpers.WriteText(stream, "Breaking", violation.Breaking ? "Yes" : "No"); HtmlHelpers.WriteText(stream, "Cause", violation.Cause); HtmlHelpers.WriteText(stream, "Description", violation.Description); HtmlHelpers.WriteText(stream, "Fix", violation.Fix); if (violation.Csharp.Length > 0) { string code = Reformat.Code(violation.Csharp); code = HtmlHelpers.Escape(code); code = HtmlHelpers.ProcessLinks(code); code = HtmlHelpers.ColorizeCode(code); stream.WriteLine("<pre class = \"code\">{0}</pre>", code); } }
private static void DoError(TextWriter writer, int counter, Violation violation, List<Location> locations) { writer.WriteLine(DoGetCounter(counter, locations.Count)); writer.WriteLine("TypeName: {0}", violation.TypeName); writer.WriteLine("CheckID: {0}", violation.CheckID); writer.WriteLine("Category: {0}", violation.Category); writer.WriteLine("Severity: {0}", violation.Severity); writer.WriteLine("Breaking: {0}", violation.Breaking ? "Yes" : "No"); writer.WriteLine(" "); foreach (Location loc in locations) { if (loc.Line >= 0) writer.WriteLine("File: {0}:{1}", loc.File, loc.Line); else if (loc.File != null && loc.File.Length > 0 && loc.File != "<unknown>") writer.WriteLine("File: {0}", loc.File); writer.WriteLine(loc.Name); if (loc.Offset >= 0 && loc.Line < 0) writer.WriteLine("Offset: {0:X4}", loc.Offset); if (loc.Details != null && loc.Details.Length > 0) writer.WriteLine(loc.Details); writer.WriteLine(" "); } writer.WriteLine("Cause:"); writer.WriteLine(DoMungeText(violation.Cause)); writer.WriteLine(" "); writer.WriteLine("Rule Description:"); writer.WriteLine(DoMungeText(violation.Description)); writer.WriteLine(" "); if (violation.Fix.Length > 0) { writer.WriteLine("How to Fix Violations:"); writer.WriteLine(DoMungeText(violation.Fix)); writer.WriteLine(" "); } if (violation.Csharp.Length > 0) { writer.WriteLine("C# Example:"); writer.WriteLine(DoMungeCode(violation.Csharp)); writer.WriteLine(" "); } }
public ViolationDto(Violation violation) { RuleCode = violation.Rule.Code; Parameters = violation.Parameters; }
internal Error(Location location, Violation violation) { Location = location; Violation = violation; }
/// <summary> /// Adds one violation to this element. /// </summary> /// <param name="violation">The violation to add.</param> /// <returns>Returns false if there is already an identical violation in the element.</returns> public bool AddViolation(Violation violation) { Param.AssertNotNull(violation, "violation"); string key = violation.Key; if (!this.violations.ContainsKey(key)) { this.violations.Add(violation.Key, violation); return true; } return false; }