internal static string GetScssSelectorName(RuleSet ruleSet, bool includeShellSelectors = true) { if (!includeShellSelectors) { var block = ruleSet.Block as ScssRuleBlock; if (block == null || ruleSet.Block.Declarations.Count == 0 && ruleSet.Block.Directives.Count == 0 && block.RuleSets.Any()) { //If we got here, the element won't be included in the output but has children that might be return null; } } string name = string.Join(",\r\n", GetSelectorNames(ruleSet, ScssMixinAction.Skip)); if (name.Length == 0) return null; var oldName = name; while (oldName != (name = name.Replace(" >", ">").Replace("> ", ">"))) { oldName = name; } return oldName.Replace(">", " > "); }
public static IEnumerable<string> GetSelectorNames(RuleSet ruleSet, LessMixinAction mixinAction) { if (ruleSet.Selectors.Any(s => s.SimpleSelectors.Any(ss => ss.SubSelectors.Any(sss => sss is LessMixinDeclaration)))) { switch (mixinAction) { case LessMixinAction.Skip: return Enumerable.Empty<string>(); case LessMixinAction.Literal: break; case LessMixinAction.NestedOnly: var mixinDecl = ruleSet.Selectors.SelectMany(s => s.SimpleSelectors.SelectMany(ss => ss.SubSelectors.OfType<LessMixinDeclaration>())).First(); return Enumerable.Repeat("«mixin " + mixinDecl.MixinName.Name + "»", 1); } } var parentBlock = ruleSet.FindType<LessRuleBlock>(); if (parentBlock == null) return ruleSet.Selectors.Select(CssExtensions.SelectorText); var parentSet = parentBlock.FindType<RuleSet>(); if (parentSet == null) return ruleSet.Selectors.Select(CssExtensions.SelectorText); // Cache the computed parents to avoid re-computing them // for every child permutation. var parentSelectors = GetSelectorNames(parentSet, mixinAction).ToList(); return ruleSet.Selectors.SelectMany(child => CombineSelectors(parentSelectors, child.SelectorText()) ); }
public string Fire(Unit target) { string result = string.Empty; RuleSet idealHitRules = new RuleSet(); idealHitRules.Add(new UnderMaximumIdealRangeRule(this, target)); idealHitRules.Add(new OverMinimumIdealRangeRule(this, target)); RuleSet regularHitRules = new RuleSet(); regularHitRules.Add(new UnderMaximumRangeRule(this, target)); regularHitRules.Add(new OverMinimumRangeRule(this, target)); //Fire! if (idealHitRules.Validate()) { result = "Ideal hit!"; } else if (regularHitRules.Validate()) { result = "Hit."; } else { result = regularHitRules.FailureMessages[0]; } return result; }
public RuleSetDialog(Activity activity, RuleSet ruleSet) { if (activity == null) throw (new ArgumentNullException("activity")); InitializeDialog(ruleSet); ITypeProvider typeProvider; this.serviceProvider = activity.Site; if (this.serviceProvider != null) { typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider)); if (typeProvider == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName); throw new InvalidOperationException(message); } WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (loader != null) loader.Flush(); } else { // no service provider, so make a TypeProvider that has all loaded Assemblies TypeProvider newProvider = new TypeProvider(null); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) newProvider.AddAssembly(a); typeProvider = newProvider; } RuleValidation validation = new RuleValidation(activity, typeProvider, false); this.ruleParser = new Parser(validation); }
private CssRule(string sourceFile, string fileText, RuleSet ruleSet, string selectorName) { SelectorName = selectorName; CleansedSelectorName = RuleRegistry.StandardizeSelector(SelectorName); DisplaySelectorName = SelectorName.Replace('\r', '\n').Replace("\n", "").Trim(); string oldDisplaySelectorName = null; while (DisplaySelectorName != oldDisplaySelectorName) { oldDisplaySelectorName = DisplaySelectorName; DisplaySelectorName = DisplaySelectorName.Replace(" ", " "); } File = sourceFile; int line, column; CalculateLineAndColumn(fileText, ruleSet, out line, out column); Line = line; Column = column; Offset = ruleSet.Range.Start; Length = ruleSet.Range.Length; var lastSelector = ruleSet.Selectors[ruleSet.Selectors.Count - 1]; SelectorLength = lastSelector.Length + lastSelector.Start - ruleSet.Selectors[0].Start; _ruleSet = ruleSet; }
private string FindRuleSetInFile(IEnumerable<string> extensions, string className, out RuleSet rule) { string root = ProjectHelpers.GetProjectFolder(peekableItem._textbuffer.GetFileName()); string result = null; bool isLow = false, isMedium = false; rule = null; foreach (string ext in extensions) { ICssParser parser = CssParserLocator.FindComponent(Mef.GetContentType(ext.Trim('.'))).CreateParser(); foreach (string file in Directory.EnumerateFiles(root, "*" + ext, SearchOption.AllDirectories)) { if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase) || file.Contains("node_modules") || file.Contains("bower_components")) continue; string text = FileHelpers.ReadAllTextRetry(file).ConfigureAwait(false).GetAwaiter().GetResult(); int index = text.IndexOf("." + className, StringComparison.Ordinal); if (index == -1) continue; var css = parser.Parse(text, true); var visitor = new CssItemCollector<ClassSelector>(false); css.Accept(visitor); var selectors = visitor.Items.Where(c => c.ClassName.Text == className); var high = selectors.FirstOrDefault(c => c.FindType<AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",")); if (high != null) { rule = high.FindType<RuleSet>(); return file; } var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","); if (medium != null && !isMedium) { rule = medium.FindType<RuleSet>(); result = file; isMedium = true; continue; } var low = selectors.FirstOrDefault(); if (low != null && !isLow && !isMedium) { rule = low.FindType<RuleSet>(); result = file; isLow = true; } } } return result; }
private string GetSelectorNameInternal(RuleSet ruleSet) { var currentSelectorName = base.GetSelectorName(ruleSet).Trim(); var currentSet = ruleSet; var currentBlock = ruleSet.Parent as LessRuleBlock; while (currentSet != null && currentBlock != null) { currentSet = currentBlock.Parent as RuleSet; if (currentSet != null) { currentSelectorName = base.GetSelectorName(currentSet).Trim() + " " + currentSelectorName; currentBlock = currentSet.Parent as LessRuleBlock; } } var name = currentSelectorName.Replace(" &", ""); var oldName = name; while (oldName != (name = name.Replace(" >", ">").Replace("> ", ">"))) { oldName = name; } return oldName.Replace(">", " > "); }
internal /*for testing purposes*/ bool TryUpdateExistingProjectRuleSet(string solutionRuleSetPath, string projectRuleSetRootFolder, string currentRuleSet, out string existingRuleSetPath, out RuleSet existingRuleSet) { existingRuleSetPath = null; existingRuleSet = null; if (ShouldIgnoreConfigureRuleSetValue(currentRuleSet)) { return false; } existingRuleSetPath = PathHelper.ResolveRelativePath(currentRuleSet, projectRuleSetRootFolder); if (!PathHelper.IsPathRootedUnderRoot(existingRuleSetPath, projectRuleSetRootFolder)) { // Not our file (i.e. absolute path to some other ruleset) existingRuleSetPath = null; return false; } if (this.AlreadyUpdatedExistingRuleSetPaths.TryGetValue(existingRuleSetPath, out existingRuleSet)) { return true; } existingRuleSet = this.ruleSetSerializer.LoadRuleSet(existingRuleSetPath); if (existingRuleSet == null) { existingRuleSetPath = null; return false; } RuleSetHelper.UpdateExistingProjectRuleSet(existingRuleSet, solutionRuleSetPath); this.AlreadyUpdatedExistingRuleSetPaths.Add(existingRuleSetPath, existingRuleSet); return true; }
public static IEnumerable<string> GetSelectorNames(RuleSet ruleSet, ScssMixinAction mixinAction) { if (ruleSet.Block.Directives.Any(d => d is ScssMixinDirective)) { switch (mixinAction) { case ScssMixinAction.Skip: return Enumerable.Empty<string>(); case ScssMixinAction.Literal: break; } } var parentBlock = ruleSet.FindType<ScssRuleBlock>(); if (parentBlock == null) return ruleSet.Selectors.Select(CssExtensions.SelectorText); var parentSet = parentBlock.FindType<RuleSet>(); if (parentSet == null) return ruleSet.Selectors.Select(CssExtensions.SelectorText); // Cache the computed parents to avoid re-computing them // for every child permutation. var parentSelectors = GetSelectorNames(parentSet, mixinAction).ToList(); return ruleSet.Selectors.SelectMany(child => CombineSelectors(parentSelectors, child.SelectorText()) ); }
public void TestFirstReturnsDefaultResultWhereNoConditionIsMet() { var ruleSet = new RuleSet<object,object,string>("default"); ruleSet.When(equal).Then("equal"); Assert.That(ruleSet.First("foo", "bar"), Is.EqualTo("default")); }
public void TestFirstReturnsDefaultResultWhereNoConditionIsMet() { var ruleSet = new RuleSet<int,string>("default"); ruleSet.When(odd).Then("odd"); Assert.That(ruleSet.First(2), Is.EqualTo("default")); }
public void TestPassingGenericTypeToWhenInsteadOfFunc() { var ruleSet = new RuleSet<int, string>(); ruleSet.When(1).Then("one"); Assert.That(ruleSet.First(1), Is.EqualTo("one")); }
public void CanUsePrintCommand() { var rs = new RuleSet(); var c = Setup( rs, new[] { ">fire", ">water", "energy", "?fire" } ); c.Cook(); Assert.AreEqual( 3, rs.FoundElements.Length ); }
public void EmptyRuleSet_AlwaysTrue() { var ruleSet = new RuleSet(new Rule[0]); var propertiesForObject = new Dictionary<object, object> { { "phrase_count", 2 }, { "length", 10 } }; Assert.That(ruleSet.VerifiedBy(propertiesForObject)); }
public void Verifies_SimpleFalseRule() { var propertiesForObject = new Dictionary<object, object> { { "phrase_count", 1 } }; var ruleSet = new RuleSet (new[]{new GreaterThan("phrase_count", 3)}); Assert.That(ruleSet.VerifiedBy(propertiesForObject), Is.False); }
public void Equality_True() { var ruleSet = new RuleSet(new[] { new EqualTo("ciao", 1) }); var propertiesForObject = new Dictionary<object, object> { { "ciao", 1 }, { "length", 10 } }; Assert.That(ruleSet.VerifiedBy(propertiesForObject), Is.True); }
public void Verifies_SimpleTrueRules() { var propertiesForObject = new Dictionary<object, object> { { "phrase_count", 2 }, { "length", 10 } }; var ruleSet = new RuleSet(new Rule[] { new GreaterThan("phrase_count", 1), new LessThan("length", 15) }); Assert.That(ruleSet.VerifiedBy(propertiesForObject), Is.True); }
public void AssertRuleSetsAreEqual(string ruleSetPath, RuleSet expectedRuleSet) { this.AssertRuleSetExists(ruleSetPath); RuleSet actualRuleSet = this.savedRuleSets[ruleSetPath]; Assert.IsNotNull(actualRuleSet, "Expected rule set to be written"); RuleSetAssert.AreEqual(expectedRuleSet, actualRuleSet); }
public void AlchemyControllerRecommendsNullIfNoElements() { var rs = new RuleSet(); var controller = new AlchemyController( rs ); var rule = controller.RecommendNewRule(); Assert.IsNull( rule ); }
public void RuleSetNotificationSendsSelfAsObject() { RuleSet other = null; var r = new RuleSet(); r.PropertyChanged += ( a, e ) => other = (RuleSet) a; r.Rules = new Rule[0]; Assert.AreSame( r, other ); }
public void TestFirstReturnsFirstResultWhereTheConditionIsMet() { var ruleSet = new RuleSet<int,string>(); ruleSet.When(even).Then("even"); ruleSet.When(even).Then("definitely even"); Assert.That(ruleSet.First(2), Is.EqualTo("even")); }
public void TestFirstReturnsFirstResultWhereTheConditionIsMet() { var ruleSet = new RuleSet<object,object,string>(); ruleSet.When(equal).Then("equal"); ruleSet.When(equal).Then("definitely equal"); Assert.That(ruleSet.First("foo", "foo"), Is.EqualTo("equal")); }
public static RuleSet CreateTestRuleSetWithRuleIds(IEnumerable<string> ids, string analyzerId = "TestId", string ruleNamespace = "TestNamespace", RuleSet existingRuleSet = null) { var ruleSet = existingRuleSet ?? new RuleSet("Test Rule Set"); foreach (var id in ids) { ruleSet.Rules.Add(new RuleReference(analyzerId, ruleNamespace, id, RuleAction.Warning)); } return ruleSet; }
public void CanExitPrematurely() { var rs = new RuleSet(); var c = Setup( rs, new[] { ">fire", ">water", "!", "alcohol", "+alcohol", "ocean", "", "", "", "", "", "", "", "" } ); c.Cook(); Assert.AreEqual( 2, rs.FoundElements.Count() ); }
void IRuleSetSerializer.WriteRuleSetFile(RuleSet ruleSet, string path) { RuleSet rs; if (!this.savedRuleSets.TryGetValue(path, out rs)) { this.savedRuleSets[path] = ruleSet; } this.fileSystem.UpdateTimestamp(path); }
public RuleSetInformation(Language language, RuleSet ruleSet) { if (ruleSet == null) { throw new ArgumentNullException(nameof(ruleSet)); } this.RuleSet = ruleSet; }
private string FormatCode(RuleSet ruleSet, IAtTemplate template, string code) { Styler styler = new Styler() { RuleSet = ruleSet, StyleTemplate = template }; return styler.StyleCode(code); }
public RuleSetDialog(Type activityType, ITypeProvider typeProvider, RuleSet ruleSet) { if (activityType == null) throw (new ArgumentNullException("activityType")); InitializeDialog(ruleSet); RuleValidation validation = new RuleValidation(activityType, typeProvider); this.ruleParser = new Parser(validation); }
public RemoveCssRuleSmartTagAction(ITrackingSpan span, RuleSet rule) { _span = span; _rule = rule; if (Icon == null) { Icon = BitmapFrame.Create(new Uri("pack://application:,,,/WebEssentials2013;component/Resources/delete.png", UriKind.RelativeOrAbsolute)); } }
public void DisplayRuleDisplaysNothingIfApplicable() { IPreCommand c = new DisplayRecommendedRule(); var rs = new RuleSet(); var a = new AlchemyController( rs ); var t = new TestCommunicator(); t.DisplayCalled += ( o, e ) => Assert.IsTrue( string.IsNullOrEmpty( (string) o ) ); var result = c.Run( a, t ); Assert.AreEqual( Do.KeepProcessing, result ); }
public void InvalidRuleDirectoryFailTest() { RuleSet ruleset = RuleSet.FromDirectory("invalid_directory", null); }
private void SetFormValidation() { _ruleSet = new RuleSet(); _ruleSet.AddValidationRule(new UsernameValidationRule(_newUsername)); }
private bool IsRuleSetBound(Dictionary <string, RuleSet> cache, Project project, RuleSetDeclaration declaration, RuleSet sonarQubeRuleSet) { RuleSet projectRuleSet = this.FindDeclarationRuleSet(cache, project, declaration); return(projectRuleSet != null && RuleSetHelper.FindInclude(projectRuleSet, sonarQubeRuleSet) != null); }
static int DoWork(RunOptions opts) { var rulesText = opts.RulesFile == "-" ? Console.In.ReadToEnd() : File.ReadAllText(opts.RulesFile); var ruleSet = RuleSet.Parse(rulesText); if (opts.DryRun) { opts.Log.WriteLine("== DRY RUN =="); // load all files from source and destination var allFiles = Directory.GetFiles(opts.SourceRoot, "*", SearchOption.AllDirectories) .Concat(Directory.GetFiles(opts.DestinationRoot, "*", SearchOption.AllDirectories)) ; var fs = new TextFileSystem(allFiles); fs.Force = opts.Force; var copyMachine = new CopyMachine(fs, opts.SourceRoot, opts.DestinationRoot, Console.Error, opts.Log); var result = copyMachine.Copy(ruleSet); opts.Log.WriteLine("== DRY RUN RESULTS =="); if (fs.CreatedDirectories.Count > 0) { opts.Log.WriteLine("Created directories:"); foreach (var dir in fs.CreatedDirectories.OrderBy(x => x)) { opts.Log.WriteLine("\t" + dir); } } if (fs.CopiedFiles.Count > 0) { opts.Log.WriteLine("Copied files:"); foreach (var file in fs.CopiedFiles.OrderBy(x => x)) { opts.Log.WriteLine("\t" + file); } } if (fs.CopiedOverFiles.Count > 0) { opts.Log.WriteLine("Copied with overwite files:"); foreach (var file in fs.CopiedOverFiles.OrderBy(x => x)) { opts.Log.WriteLine("\t" + file); } } return(result); } else { // usual run var fs = new RealFileSystem(); fs.Force = opts.Force; var copyMachine = new CopyMachine(fs, opts.SourceRoot, opts.DestinationRoot, Console.Error, opts.Log); var result = copyMachine.Copy(ruleSet); if (opts.Summary) { Console.WriteLine($"{copyMachine.FilesCopied} files copied"); Console.WriteLine($"Exit code: {result}"); } return(result); } }
public void InvalidRuleFileFailTest() { RuleSet ruleset = RuleSet.FromFile("non-existent-file.txt", null); }
public IRuleSet GetRuleSet(string propertyName) { var ruleSet = new RuleSet(); return(ruleSet); }
void selectAcception_AcceptingAdmin(object sender, DialogControllerAcceptingEventArgs e) { ObjectSpace objectSpace = Application.CreateObjectSpace(); DevExpress.ExpressApp.ListView lv = ((DevExpress.ExpressApp.ListView)((WindowController)sender).Window.View); User u = (User)SecuritySystem.CurrentUser; XPCollection <Role> xpc = new XPCollection <Role>(u.Roles, new BinaryOperator("Name", "Administrators")); XPCollection <Role> xpc2 = new XPCollection <Role>(u.Roles, new BinaryOperator("Name", "DataAdmins")); if (xpc.Count + xpc2.Count > 0) { objectSpace.Session.BeginTransaction(); Student currentStudent; Lesson curLesson; foreach (string studentCode in listStudentCode) { currentStudent = objectSpace.FindObject <Student>( new BinaryOperator("StudentCode", studentCode)); foreach (Lesson lesson in lv.SelectedObjects) { curLesson = objectSpace.FindObject <Lesson>( new BinaryOperator("Oid", lesson.Oid)); RegisterDetail regdetail = new RegisterDetail(objectSpace.Session) { Student = currentStudent, Lesson = curLesson, RegisterState = objectSpace.FindObject <RegisterState>( new BinaryOperator("Code", "SELECTED")), CheckState = objectSpace.FindObject <RegisterState>( new BinaryOperator("Code", "NOTCHECKED")) }; RuleSet ruleSet = new RuleSet(); RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save); if (ValidationState.Invalid == result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State) { regdetail.Delete(); } else { regdetail.Save(); } } } objectSpace.Session.CommitTransaction(); PopUpMessage ms = objectSpace.CreateObject <PopUpMessage>(); ms.Title = "Lỗi đăng ký"; ms.Message = string.Format("Error"); ShowViewParameters svp = new ShowViewParameters(); svp.CreatedView = Application.CreateDetailView( objectSpace, ms); svp.TargetWindow = TargetWindow.NewModalWindow; svp.CreatedView.Caption = "Thông báo"; DialogController dc = Application.CreateController <DialogController>(); svp.Controllers.Add(dc); dc.SaveOnAccept = false; Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null)); //// View.ObjectSpace.CommitChanges(); //View.ObjectSpace.Refresh(); //ListView view = null; //Frame currentFrame = ((ActionBase)sender).Controller.Frame; //switch (currentFrame.View.ObjectTypeInfo.Name) //{ // case "Student": // view = Application.CreateListView(objectSpace,typeof(RegisterDetail),true); // break; //} //currentFrame.SetView(view); //e.Cancel = true; } }
public static bool TryGetRuleSet(this IBindingConfigFile bindingConfigFile, out RuleSet ruleSet) { ruleSet = (bindingConfigFile as IBindingConfigFileWithRuleset)?.RuleSet; return(ruleSet != null); }
} // end getRuntimeConfiguration() // readSourcePathsFile(): /// <summary> /// Reads the specified file as a list of source paths and inclusion/exclusion rules for each source path. /// Each source is specified by a line containing a source path, followed by a series of inclusion and exclusion rules. /// Each rule is a '+' for inclusion, '-' for exclusion, or '!' to completely ignore an entire directory tree, /// followed by a simple regular expression to be applied to items to see if they match. /// Each item will be tested by rules in the order those rules are defined. /// </summary> /// <returns> /// A <c>List</c> of <c>SourcePathInfo</c> objects defining the source paths and rules for each defined in the file. /// </returns> /// <param name="filePath">A <c>string</c> containing the full path to a file to read as a list of source paths and rules.</param> /// <exception cref="ErrorManagement.OptionsException">Thrown when specified file cannot be found or cannot be read.</exception> /// <exception cref="OutOfMemoryException">Thrown when memory runs out trying to read the file.</exception> private static List <SourcePathInfo> readSourcePathsFile(string filePath) { List <SourcePathInfo> sourcePaths = new List <SourcePathInfo>(); // List to build and return. // Variables to hold info about the current working item. string currentSourceItemPath = null; RuleSet currentRuleSet = new RuleSet(); // Open the file for reading. try { using (StreamReader reader = new StreamReader(filePath)) { // Read the entire file and parse it line by line. for (string currentLine = reader.ReadLine(); currentLine != null; currentLine = reader.ReadLine()) { // Ignore empty lines or those containing only whitespace. if (currentLine.Trim().Length < 1) { continue; } RuleSet.AllowanceType?ruleType; Regex ruleDefinition; if (tryParseAsRule(currentLine, out ruleType, out ruleDefinition)) { // A rule that comes where no path has yet been enountered is an error. if (currentSourceItemPath == null) { throw new OptionsException($"Source paths file {filePath} contains a rule but no path to which to apply that rule."); } // Add this rule to the set of rules applying to the current source path. currentRuleSet.addRule((RuleSet.AllowanceType)ruleType, ruleDefinition); } else // Not a rule, so it must be the next source path. { // If we were already reading rules for a source path, this means we've completed reading the rule set for that one. // Add that path and its rules to the list we will return from this function. if (currentSourceItemPath != null) { sourcePaths.Add(new SourcePathInfo(currentSourceItemPath, currentRuleSet)); } // Store the current line as the new source path, and reset the rule definitions to an empty set // before reading in the rules associated with this new source path. currentSourceItemPath = Path.GetFullPath(currentLine); currentRuleSet = new RuleSet(); } // end if / else on (currentLine[0] == '+' || currentLine[0] == '-') } // end for loop iterating through lines of the file. // We've reached the end of the file. If we were reading info about a source path, // add that path and its rules to the list to return. if (currentSourceItemPath != null) { sourcePaths.Add(new SourcePathInfo(currentSourceItemPath, currentRuleSet)); } } // end using(reader) } catch (OptionsException) { throw; } catch (IOException e) { throw new OptionsException($"Error reading from sources file: {filePath}", e); } catch (OutOfMemoryException e) { throw new OutOfMemoryException($"Error; out of memory while trying to read from sources file: {filePath}", e); } catch (Exception e) when(e is ArgumentException || e is ArgumentNullException || e is FileNotFoundException || e is DirectoryNotFoundException) { throw new OptionsException($"Error attempting to access or open sources file. File or path may not exist: {filePath}", e); } return(sourcePaths); } // end readSourcePathsFile()
/// <summary> /// Fires after the next button has been clicked /// </summary> private bool Validate(XafWizardPage page) { if (page == null) { return(true); } var validationResults = new RuleSetValidationResult(); var usedProperties = new List <string>(); var resultsHighlightControllers = new List <ResultsHighlightController> { Frame.GetController <ResultsHighlightController>() }.Where(controller => controller != null).ToList(); foreach (var item in page.View.GetItems <PropertyEditor>()) { if (item.Control != null && ((Control)item.Control).Visible) { usedProperties.Add(item.PropertyName); var editor = item as ListPropertyEditor; if (editor != null) { usedProperties.AddRange(editor.ListView.Editor.RequiredProperties.Select(property => property.TrimEnd('!'))); var nestedController = editor.Frame.GetController <ResultsHighlightController>(); if (nestedController != null) { resultsHighlightControllers.Add(nestedController); } } } } var modifiedObjects = ModifiedObjects(page); foreach (var obj in modifiedObjects) { IList <IRule> rules = Validator.RuleSet.GetRules(obj, ContextIdentifier.Save); foreach (IRule rule in rules) { bool ruleInUse = rule.UsedProperties.Any(property => usedProperties.Contains(property) || !string.IsNullOrEmpty(usedProperties.FirstOrDefault(p => p.EndsWith( $".{property}")))); string reason; if (ruleInUse && RuleSet.NeedToValidateRule(ObjectSpace, rule, obj, out reason)) { var objectSpaceLink = rule as IObjectSpaceLink; if (objectSpaceLink != null) { objectSpaceLink.ObjectSpace = ObjectSpace; } RuleValidationResult result = rule.Validate(obj); if (result.State == ValidationState.Invalid) { validationResults.AddResult(new RuleSetValidationResultItem(obj, ContextIdentifier.Save, rule, result)); } } } } foreach (ResultsHighlightController resultsHighlightController in resultsHighlightControllers) { resultsHighlightController.ClearHighlighting(); if (validationResults.State == ValidationState.Invalid) { resultsHighlightController.HighlightResults(validationResults); } } return(validationResults.State != ValidationState.Invalid); }
public HScene.StartMotion RandomSelectAnimation(List <HScene.AnimationListInfo>[] animList) { HAutoCtrl.AutoRandom inclusionAutoRandom = new HAutoCtrl.AutoRandom(); HAutoCtrl.AutoRandom autoRandom = new HAutoCtrl.AutoRandom(); bool male = Singleton <HSceneManager> .Instance.player.sex == 0; bool futa = Singleton <HSceneManager> .Instance.bFutanari && !male; bool multipleFemales = Singleton <HSceneManager> .Instance.Hscene.GetFemales().Length > 1; bool fem1Present = Singleton <HSceneManager> .Instance.Hscene.GetFemales()[1] != null; bool multipleMales = Singleton <HSceneManager> .Instance.Hscene.GetMales().Length > 1; string femaleName1 = Singleton <HSceneManager> .Instance.Hscene.GetFemales()[0] == null ? "" : Singleton <HSceneManager> .Instance.Hscene.GetFemales()[0].fileParam.fullname; string femaleName2 = Singleton <HSceneManager> .Instance.Hscene.GetFemales()[1] == null ? "" : Singleton <HSceneManager> .Instance.Hscene.GetFemales()[1].fileParam.fullname; string roomName = BaseMap.infoTable[Singleton <HSceneManager> .Instance.mapID].MapNames[0]; // Log.LogInfo(string.Format("Now Entering: {0} {3} with {1} {2}", Singleton<HSceneManager>.Instance.mapID, femaleName1, femaleName2, roomName)); for (int info1 = 0; info1 < animList.Length; info1++) { for (int pos = 0; pos < animList[info1].Count; pos++) { int mode = DetermineModeByActionCtrl(animList[info1][pos].ActionCtrl.Item1, animList[info1][pos].ActionCtrl.Item2); if (!animList[info1][pos].nPositons.Contains(Singleton <HSceneFlagCtrl> .Instance.nPlace)) { // Skip positions not available in location if (!AllowAllPositions.Value) { continue; } } if (mode == 4 && (male || futa)) { //Skip masturbation if not female continue; } if (mode == 5 && (male || futa) && !fem1Present) { // Don't peep without a female subject? continue; } if (!multipleFemales && (mode == 6 || mode == 7)) { // need multiple females for les/f2 scenes continue; } if (!multipleMales && mode == 8) { // need multiple makes for m2 scenes continue; } TCRuleApplicationJudgement female1CharacterJudgement = Singleton <HSceneManager> .Instance.Hscene.GetFemales()[0] == null ? TCRuleApplicationJudgement.NEUTRAL : RuleSet.CharacterRuleJudgement(femaleName1, animList[info1][pos].nameAnimation, ((PositionCategories)mode).ToString()); TCRuleApplicationJudgement female2CharacterJudgement = Singleton <HSceneManager> .Instance.Hscene.GetFemales()[1] == null ? TCRuleApplicationJudgement.NEUTRAL : RuleSet.CharacterRuleJudgement(femaleName2, animList[info1][pos].nameAnimation, ((PositionCategories)mode).ToString()); TCRuleApplicationJudgement roomJudgement = RuleSet.RoomRuleJudgement(roomName, animList[info1][pos].nameAnimation, ((PositionCategories)mode).ToString()); if (RuleSet.ExcludeAlwaysCheck(animList[info1][pos].nameAnimation, ((PositionCategories)mode).ToString()) || female1CharacterJudgement == TCRuleApplicationJudgement.EXCLUDED || female2CharacterJudgement == TCRuleApplicationJudgement.EXCLUDED || roomJudgement == TCRuleApplicationJudgement.EXCLUDED) { // Log.LogInfo(string.Format("TC Rule Judgement: Excluding: {0} ({1}, {2}, {3})", animList[info1][pos].nameAnimation, femaleName1, femaleName2, roomName)); continue; } // Staying with Illusion Random logic for consistency... HAutoCtrl.AutoRandom.AutoRandomDate autoRandomDate = new HAutoCtrl.AutoRandom.AutoRandomDate(); autoRandomDate.mode = info1; autoRandomDate.id = animList[info1][pos].id; if (female1CharacterJudgement == TCRuleApplicationJudgement.INCLUDED || female2CharacterJudgement == TCRuleApplicationJudgement.INCLUDED || roomJudgement == TCRuleApplicationJudgement.INCLUDED) { // Log.LogInfo(string.Format("TC Rule Judgement: Including: {0} ({1}, {2}, {3})", animList[info1][pos].nameAnimation, femaleName1, femaleName2, roomName)); inclusionAutoRandom.Add(autoRandomDate, 10f); } else { autoRandom.Add(autoRandomDate, 10f); } } } if (!inclusionAutoRandom.IsEmpty()) { HAutoCtrl.AutoRandom.AutoRandomDate selectedAutoRandom = inclusionAutoRandom.Random(); return(new HScene.StartMotion(selectedAutoRandom.mode, selectedAutoRandom.id)); } else { HAutoCtrl.AutoRandom.AutoRandomDate selectedAutoRandom = autoRandom.Random(); return(new HScene.StartMotion(selectedAutoRandom.mode, selectedAutoRandom.id)); } }
public override IRuleSet GetRuleSet(string propertyName, string datalist) { IRuleSet ruleSet = new RuleSet(); return(ruleSet); }
private ExecutionContext() { RuleSet = new RuleSet(); }
private static string GetSelectorText(RuleSet rule) { var selectorsText = rule.Selectors.OrderBy(s => s.Text.Trim(',')).Select(s => s.Text.Trim(',')); return(string.Join(", ", selectorsText)); }
internal static bool IsRuleUsed(RuleSet rule) { return(GetAllUnusedRules().All(x => !x.Matches(rule))); }
public static RuleSetValidationResult NewRuleSetValidationMessageResult(this RuleSet ruleSet, IObjectSpace objectSpace, string messageTemplate, object objectTarget) { return(ruleSet.NewRuleSetValidationMessageResult(objectSpace, messageTemplate, ContextIdentifier.Save, objectTarget, objectTarget.GetType())); }
public override string GetSelectorName(RuleSet ruleSet) { return(GetLessSelectorName(ruleSet, false)); }
/// <summary> /// Read the data from Csv-File. Each line is separated in it's parts via the method ".Split". /// </summary> /// <returns></returns> private bool GetDataFromCsvRuleSet() { bool errorOccured; string line; char[] saparators = new char[] { ';' }; string[] separatedLine; int lineCounter = 0; int indexCounter = 0; string name; string[] attributeHeader = null; string[] attributeTypeHeader = null; List <string[]> listAttributes = null; // Count how many CSV-files have to be read. foreach (System.IO.FileInfo f in parentDirectory.GetFiles()) { indexCounter++; } // Store the names of the available CSV-files. availableRuleSetsName = new string[indexCounter]; // For each CSV-file one enty in the variable setsOfRules is greated. setsOfRules = new RuleSet[indexCounter]; // Reset the indexCounter indexCounter = 0; Console.WriteLine(Environment.NewLine); Console.WriteLine("The following rulesets were found: "); foreach (System.IO.FileInfo f in parentDirectory.GetFiles()) { availableRuleSetsName[indexCounter] = f.Name; Console.WriteLine("Ruleset {0}: " + f.Name, (indexCounter + 1)); indexCounter++; } errorOccured = false; for (int i = 0; i < indexCounter; i++) { try { sFilePathRuleSet = @"RuleSets\" + availableRuleSetsName[i].ToString(); StreamReader inputFile = new StreamReader(sFilePathRuleSet); // Read header from CSV-file line = inputFile.ReadLine(); separatedLine = line.Split(saparators); name = separatedLine[1]; listAttributes = null; lineCounter++; while ((line = inputFile.ReadLine()) != null) { // Whith each line, which is read in the lineCounter is increased. lineCounter++; separatedLine = line.Split(saparators); // Store the attributeHeader from line 2. if (lineCounter == 2) { attributeHeader = new string[separatedLine.Length]; attributeHeader = separatedLine; } // Store the attributeTypeHeader from line 2. if (lineCounter == 3) { attributeTypeHeader = new string[separatedLine.Length]; attributeTypeHeader = separatedLine; } // Store all attributes. if (lineCounter == 4) { numberOfQuestions = (separatedLine.Length - 2); } if (lineCounter >= 4) { if (listAttributes == null) { listAttributes = RuleSet.CreateNewAttributesList(separatedLine); } else { listAttributes = RuleSet.CreateNewAttributesList(separatedLine, listAttributes); } } } // Creat another ruleset setsOfRules[i] = new RuleSet(name, attributeHeader, attributeTypeHeader, listAttributes); lineCounter = 0; inputFile.Close(); } catch { // If one file is not read in successfully an error occurs. All other files are read in. Console.WriteLine(Environment.NewLine); Console.WriteLine("Following file was not read in successfully: {0}", availableRuleSetsName[i].ToString()); errorOccured = true; } } return(errorOccured); }
private string FindRuleSetInFile(IEnumerable <string> extensions, string className, out RuleSet rule) { string root = ProjectHelpers.GetProjectFolder(peekableItem._textbuffer.GetFileName()); string result = null; bool isLow = false, isMedium = false; rule = null; foreach (string ext in extensions) { ICssParser parser = CssParserLocator.FindComponent(ProjectHelpers.GetContentType(ext.Trim('.'))).CreateParser(); foreach (string file in Directory.EnumerateFiles(root, "*" + ext, SearchOption.AllDirectories)) { if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase) || file.Contains("node_modules") || file.Contains("bower_components")) { continue; } string text = File.ReadAllText(file); int index = text.IndexOf("." + className, StringComparison.Ordinal); if (index == -1) { continue; } var css = parser.Parse(text, true); var visitor = new CssItemCollector <ClassSelector>(false); css.Accept(visitor); var selectors = visitor.Items.Where(c => c.ClassName.Text == className); var high = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",")); if (high != null) { rule = high.FindType <RuleSet>(); return(file); } var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","); if (medium != null && !isMedium) { rule = medium.FindType <RuleSet>(); result = file; isMedium = true; continue; } var low = selectors.FirstOrDefault(); if (low != null && !isLow && !isMedium) { rule = low.FindType <RuleSet>(); result = file; isLow = true; } } } return(result); }
public void InvalidRuleDirectoryArgsFailTest() { RuleSet ruleset = RuleSet.FromDirectory(null, null); }
private void handleCreateTableSubType(List <User> users, List <IClientConnectionController> clientConnectionControllers, List <IGameController> gameControllers, IUserPermissionService userPermissionService, ClientMessage message) { if (!userPermissionService.IsMessageFromNamedUser(users, message)) { // drop? return; } var numbers = Enumerable.Range(1, 10000); // limit of 10000 tables but should never be an issue var newTableID = numbers.FirstOrDefault(number => !gameControllers.Exists(gameController => gameController.TableID == number)); if (newTableID != 0) { try { var parts = message.Text.Split(","); string name = "", password = null; bool hidden = false; RuleSet ruleSet = new RuleSet(); if (parts.Count() > 0) { name = parts[0]; if (parts.Count() > 1) { password = parts[1]; if (parts.Count() > 2) { hidden = parts[2] == "true"; if (parts.Count() > 3) { // split all parts to retrieve rules for (int partID = 3; partID < parts.Count(); ++partID) { var keyValue = parts[partID].Split(":"); if (keyValue.Count() != 2) { continue; } switch (keyValue[0]) { case "useNines": ruleSet.UseNines = keyValue[1] == "true"; break; case "withArmut": ruleSet.WithArmut = keyValue[1] == "true"; break; case "withFleischlos": ruleSet.WithFleischlos = keyValue[1] == "true"; break; case "countingReContra": ruleSet.CountReContraBy = keyValue[1] == "+2" ? RuleSet.ReContraCounting.ADDING_TWO : RuleSet.ReContraCounting.DOUBLING; break; case "secondDulleTrumpsFirst": ruleSet.SecondDulleTrumpsFirst = keyValue[1] == "true"; break; case "bothPigletsTrumpAll": ruleSet.BothPigletsTrumpAll = keyValue[1] == "true"; break; case "reContraAtHochzeitAfterFinderTrick": ruleSet.ReContraAtHochzeitAfterFinderTrick = keyValue[1] == "true"; break; case "withReshufflingAtFiveKings": ruleSet.WithReshufflingAtFiveKings = keyValue[1] == "true"; break; case "withReshufflingAtEightyPoints": ruleSet.WithReshufflingAtEightyPoints = keyValue[1] == "true"; break; case "soloPlayerFirstToAct": ruleSet.SoloPlayerFirstToAct = keyValue[1] == "true"; break; case "numberOfNestedBuckRounds": if (int.TryParse(keyValue[1], out int numberOfNestedBuckRounds)) { ruleSet.NumberOfNestedBuckRounds = numberOfNestedBuckRounds; } break; case "addBuckRoundAtLostSolo": ruleSet.AddBuckRoundAtLostSolo = keyValue[1] == "true"; break; case "addBuckRoundAtFullHeartTrick": ruleSet.AddBuckRoundAtFullHeartTrick = keyValue[1] == "true"; break; case "addBuckRoundAtLostContra": ruleSet.AddBuckRoundAtLostContra = keyValue[1] == "true"; break; case "addBuckRoundAtZeroGame": ruleSet.AddBuckRoundAtZeroGame = keyValue[1] == "true"; break; } } } } } } var founder = users.FirstOrDefault(user => user.Token == message.Token); gameControllers.Add(new GameController(sendService, users, clientConnectionControllers, newTableID, name, password, hidden, founder, ruleSet)); founder.TableID = newTableID; sendService.SendTo(clientConnectionControllers.Select(c => c.Socket), new ServerMessage { Type = Message.MessageType.Meta, SubType = "tablesUpdated" }); } catch (JsonException) { // drop? } } }
protected void GenerateIndicatorPanelDetail(RiskRuleCategory category, HealthcheckRiskRule rule) { string safeRuleId = rule.RiskId.Replace("$", "dollar"); GenerateAccordionDetail("rules" + safeRuleId, "rules" + category.ToString(), rule.Rationale, rule.Points, true, () => { var hcrule = RuleSet<T>.GetRuleFromID(rule.RiskId); if (hcrule == null) { } else { Add("<h3>"); Add(hcrule.Title); Add("</h3>\r\n<strong>Description:</strong><p class=\"text-justify\">"); Add(NewLineToBR(hcrule.Description)); Add("</p>\r\n<strong>Technical explanation:</strong><p class=\"text-justify\">"); Add(NewLineToBR(hcrule.TechnicalExplanation)); Add("</p>\r\n<strong>Advised solution:</strong><p class=\"text-justify\">"); Add(NewLineToBR(hcrule.Solution)); Add("</p>\r\n<strong>Points:</strong><p>"); Add(NewLineToBR(hcrule.GetComputationModelString())); Add("</p>\r\n"); if (!String.IsNullOrEmpty(hcrule.Documentation)) { Add("<strong>Documentation:</strong><p>"); Add(hcrule.Documentation); Add("</p>"); } } if ((rule.Details != null && rule.Details.Count > 0) || (hcrule != null && !String.IsNullOrEmpty(hcrule.ReportLocation))) { Add("<strong>Details:</strong>"); if (!String.IsNullOrEmpty(hcrule.ReportLocation)) { Add("<p>"); Add(hcrule.ReportLocation); Add("</p>"); } if (rule.Details != null && rule.Details.Count > 0 && !string.IsNullOrEmpty(rule.Details[0])) { var test = rule.Details[0].Replace("Domain controller:","Domain_controller:").Split(' '); if (test.Length > 1 && test[0].EndsWith(":")) { var tokens = new List<string>(); for (int i = 0; i < test.Length; i++) { if (!string.IsNullOrEmpty(test[i]) && test[i].EndsWith(":")) { tokens.Add(test[i]); } } Add(@"<div class=""row""> <div class=""col-md-12 table-responsive""> <table class=""table table-striped table-bordered""> <thead><tr>"); foreach(var token in tokens) { Add("<th>"); AddEncoded(token.Replace("Domain_controller:", "Domain controller:").Substring(0, token.Length - 1)); Add("</th>"); } Add("</tr></thead><tbody>"); foreach (var d in rule.Details) { if (string.IsNullOrEmpty(d)) continue; Add("<tr>"); var t = d.Replace("Domain controller:", "Domain_controller:").Split(' '); for (int i = 0, j = 0; i < t.Length && j <= tokens.Count; i++) { if (j < tokens.Count && t[i] == tokens[j]) { j++; if (j != 0) Add("</td>"); Add("<td>"); } else { Add(t[i]); Add(" "); } } Add("</td>"); Add("</tr>"); } Add("</tbody></table></div></div>"); } else { Add("<p>"); Add(String.Join("<br>\r\n", rule.Details.ToArray())); Add("</p>"); } } } }); }
private RuleEngine CreateRuleEngine(RuleSet ruleSet) { return(new RuleEngine(ruleSet, GetValidation(ruleSet, typeof(SampleFlow.FlowEntity)))); }
protected void GenerateRiskModelPanel(List<HealthcheckRiskRule> rules, int numberOfDomain = 1) { Add(@" <div class=""row d-print-none""><div class=""col-lg-12""> <a data-toggle=""collapse"" data-target=""#riskModel""> <h2>Risk model</h2> </a> </div></div> <div class=""row collapse show d-print-none"" id=""riskModel""> <div class=""col-md-12 table-responsive""> <table class=""model_table""> <thead><tr><th>Stale Objects</th><th>Privileged accounts</th><th>Trusts</th><th>Anomalies</th></tr></thead> <tbody> "); var riskmodel = new Dictionary<RiskRuleCategory, List<RiskModelCategory>>(); foreach (RiskRuleCategory category in Enum.GetValues(typeof(RiskRuleCategory))) { riskmodel[category] = new List<RiskModelCategory>(); } for (int j = 0; j < 4; j++) { for (int i = 0; ; i++) { int id = (1000 * j + 1000 + i); if (Enum.IsDefined(typeof(RiskModelCategory), id)) { riskmodel[(RiskRuleCategory)j].Add((RiskModelCategory)id); } else break; } } foreach (RiskRuleCategory category in Enum.GetValues(typeof(RiskRuleCategory))) { riskmodel[category].Sort( (RiskModelCategory a, RiskModelCategory b) => { return string.Compare(ReportHelper.GetEnumDescription(a), ReportHelper.GetEnumDescription(b)); }); } for (int i = 0; ; i++) { string line = "<tr>"; bool HasValue = false; foreach (RiskRuleCategory category in Enum.GetValues(typeof(RiskRuleCategory))) { if (i < riskmodel[category].Count) { HasValue = true; RiskModelCategory model = riskmodel[category][i]; int score = 0; int numrules = 0; List<HealthcheckRiskRule> rulematched = new List<HealthcheckRiskRule>(); foreach (HealthcheckRiskRule rule in rules) { if (rule.Model == model) { numrules++; score += rule.Points; rulematched.Add(rule); } } string tdclass = ""; if (numrules == 0) { tdclass = "model_good"; } else if (score == 0) { tdclass = "model_info"; } else if (score <= 10 * numberOfDomain) { tdclass = "model_toimprove"; } else if (score <= 30 * numberOfDomain) { tdclass = "model_warning"; } else { tdclass = "model_danger"; } string tooltip = "Rules: " + numrules + " Score: " + (numberOfDomain == 0? 100 : score / numberOfDomain); string tooltipdetail = null; string modelstring = ReportHelper.GetEnumDescription(model); rulematched.Sort((HealthcheckRiskRule a, HealthcheckRiskRule b) => { return a.Points.CompareTo(b.Points); }); foreach (var rule in rulematched) { tooltipdetail += ReportHelper.Encode(rule.Rationale) + "<br>"; var hcrule = RuleSet<T>.GetRuleFromID(rule.RiskId); if (hcrule != null && !string.IsNullOrEmpty(hcrule.ReportLocation)) { tooltipdetail += "<small class='text-muted'>" + ReportHelper.Encode(hcrule.ReportLocation) + "</small><br>"; } } line += "<td class=\"model_cell " + tdclass + "\"><div class=\"div_model\" placement=\"auto right\" data-toggle=\"popover\" title=\"" + tooltip + "\" data-html=\"true\" data-content=\"" + (String.IsNullOrEmpty(tooltipdetail) ? "No rule matched" : "<p>" + tooltipdetail + "</p>") + "\"><span class=\"small\">" + modelstring + "</span></div></td>"; } else line += "<td class=\"model_empty_cell\"></td>"; } line += "</tr>"; if (HasValue) Add(line); else break; } Add(@" </tbody> </table> </div> <div class=""col-md-12"" id=""maturityModel""> Legend: <br> <i class=""risk_model_none""> </i> score is 0 - no risk identified but some improvements detected<br> <i class=""risk_model_low""> </i> score between 1 and 10 - a few actions have been identified<br> <i class=""risk_model_medium""> </i> score between 10 and 30 - rules should be looked with attention<br> <i class=""risk_model_high""> </i> score higher than 30 - major risks identified </div> </div>"); }
public CheckConfiguration(IReadOnlyList <string> inputPaths, string?reportPath, bool quiet, HashSet <int> suppressErrorIDs, bool verbose, RevocationChecking revocationMode, string?extract, RuleSet ruleSet) { InputPaths = inputPaths; ReportPath = reportPath; Quiet = quiet; SuppressErrorIDs = suppressErrorIDs; Verbose = verbose; RevocationMode = revocationMode; ExtractPath = extract; RuleSet = ruleSet; }
public void RegisterRuleSet(RuleSet ruleSet, string path) { this.savedRuleSets[path] = ruleSet; this.fileSystem.AddFile(path, new MockFileData("")); }
public void RegisterRuleSet(RuleSet ruleSet) { this.RegisterRuleSet(ruleSet, ruleSet.FilePath); }
public RuleResult(RuleSet rule, int start, string value) { Rule = rule; Start = start; Value = value; }
/// <summary> /// Add default and/or custom rules paths /// Iterate paths and add to ruleset /// </summary> void ConfigRules() { WriteOnce.SafeLog("AnalyzeCommand::ConfigRules", LogLevel.Trace); RuleSet rulesSet = new RuleSet(_arg_logger); List <string> rulePaths = new List <string>(); if (!_arg_ignoreDefaultRules) { Assembly assembly = Assembly.GetExecutingAssembly(); string[] resourceName = assembly.GetManifestResourceNames(); string filePath = "Microsoft.ApplicationInspector.Commands.defaultRules.json"; Stream resource = assembly.GetManifestResourceStream(filePath); using (StreamReader file = new StreamReader(resource)) { rulesSet.AddString(file.ReadToEnd(), filePath, null); } } if (!string.IsNullOrEmpty(_arg_customRulesPath)) { rulePaths.Add(_arg_customRulesPath); } foreach (string rulePath in rulePaths) { if (Directory.Exists(rulePath)) { rulesSet.AddDirectory(rulePath); } else if (File.Exists(rulePath)) { rulesSet.AddFile(rulePath); } else { throw new OpException(ErrMsg.FormatString(ErrMsg.ID.CMD_INVALID_RULE_PATH, rulePath)); } } //error check based on ruleset not path enumeration if (rulesSet.Count() == 0) { throw new OpException(ErrMsg.GetString(ErrMsg.ID.CMD_NORULES_SPECIFIED)); } //instantiate a RuleProcessor with the added rules and exception for dependency _rulesProcessor = new RuleProcessor(rulesSet, _arg_confidence, _arg_outputUniqueTagsOnly, _arg_simpleTagsOnly, _arg_logger); if (_arg_outputUniqueTagsOnly) { List <TagException> tagExceptions; if (File.Exists(Utils.GetPath(Utils.AppPath.tagCounterPref))) { tagExceptions = JsonConvert.DeserializeObject <List <TagException> >(File.ReadAllText(Utils.GetPath(Utils.AppPath.tagCounterPref))); string[] exceptions = new string[tagExceptions.Count]; for (int i = 0; i < tagExceptions.Count; i++) { exceptions[i] = tagExceptions[i].Tag; } _rulesProcessor.UniqueTagExceptions = exceptions; } } _appProfile = new AppProfile(_arg_sourcePath, rulePaths, false, _arg_simpleTagsOnly, _arg_outputUniqueTagsOnly, _arg_autoBrowserOpen); _appProfile.Args = "analyze -f " + _arg_fileFormat + " -u " + _arg_outputUniqueTagsOnly.ToString().ToLower() + " -v " + WriteOnce.Verbosity.ToString() + " -x " + _arg_confidence + " -i " + _arg_ignoreDefaultRules.ToString().ToLower(); }
public void InvalidRuleFileFailTest2() { RuleSet ruleset = RuleSet.FromFile(null, null); }